Show More
@@ -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,474 +1,503 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Display formatters. |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | Authors: |
|
5 | Authors: | |
6 |
|
6 | |||
7 | * Robert Kern |
|
7 | * Robert Kern | |
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (c) 2010, IPython Development Team. |
|
11 | # Copyright (c) 2010, IPython Development Team. | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the Modified BSD License. |
|
13 | # Distributed under the terms of the Modified BSD License. | |
14 | # |
|
14 | # | |
15 | # 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. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | # Stdlib imports |
|
22 | # Stdlib imports | |
23 | import abc |
|
23 | import abc | |
24 | # We must use StringIO, as cStringIO doesn't handle unicode properly. |
|
24 | # We must use StringIO, as cStringIO doesn't handle unicode properly. | |
25 | from StringIO import StringIO |
|
25 | from StringIO import StringIO | |
26 |
|
26 | |||
27 | # Our own imports |
|
27 | # Our own imports | |
28 | from IPython.config.configurable import Configurable |
|
28 | from IPython.config.configurable import Configurable | |
29 | from IPython.external import pretty |
|
29 | from IPython.external import pretty | |
30 | from IPython.utils.traitlets import Bool, Dict, Int, Str |
|
30 | from IPython.utils.traitlets import Bool, Dict, Int, Str | |
31 |
|
31 | |||
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # The main DisplayFormatter class |
|
34 | # The main DisplayFormatter class | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | class DisplayFormatter(Configurable): |
|
38 | class DisplayFormatter(Configurable): | |
39 |
|
39 | |||
|
40 | # When set to true only the default plain text formatter will be used. | |||
|
41 | plain_text_only = Bool(False, config=True) | |||
|
42 | ||||
40 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
43 | # A dict of formatter whose keys are format types (MIME types) and whose | |
41 | # values are subclasses of BaseFormatter. |
|
44 | # values are subclasses of BaseFormatter. | |
42 | formatters = Dict(config=True) |
|
45 | formatters = Dict(config=True) | |
43 | def _formatters_default(self): |
|
46 | def _formatters_default(self): | |
44 | """Activate the default formatters.""" |
|
47 | """Activate the default formatters.""" | |
45 | formatter_classes = [ |
|
48 | formatter_classes = [ | |
46 | PlainTextFormatter, |
|
49 | PlainTextFormatter, | |
47 | HTMLFormatter, |
|
50 | HTMLFormatter, | |
48 | SVGFormatter, |
|
51 | SVGFormatter, | |
49 | PNGFormatter, |
|
52 | PNGFormatter, | |
50 | LatexFormatter, |
|
53 | LatexFormatter, | |
51 | JSONFormatter |
|
54 | JSONFormatter | |
52 | ] |
|
55 | ] | |
53 | d = {} |
|
56 | d = {} | |
54 | for cls in formatter_classes: |
|
57 | for cls in formatter_classes: | |
55 | f = cls(config=self.config) |
|
58 | f = cls(config=self.config) | |
56 | d[f.format_type] = f |
|
59 | d[f.format_type] = f | |
57 | return d |
|
60 | return d | |
58 |
|
61 | |||
59 | def format(self, obj, include=None, exclude=None): |
|
62 | def format(self, obj, include=None, exclude=None): | |
60 | """Return a format data dict for an object. |
|
63 | """Return a format data dict for an object. | |
61 |
|
64 | |||
62 | By default all format types will be computed. |
|
65 | By default all format types will be computed. | |
63 |
|
66 | |||
64 | The following MIME types are currently implemented: |
|
67 | The following MIME types are currently implemented: | |
65 |
|
68 | |||
66 | * text/plain |
|
69 | * text/plain | |
67 | * text/html |
|
70 | * text/html | |
68 | * text/latex |
|
71 | * text/latex | |
69 | * application/json |
|
72 | * application/json | |
70 | * image/png |
|
73 | * image/png | |
71 | * immage/svg+xml |
|
74 | * immage/svg+xml | |
72 |
|
75 | |||
73 | Parameters |
|
76 | Parameters | |
74 | ---------- |
|
77 | ---------- | |
75 | obj : object |
|
78 | obj : object | |
76 | The Python object whose format data will be computed. |
|
79 | The Python object whose format data will be computed. | |
77 |
|
80 | |||
78 | Returns |
|
81 | Returns | |
79 | ------- |
|
82 | ------- | |
80 | format_dict : dict |
|
83 | format_dict : dict | |
81 | A dictionary of key/value pairs, one or each format that was |
|
84 | A dictionary of key/value pairs, one or each format that was | |
82 | generated for the object. The keys are the format types, which |
|
85 | generated for the object. The keys are the format types, which | |
83 | will usually be MIME type strings and the values and JSON'able |
|
86 | will usually be MIME type strings and the values and JSON'able | |
84 | data structure containing the raw data for the representation in |
|
87 | data structure containing the raw data for the representation in | |
85 | that format. |
|
88 | that format. | |
86 | include : list or tuple, optional |
|
89 | include : list or tuple, optional | |
87 | A list of format type strings (MIME types) to include in the |
|
90 | A list of format type strings (MIME types) to include in the | |
88 | format data dict. If this is set *only* the format types included |
|
91 | format data dict. If this is set *only* the format types included | |
89 | in this list will be computed. |
|
92 | in this list will be computed. | |
90 | exclude : list or tuple, optional |
|
93 | exclude : list or tuple, optional | |
91 | A list of format type string (MIME types) to exclue in the format |
|
94 | A list of format type string (MIME types) to exclue in the format | |
92 | data dict. If this is set all format types will be computed, |
|
95 | data dict. If this is set all format types will be computed, | |
93 | except for those included in this argument. |
|
96 | except for those included in this argument. | |
94 | """ |
|
97 | """ | |
95 | format_dict = {} |
|
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 | ||||
96 | for format_type, formatter in self.formatters.items(): |
|
112 | for format_type, formatter in self.formatters.items(): | |
97 | if include is not None: |
|
113 | if include is not None: | |
98 | if format_type not in include: |
|
114 | if format_type not in include: | |
99 | continue |
|
115 | continue | |
100 | if exclude is not None: |
|
116 | if exclude is not None: | |
101 | if format_type in exclude: |
|
117 | if format_type in exclude: | |
102 | continue |
|
118 | continue | |
103 | try: |
|
119 | try: | |
104 | data = formatter(obj) |
|
120 | data = formatter(obj) | |
105 | except: |
|
121 | except: | |
106 | # FIXME: log the exception |
|
122 | # FIXME: log the exception | |
107 | raise |
|
123 | raise | |
108 | if data is not None: |
|
124 | if data is not None: | |
109 | format_dict[format_type] = data |
|
125 | format_dict[format_type] = data | |
110 | return format_dict |
|
126 | return format_dict | |
111 |
|
127 | |||
112 | @property |
|
128 | @property | |
113 | def format_types(self): |
|
129 | def format_types(self): | |
114 | """Return the format types (MIME types) of the active formatters.""" |
|
130 | """Return the format types (MIME types) of the active formatters.""" | |
115 | return self.formatters.keys() |
|
131 | return self.formatters.keys() | |
116 |
|
132 | |||
117 |
|
133 | |||
118 | #----------------------------------------------------------------------------- |
|
134 | #----------------------------------------------------------------------------- | |
119 | # Formatters for specific format types (text, html, svg, etc.) |
|
135 | # Formatters for specific format types (text, html, svg, etc.) | |
120 | #----------------------------------------------------------------------------- |
|
136 | #----------------------------------------------------------------------------- | |
121 |
|
137 | |||
122 |
|
138 | |||
123 | class FormatterABC(object): |
|
139 | class FormatterABC(object): | |
124 | """ Abstract base class for Formatters. |
|
140 | """ Abstract base class for Formatters. | |
125 |
|
141 | |||
126 | A formatter is a callable class that is responsible for computing the |
|
142 | A formatter is a callable class that is responsible for computing the | |
127 | raw format data for a particular format type (MIME type). For example, |
|
143 | raw format data for a particular format type (MIME type). For example, | |
128 | an HTML formatter would have a format type of `text/html` and would return |
|
144 | an HTML formatter would have a format type of `text/html` and would return | |
129 | the HTML representation of the object when called. |
|
145 | the HTML representation of the object when called. | |
130 | """ |
|
146 | """ | |
131 | __metaclass__ = abc.ABCMeta |
|
147 | __metaclass__ = abc.ABCMeta | |
132 |
|
148 | |||
133 | # The format type of the data returned, usually a MIME type. |
|
149 | # The format type of the data returned, usually a MIME type. | |
134 | format_type = 'text/plain' |
|
150 | format_type = 'text/plain' | |
135 |
|
151 | |||
|
152 | # Is the formatter enabled... | |||
|
153 | enabled = True | |||
|
154 | ||||
136 | @abc.abstractmethod |
|
155 | @abc.abstractmethod | |
137 | def __call__(self, obj): |
|
156 | def __call__(self, obj): | |
138 | """Return a JSON'able representation of the object. |
|
157 | """Return a JSON'able representation of the object. | |
139 |
|
158 | |||
140 | If the object cannot be formatted by this formatter, then return None |
|
159 | If the object cannot be formatted by this formatter, then return None | |
141 | """ |
|
160 | """ | |
142 | try: |
|
161 | try: | |
143 | return repr(obj) |
|
162 | return repr(obj) | |
144 | except TypeError: |
|
163 | except TypeError: | |
145 | return None |
|
164 | return None | |
146 |
|
165 | |||
147 |
|
166 | |||
148 | class BaseFormatter(Configurable): |
|
167 | class BaseFormatter(Configurable): | |
149 | """A base formatter class that is configurable. |
|
168 | """A base formatter class that is configurable. | |
150 |
|
169 | |||
151 | This formatter should usually be used as the base class of all formatters. |
|
170 | This formatter should usually be used as the base class of all formatters. | |
152 | It is a traited :class:`Configurable` class and includes an extensible |
|
171 | It is a traited :class:`Configurable` class and includes an extensible | |
153 | API for users to determine how their objects are formatted. The following |
|
172 | API for users to determine how their objects are formatted. The following | |
154 | logic is used to find a function to format an given object. |
|
173 | logic is used to find a function to format an given object. | |
155 |
|
174 | |||
156 | 1. The object is introspected to see if it has a method with the name |
|
175 | 1. The object is introspected to see if it has a method with the name | |
157 | :attr:`print_method`. If is does, that object is passed to that method |
|
176 | :attr:`print_method`. If is does, that object is passed to that method | |
158 | for formatting. |
|
177 | for formatting. | |
159 | 2. If no print method is found, three internal dictionaries are consulted |
|
178 | 2. If no print method is found, three internal dictionaries are consulted | |
160 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
179 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
161 | and :attr:`deferred_printers`. |
|
180 | and :attr:`deferred_printers`. | |
162 |
|
181 | |||
163 | Users should use these dictionarie to register functions that will be used |
|
182 | Users should use these dictionarie to register functions that will be used | |
164 | to compute the format data for their objects (if those objects don't have |
|
183 | to compute the format data for their objects (if those objects don't have | |
165 | the special print methods). The easiest way of using these dictionaries |
|
184 | the special print methods). The easiest way of using these dictionaries | |
166 | is through the :meth:`for_type` and :meth:`for_type_by_name` methods. |
|
185 | is through the :meth:`for_type` and :meth:`for_type_by_name` methods. | |
167 |
|
186 | |||
168 | If no function/callable is found to compute the format data, ``None`` is |
|
187 | If no function/callable is found to compute the format data, ``None`` is | |
169 | returned and this format type is not used. |
|
188 | returned and this format type is not used. | |
170 | """ |
|
189 | """ | |
171 |
|
190 | |||
172 | format_type = Str('text/plain') |
|
191 | format_type = Str('text/plain') | |
173 |
|
192 | |||
|
193 | enabled = Bool(True, config=True) | |||
|
194 | ||||
174 | print_method = Str('__repr__') |
|
195 | print_method = Str('__repr__') | |
175 |
|
196 | |||
176 | # The singleton printers. |
|
197 | # The singleton printers. | |
177 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
198 | # Maps the IDs of the builtin singleton objects to the format functions. | |
178 | singleton_printers = Dict(config=True) |
|
199 | singleton_printers = Dict(config=True) | |
179 | def _singleton_printers_default(self): |
|
200 | def _singleton_printers_default(self): | |
180 | return {} |
|
201 | return {} | |
181 |
|
202 | |||
182 | # The type-specific printers. |
|
203 | # The type-specific printers. | |
183 | # Map type objects to the format functions. |
|
204 | # Map type objects to the format functions. | |
184 | type_printers = Dict(config=True) |
|
205 | type_printers = Dict(config=True) | |
185 | def _type_printers_default(self): |
|
206 | def _type_printers_default(self): | |
186 | return {} |
|
207 | return {} | |
187 |
|
208 | |||
188 | # The deferred-import type-specific printers. |
|
209 | # The deferred-import type-specific printers. | |
189 | # Map (modulename, classname) pairs to the format functions. |
|
210 | # Map (modulename, classname) pairs to the format functions. | |
190 | deferred_printers = Dict(config=True) |
|
211 | deferred_printers = Dict(config=True) | |
191 | def _deferred_printers_default(self): |
|
212 | def _deferred_printers_default(self): | |
192 | return {} |
|
213 | return {} | |
193 |
|
214 | |||
194 | def __call__(self, obj): |
|
215 | def __call__(self, obj): | |
195 | """Compute the format for an object.""" |
|
216 | """Compute the format for an object.""" | |
196 | obj_id = id(obj) |
|
217 | if self.enabled: | |
197 | try: |
|
218 | obj_id = id(obj) | |
198 | obj_class = getattr(obj, '__class__', None) or type(obj) |
|
|||
199 | if hasattr(obj_class, self.print_method): |
|
|||
200 | printer = getattr(obj_class, self.print_method) |
|
|||
201 | return printer(obj) |
|
|||
202 | try: |
|
219 | try: | |
203 | printer = self.singleton_printers[obj_id] |
|
220 | obj_class = getattr(obj, '__class__', None) or type(obj) | |
204 | except (TypeError, KeyError): |
|
221 | if hasattr(obj_class, self.print_method): | |
205 | pass |
|
222 | printer = getattr(obj_class, self.print_method) | |
206 | else: |
|
223 | return printer(obj) | |
207 |
|
|
224 | try: | |
208 | for cls in pretty._get_mro(obj_class): |
|
225 | printer = self.singleton_printers[obj_id] | |
209 | if cls in self.type_printers: |
|
226 | except (TypeError, KeyError): | |
210 | return self.type_printers[cls](obj) |
|
227 | pass | |
211 | else: |
|
228 | else: | |
212 | printer = self._in_deferred_types(cls) |
|
229 | return printer(obj) | |
213 | if printer is not None: |
|
230 | for cls in pretty._get_mro(obj_class): | |
214 |
|
|
231 | if cls in self.type_printers: | |
|
232 | return self.type_printers[cls](obj) | |||
|
233 | else: | |||
|
234 | printer = self._in_deferred_types(cls) | |||
|
235 | if printer is not None: | |||
|
236 | return printer(obj) | |||
|
237 | return None | |||
|
238 | except Exception: | |||
|
239 | pass | |||
|
240 | else: | |||
215 | return None |
|
241 | return None | |
216 | except Exception: |
|
|||
217 | pass |
|
|||
218 |
|
242 | |||
219 | def for_type(self, typ, func): |
|
243 | def for_type(self, typ, func): | |
220 | """Add a format function for a given type. |
|
244 | """Add a format function for a given type. | |
221 |
|
245 | |||
222 | Parameteres |
|
246 | Parameteres | |
223 | ----------- |
|
247 | ----------- | |
224 | typ : class |
|
248 | typ : class | |
225 | The class of the object that will be formatted using `func`. |
|
249 | The class of the object that will be formatted using `func`. | |
226 | func : callable |
|
250 | func : callable | |
227 | The callable that will be called to compute the format data. The |
|
251 | The callable that will be called to compute the format data. The | |
228 | call signature of this function is simple, it must take the |
|
252 | call signature of this function is simple, it must take the | |
229 | object to be formatted and return the raw data for the given |
|
253 | object to be formatted and return the raw data for the given | |
230 | format. Subclasses may use a different call signature for the |
|
254 | format. Subclasses may use a different call signature for the | |
231 | `func` argument. |
|
255 | `func` argument. | |
232 | """ |
|
256 | """ | |
233 | oldfunc = self.type_printers.get(typ, None) |
|
257 | oldfunc = self.type_printers.get(typ, None) | |
234 | if func is not None: |
|
258 | if func is not None: | |
235 | # To support easy restoration of old printers, we need to ignore |
|
259 | # To support easy restoration of old printers, we need to ignore | |
236 | # Nones. |
|
260 | # Nones. | |
237 | self.type_printers[typ] = func |
|
261 | self.type_printers[typ] = func | |
238 | return oldfunc |
|
262 | return oldfunc | |
239 |
|
263 | |||
240 | def for_type_by_name(self, type_module, type_name, func): |
|
264 | def for_type_by_name(self, type_module, type_name, func): | |
241 | """Add a format function for a type specified by the full dotted |
|
265 | """Add a format function for a type specified by the full dotted | |
242 | module and name of the type, rather than the type of the object. |
|
266 | module and name of the type, rather than the type of the object. | |
243 |
|
267 | |||
244 | Parameters |
|
268 | Parameters | |
245 | ---------- |
|
269 | ---------- | |
246 | type_module : str |
|
270 | type_module : str | |
247 | The full dotted name of the module the type is defined in, like |
|
271 | The full dotted name of the module the type is defined in, like | |
248 | ``numpy``. |
|
272 | ``numpy``. | |
249 | type_name : str |
|
273 | type_name : str | |
250 | The name of the type (the class name), like ``dtype`` |
|
274 | The name of the type (the class name), like ``dtype`` | |
251 | func : callable |
|
275 | func : callable | |
252 | The callable that will be called to compute the format data. The |
|
276 | The callable that will be called to compute the format data. The | |
253 | call signature of this function is simple, it must take the |
|
277 | call signature of this function is simple, it must take the | |
254 | object to be formatted and return the raw data for the given |
|
278 | object to be formatted and return the raw data for the given | |
255 | format. Subclasses may use a different call signature for the |
|
279 | format. Subclasses may use a different call signature for the | |
256 | `func` argument. |
|
280 | `func` argument. | |
257 | """ |
|
281 | """ | |
258 | key = (type_module, type_name) |
|
282 | key = (type_module, type_name) | |
259 | oldfunc = self.deferred_printers.get(key, None) |
|
283 | oldfunc = self.deferred_printers.get(key, None) | |
260 | if func is not None: |
|
284 | if func is not None: | |
261 | # To support easy restoration of old printers, we need to ignore |
|
285 | # To support easy restoration of old printers, we need to ignore | |
262 | # Nones. |
|
286 | # Nones. | |
263 | self.deferred_printers[key] = func |
|
287 | self.deferred_printers[key] = func | |
264 | return oldfunc |
|
288 | return oldfunc | |
265 |
|
289 | |||
266 | def _in_deferred_types(self, cls): |
|
290 | def _in_deferred_types(self, cls): | |
267 | """ |
|
291 | """ | |
268 | Check if the given class is specified in the deferred type registry. |
|
292 | Check if the given class is specified in the deferred type registry. | |
269 |
|
293 | |||
270 | Returns the printer from the registry if it exists, and None if the |
|
294 | Returns the printer from the registry if it exists, and None if the | |
271 | class is not in the registry. Successful matches will be moved to the |
|
295 | class is not in the registry. Successful matches will be moved to the | |
272 | regular type registry for future use. |
|
296 | regular type registry for future use. | |
273 | """ |
|
297 | """ | |
274 | mod = getattr(cls, '__module__', None) |
|
298 | mod = getattr(cls, '__module__', None) | |
275 | name = getattr(cls, '__name__', None) |
|
299 | name = getattr(cls, '__name__', None) | |
276 | key = (mod, name) |
|
300 | key = (mod, name) | |
277 | printer = None |
|
301 | printer = None | |
278 | if key in self.deferred_printers: |
|
302 | if key in self.deferred_printers: | |
279 | # Move the printer over to the regular registry. |
|
303 | # Move the printer over to the regular registry. | |
280 | printer = self.deferred_printers.pop(key) |
|
304 | printer = self.deferred_printers.pop(key) | |
281 | self.type_printers[cls] = printer |
|
305 | self.type_printers[cls] = printer | |
282 | return printer |
|
306 | return printer | |
283 |
|
307 | |||
|
308 | ||||
284 | class PlainTextFormatter(BaseFormatter): |
|
309 | class PlainTextFormatter(BaseFormatter): | |
285 | """The default pretty-printer. |
|
310 | """The default pretty-printer. | |
286 |
|
311 | |||
287 | This uses :mod:`IPython.external.pretty` to compute the format data of |
|
312 | This uses :mod:`IPython.external.pretty` to compute the format data of | |
288 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
313 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
289 | See the documentation of :mod:`IPython.external.pretty` for details on |
|
314 | See the documentation of :mod:`IPython.external.pretty` for details on | |
290 | how to write pretty printers. Here is a simple example:: |
|
315 | how to write pretty printers. Here is a simple example:: | |
291 |
|
316 | |||
292 | def dtype_pprinter(obj, p, cycle): |
|
317 | def dtype_pprinter(obj, p, cycle): | |
293 | if cycle: |
|
318 | if cycle: | |
294 | return p.text('dtype(...)') |
|
319 | return p.text('dtype(...)') | |
295 | if hasattr(obj, 'fields'): |
|
320 | if hasattr(obj, 'fields'): | |
296 | if obj.fields is None: |
|
321 | if obj.fields is None: | |
297 | p.text(repr(obj)) |
|
322 | p.text(repr(obj)) | |
298 | else: |
|
323 | else: | |
299 | p.begin_group(7, 'dtype([') |
|
324 | p.begin_group(7, 'dtype([') | |
300 | for i, field in enumerate(obj.descr): |
|
325 | for i, field in enumerate(obj.descr): | |
301 | if i > 0: |
|
326 | if i > 0: | |
302 | p.text(',') |
|
327 | p.text(',') | |
303 | p.breakable() |
|
328 | p.breakable() | |
304 | p.pretty(field) |
|
329 | p.pretty(field) | |
305 | p.end_group(7, '])') |
|
330 | p.end_group(7, '])') | |
306 | """ |
|
331 | """ | |
307 |
|
332 | |||
308 | # The format type of data returned. |
|
333 | # The format type of data returned. | |
309 | format_type = Str('text/plain') |
|
334 | format_type = Str('text/plain') | |
310 |
|
335 | |||
|
336 | # This subclass ignores this attribute as it always need to return | |||
|
337 | # something. | |||
|
338 | enabled = Bool(True, config=False) | |||
|
339 | ||||
311 | # Look for a __pretty__ methods to use for pretty printing. |
|
340 | # Look for a __pretty__ methods to use for pretty printing. | |
312 | print_method = Str('__pretty__') |
|
341 | print_method = Str('__pretty__') | |
313 |
|
342 | |||
314 | # Whether to pretty-print or not. |
|
343 | # Whether to pretty-print or not. | |
315 | pprint = Bool(True, config=True) |
|
344 | pprint = Bool(True, config=True) | |
316 |
|
345 | |||
317 | # Whether to be verbose or not. |
|
346 | # Whether to be verbose or not. | |
318 | verbose = Bool(False, config=True) |
|
347 | verbose = Bool(False, config=True) | |
319 |
|
348 | |||
320 | # The maximum width. |
|
349 | # The maximum width. | |
321 | max_width = Int(79, config=True) |
|
350 | max_width = Int(79, config=True) | |
322 |
|
351 | |||
323 | # The newline character. |
|
352 | # The newline character. | |
324 | newline = Str('\n', config=True) |
|
353 | newline = Str('\n', config=True) | |
325 |
|
354 | |||
326 | # Use the default pretty printers from IPython.external.pretty. |
|
355 | # Use the default pretty printers from IPython.external.pretty. | |
327 | def _singleton_printers_default(self): |
|
356 | def _singleton_printers_default(self): | |
328 | return pretty._singleton_pprinters.copy() |
|
357 | return pretty._singleton_pprinters.copy() | |
329 |
|
358 | |||
330 | def _type_printers_default(self): |
|
359 | def _type_printers_default(self): | |
331 | return pretty._type_pprinters.copy() |
|
360 | return pretty._type_pprinters.copy() | |
332 |
|
361 | |||
333 | def _deferred_printers_default(self): |
|
362 | def _deferred_printers_default(self): | |
334 | return pretty._deferred_type_pprinters.copy() |
|
363 | return pretty._deferred_type_pprinters.copy() | |
335 |
|
364 | |||
336 | #### FormatterABC interface #### |
|
365 | #### FormatterABC interface #### | |
337 |
|
366 | |||
338 | def __call__(self, obj): |
|
367 | def __call__(self, obj): | |
339 | """Compute the pretty representation of the object.""" |
|
368 | """Compute the pretty representation of the object.""" | |
340 | if not self.pprint: |
|
369 | if not self.pprint: | |
341 | try: |
|
370 | try: | |
342 | return repr(obj) |
|
371 | return repr(obj) | |
343 | except TypeError: |
|
372 | except TypeError: | |
344 | return '' |
|
373 | return '' | |
345 | else: |
|
374 | else: | |
346 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
375 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
347 | stream = StringIO() |
|
376 | stream = StringIO() | |
348 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
377 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
349 | self.max_width, self.newline, |
|
378 | self.max_width, self.newline, | |
350 | singleton_pprinters=self.singleton_printers, |
|
379 | singleton_pprinters=self.singleton_printers, | |
351 | type_pprinters=self.type_printers, |
|
380 | type_pprinters=self.type_printers, | |
352 | deferred_pprinters=self.deferred_printers) |
|
381 | deferred_pprinters=self.deferred_printers) | |
353 | printer.pretty(obj) |
|
382 | printer.pretty(obj) | |
354 | printer.flush() |
|
383 | printer.flush() | |
355 | return stream.getvalue() |
|
384 | return stream.getvalue() | |
356 |
|
385 | |||
357 |
|
386 | |||
358 | class HTMLFormatter(BaseFormatter): |
|
387 | class HTMLFormatter(BaseFormatter): | |
359 | """An HTML formatter. |
|
388 | """An HTML formatter. | |
360 |
|
389 | |||
361 | To define the callables that compute the HTML representation of your |
|
390 | To define the callables that compute the HTML representation of your | |
362 | objects, define a :meth:`__html__` method or use the :meth:`for_type` |
|
391 | objects, define a :meth:`__html__` method or use the :meth:`for_type` | |
363 | or :meth:`for_type_by_name` methods to register functions that handle |
|
392 | or :meth:`for_type_by_name` methods to register functions that handle | |
364 | this. |
|
393 | this. | |
365 | """ |
|
394 | """ | |
366 | format_type = Str('text/html') |
|
395 | format_type = Str('text/html') | |
367 |
|
396 | |||
368 | print_method = Str('__html__') |
|
397 | print_method = Str('__html__') | |
369 |
|
398 | |||
370 |
|
399 | |||
371 | class SVGFormatter(BaseFormatter): |
|
400 | class SVGFormatter(BaseFormatter): | |
372 | """An SVG formatter. |
|
401 | """An SVG formatter. | |
373 |
|
402 | |||
374 | To define the callables that compute the SVG representation of your |
|
403 | To define the callables that compute the SVG representation of your | |
375 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` |
|
404 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` | |
376 | or :meth:`for_type_by_name` methods to register functions that handle |
|
405 | or :meth:`for_type_by_name` methods to register functions that handle | |
377 | this. |
|
406 | this. | |
378 | """ |
|
407 | """ | |
379 | format_type = Str('image/svg+xml') |
|
408 | format_type = Str('image/svg+xml') | |
380 |
|
409 | |||
381 | print_method = Str('__svg__') |
|
410 | print_method = Str('__svg__') | |
382 |
|
411 | |||
383 |
|
412 | |||
384 | class PNGFormatter(BaseFormatter): |
|
413 | class PNGFormatter(BaseFormatter): | |
385 | """A PNG formatter. |
|
414 | """A PNG formatter. | |
386 |
|
415 | |||
387 | To define the callables that compute the PNG representation of your |
|
416 | To define the callables that compute the PNG representation of your | |
388 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` |
|
417 | objects, define a :meth:`__svg__` method or use the :meth:`for_type` | |
389 | or :meth:`for_type_by_name` methods to register functions that handle |
|
418 | or :meth:`for_type_by_name` methods to register functions that handle | |
390 | this. The raw data should be the base64 encoded raw png data. |
|
419 | this. The raw data should be the base64 encoded raw png data. | |
391 | """ |
|
420 | """ | |
392 | format_type = Str('image/png') |
|
421 | format_type = Str('image/png') | |
393 |
|
422 | |||
394 | print_method = Str('__png__') |
|
423 | print_method = Str('__png__') | |
395 |
|
424 | |||
396 |
|
425 | |||
397 | class LatexFormatter(BaseFormatter): |
|
426 | class LatexFormatter(BaseFormatter): | |
398 | """A LaTeX formatter. |
|
427 | """A LaTeX formatter. | |
399 |
|
428 | |||
400 | To define the callables that compute the LaTeX representation of your |
|
429 | To define the callables that compute the LaTeX representation of your | |
401 | objects, define a :meth:`__latex__` method or use the :meth:`for_type` |
|
430 | objects, define a :meth:`__latex__` method or use the :meth:`for_type` | |
402 | or :meth:`for_type_by_name` methods to register functions that handle |
|
431 | or :meth:`for_type_by_name` methods to register functions that handle | |
403 | this. |
|
432 | this. | |
404 | """ |
|
433 | """ | |
405 | format_type = Str('text/latex') |
|
434 | format_type = Str('text/latex') | |
406 |
|
435 | |||
407 | print_method = Str('__latex__') |
|
436 | print_method = Str('__latex__') | |
408 |
|
437 | |||
409 |
|
438 | |||
410 | class JSONFormatter(BaseFormatter): |
|
439 | class JSONFormatter(BaseFormatter): | |
411 | """A JSON string formatter. |
|
440 | """A JSON string formatter. | |
412 |
|
441 | |||
413 | To define the callables that compute the JSON string representation of |
|
442 | To define the callables that compute the JSON string representation of | |
414 | your objects, define a :meth:`__json__` method or use the :meth:`for_type` |
|
443 | your objects, define a :meth:`__json__` method or use the :meth:`for_type` | |
415 | or :meth:`for_type_by_name` methods to register functions that handle |
|
444 | or :meth:`for_type_by_name` methods to register functions that handle | |
416 | this. |
|
445 | this. | |
417 | """ |
|
446 | """ | |
418 | format_type = Str('application/json') |
|
447 | format_type = Str('application/json') | |
419 |
|
448 | |||
420 | print_method = Str('__json__') |
|
449 | print_method = Str('__json__') | |
421 |
|
450 | |||
422 |
|
451 | |||
423 | FormatterABC.register(BaseFormatter) |
|
452 | FormatterABC.register(BaseFormatter) | |
424 | FormatterABC.register(PlainTextFormatter) |
|
453 | FormatterABC.register(PlainTextFormatter) | |
425 | FormatterABC.register(HTMLFormatter) |
|
454 | FormatterABC.register(HTMLFormatter) | |
426 | FormatterABC.register(SVGFormatter) |
|
455 | FormatterABC.register(SVGFormatter) | |
427 | FormatterABC.register(PNGFormatter) |
|
456 | FormatterABC.register(PNGFormatter) | |
428 | FormatterABC.register(LatexFormatter) |
|
457 | FormatterABC.register(LatexFormatter) | |
429 | FormatterABC.register(JSONFormatter) |
|
458 | FormatterABC.register(JSONFormatter) | |
430 |
|
459 | |||
431 |
|
460 | |||
432 | def format_display_data(obj, include=None, exclude=None): |
|
461 | def format_display_data(obj, include=None, exclude=None): | |
433 | """Return a format data dict for an object. |
|
462 | """Return a format data dict for an object. | |
434 |
|
463 | |||
435 | By default all format types will be computed. |
|
464 | By default all format types will be computed. | |
436 |
|
465 | |||
437 | The following MIME types are currently implemented: |
|
466 | The following MIME types are currently implemented: | |
438 |
|
467 | |||
439 | * text/plain |
|
468 | * text/plain | |
440 | * text/html |
|
469 | * text/html | |
441 | * text/latex |
|
470 | * text/latex | |
442 | * application/json |
|
471 | * application/json | |
443 | * image/png |
|
472 | * image/png | |
444 | * immage/svg+xml |
|
473 | * immage/svg+xml | |
445 |
|
474 | |||
446 | Parameters |
|
475 | Parameters | |
447 | ---------- |
|
476 | ---------- | |
448 | obj : object |
|
477 | obj : object | |
449 | The Python object whose format data will be computed. |
|
478 | The Python object whose format data will be computed. | |
450 |
|
479 | |||
451 | Returns |
|
480 | Returns | |
452 | ------- |
|
481 | ------- | |
453 | format_dict : dict |
|
482 | format_dict : dict | |
454 | A dictionary of key/value pairs, one or each format that was |
|
483 | A dictionary of key/value pairs, one or each format that was | |
455 | generated for the object. The keys are the format types, which |
|
484 | generated for the object. The keys are the format types, which | |
456 | will usually be MIME type strings and the values and JSON'able |
|
485 | will usually be MIME type strings and the values and JSON'able | |
457 | data structure containing the raw data for the representation in |
|
486 | data structure containing the raw data for the representation in | |
458 | that format. |
|
487 | that format. | |
459 | include : list or tuple, optional |
|
488 | include : list or tuple, optional | |
460 | A list of format type strings (MIME types) to include in the |
|
489 | A list of format type strings (MIME types) to include in the | |
461 | format data dict. If this is set *only* the format types included |
|
490 | format data dict. If this is set *only* the format types included | |
462 | in this list will be computed. |
|
491 | in this list will be computed. | |
463 | exclude : list or tuple, optional |
|
492 | exclude : list or tuple, optional | |
464 | A list of format type string (MIME types) to exclue in the format |
|
493 | A list of format type string (MIME types) to exclue in the format | |
465 | data dict. If this is set all format types will be computed, |
|
494 | data dict. If this is set all format types will be computed, | |
466 | except for those included in this argument. |
|
495 | except for those included in this argument. | |
467 | """ |
|
496 | """ | |
468 | from IPython.core.interactiveshell import InteractiveShell |
|
497 | from IPython.core.interactiveshell import InteractiveShell | |
469 |
|
498 | |||
470 | InteractiveShell.instance().display_formatter.format( |
|
499 | InteractiveShell.instance().display_formatter.format( | |
471 | obj, |
|
500 | obj, | |
472 | include, |
|
501 | include, | |
473 | exclude |
|
502 | exclude | |
474 | ) |
|
503 | ) |
@@ -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,2556 +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.displaypub import DisplayPublisher | |
45 | from IPython.core.error import TryNext, UsageError |
|
45 | from IPython.core.error import TryNext, UsageError | |
46 | from IPython.core.extensions import ExtensionManager |
|
46 | from IPython.core.extensions import ExtensionManager | |
47 | 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 |
|
48 | from IPython.core.formatters import DisplayFormatter | |
49 | from IPython.core.history import HistoryManager |
|
49 | from IPython.core.history import HistoryManager | |
50 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
50 | from IPython.core.inputsplitter import IPythonInputSplitter | |
51 | from IPython.core.logger import Logger |
|
51 | from IPython.core.logger import Logger | |
52 | from IPython.core.magic import Magic |
|
52 | from IPython.core.magic import Magic | |
53 | from IPython.core.payload import PayloadManager |
|
53 | from IPython.core.payload import PayloadManager | |
54 | from IPython.core.plugin import PluginManager |
|
54 | from IPython.core.plugin import PluginManager | |
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
56 | from IPython.external.Itpl import ItplNS |
|
56 | from IPython.external.Itpl import ItplNS | |
57 | from IPython.utils import PyColorize |
|
57 | from IPython.utils import PyColorize | |
58 | from IPython.utils import io |
|
58 | from IPython.utils import io | |
59 | from IPython.utils import pickleshare |
|
59 | from IPython.utils import pickleshare | |
60 | from IPython.utils.doctestreload import doctest_reload |
|
60 | from IPython.utils.doctestreload import doctest_reload | |
61 | from IPython.utils.io import ask_yes_no, rprint |
|
61 | from IPython.utils.io import ask_yes_no, rprint | |
62 | from IPython.utils.ipstruct import Struct |
|
62 | from IPython.utils.ipstruct import Struct | |
63 | 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 | |
64 | from IPython.utils.process import system, getoutput |
|
64 | from IPython.utils.process import system, getoutput | |
65 | from IPython.utils.strdispatch import StrDispatch |
|
65 | from IPython.utils.strdispatch import StrDispatch | |
66 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
66 | from IPython.utils.syspathcontext import prepended_to_syspath | |
67 | 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 | |
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
69 | List, Unicode, Instance, Type) |
|
69 | List, Unicode, Instance, Type) | |
70 | from IPython.utils.warn import warn, error, fatal |
|
70 | from IPython.utils.warn import warn, error, fatal | |
71 | import IPython.core.hooks |
|
71 | import IPython.core.hooks | |
72 |
|
72 | |||
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 | # Globals |
|
74 | # Globals | |
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Utilities |
|
81 | # Utilities | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | # 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 | |
85 | # overwrites it (like wx.py.PyShell does) |
|
85 | # overwrites it (like wx.py.PyShell does) | |
86 | raw_input_original = raw_input |
|
86 | raw_input_original = raw_input | |
87 |
|
87 | |||
88 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
89 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
90 |
|
90 | |||
91 | oldvalue = 0 |
|
91 | oldvalue = 0 | |
92 | try: |
|
92 | try: | |
93 | oldvalue = file.softspace |
|
93 | oldvalue = file.softspace | |
94 | except AttributeError: |
|
94 | except AttributeError: | |
95 | pass |
|
95 | pass | |
96 | try: |
|
96 | try: | |
97 | file.softspace = newvalue |
|
97 | file.softspace = newvalue | |
98 | except (AttributeError, TypeError): |
|
98 | except (AttributeError, TypeError): | |
99 | # "attribute-less object" or "read-only attributes" |
|
99 | # "attribute-less object" or "read-only attributes" | |
100 | pass |
|
100 | pass | |
101 | return oldvalue |
|
101 | return oldvalue | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def no_op(*a, **kw): pass |
|
104 | def no_op(*a, **kw): pass | |
105 |
|
105 | |||
106 | class SpaceInInput(Exception): pass |
|
106 | class SpaceInInput(Exception): pass | |
107 |
|
107 | |||
108 | class Bunch: pass |
|
108 | class Bunch: pass | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | def get_default_colors(): |
|
111 | def get_default_colors(): | |
112 | if sys.platform=='darwin': |
|
112 | if sys.platform=='darwin': | |
113 | return "LightBG" |
|
113 | return "LightBG" | |
114 | elif os.name=='nt': |
|
114 | elif os.name=='nt': | |
115 | return 'Linux' |
|
115 | return 'Linux' | |
116 | else: |
|
116 | else: | |
117 | return 'Linux' |
|
117 | return 'Linux' | |
118 |
|
118 | |||
119 |
|
119 | |||
120 | class SeparateStr(Str): |
|
120 | class SeparateStr(Str): | |
121 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | """A Str subclass to validate separate_in, separate_out, etc. | |
122 |
|
122 | |||
123 | 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'. | |
124 | """ |
|
124 | """ | |
125 |
|
125 | |||
126 | def validate(self, obj, value): |
|
126 | def validate(self, obj, value): | |
127 | if value == '0': value = '' |
|
127 | if value == '0': value = '' | |
128 | value = value.replace('\\n','\n') |
|
128 | value = value.replace('\\n','\n') | |
129 | return super(SeparateStr, self).validate(obj, value) |
|
129 | return super(SeparateStr, self).validate(obj, value) | |
130 |
|
130 | |||
131 | class MultipleInstanceError(Exception): |
|
131 | class MultipleInstanceError(Exception): | |
132 | pass |
|
132 | pass | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
136 | # Main IPython class |
|
136 | # Main IPython class | |
137 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
138 |
|
138 | |||
139 | class InteractiveShell(Configurable, Magic): |
|
139 | class InteractiveShell(Configurable, Magic): | |
140 | """An enhanced, interactive shell for Python.""" |
|
140 | """An enhanced, interactive shell for Python.""" | |
141 |
|
141 | |||
142 | _instance = None |
|
142 | _instance = None | |
143 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
143 | autocall = Enum((0,1,2), default_value=1, config=True) | |
144 | # TODO: remove all autoindent logic and put into frontends. |
|
144 | # TODO: remove all autoindent logic and put into frontends. | |
145 | # 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. | |
146 | autoindent = CBool(True, config=True) |
|
146 | autoindent = CBool(True, config=True) | |
147 | automagic = CBool(True, config=True) |
|
147 | automagic = CBool(True, config=True) | |
148 | cache_size = Int(1000, config=True) |
|
148 | cache_size = Int(1000, config=True) | |
149 | color_info = CBool(True, config=True) |
|
149 | color_info = CBool(True, config=True) | |
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
151 | default_value=get_default_colors(), config=True) |
|
151 | default_value=get_default_colors(), config=True) | |
152 | debug = CBool(False, config=True) |
|
152 | debug = CBool(False, config=True) | |
153 | deep_reload = CBool(False, config=True) |
|
153 | deep_reload = CBool(False, config=True) | |
154 | display_formatter = Instance(DisplayFormatter) |
|
154 | display_formatter = Instance(DisplayFormatter) | |
155 | displayhook_class = Type(DisplayHook) |
|
155 | displayhook_class = Type(DisplayHook) | |
156 | display_pub_class = Type(DisplayPublisher) |
|
156 | display_pub_class = Type(DisplayPublisher) | |
157 |
|
157 | |||
158 | exit_now = CBool(False) |
|
158 | exit_now = CBool(False) | |
159 | # Monotonically increasing execution counter |
|
159 | # Monotonically increasing execution counter | |
160 | execution_count = Int(1) |
|
160 | execution_count = Int(1) | |
161 | filename = Str("<ipython console>") |
|
161 | filename = Str("<ipython console>") | |
162 | 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__ | |
163 |
|
163 | |||
164 | # Input splitter, to split entire cells of input into either individual |
|
164 | # Input splitter, to split entire cells of input into either individual | |
165 | # interactive statements or whole blocks. |
|
165 | # interactive statements or whole blocks. | |
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
167 | (), {}) |
|
167 | (), {}) | |
168 | logstart = CBool(False, config=True) |
|
168 | logstart = CBool(False, config=True) | |
169 | logfile = Str('', config=True) |
|
169 | logfile = Str('', config=True) | |
170 | logappend = Str('', config=True) |
|
170 | logappend = Str('', config=True) | |
171 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
171 | object_info_string_level = Enum((0,1,2), default_value=0, | |
172 | config=True) |
|
172 | config=True) | |
173 | pdb = CBool(False, config=True) |
|
173 | pdb = CBool(False, config=True) | |
174 |
|
174 | |||
175 | pprint = CBool(True, config=True) |
|
|||
176 | profile = Str('', config=True) |
|
175 | profile = Str('', config=True) | |
177 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
176 | prompt_in1 = Str('In [\\#]: ', config=True) | |
178 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
177 | prompt_in2 = Str(' .\\D.: ', config=True) | |
179 | prompt_out = Str('Out[\\#]: ', config=True) |
|
178 | prompt_out = Str('Out[\\#]: ', config=True) | |
180 | prompts_pad_left = CBool(True, config=True) |
|
179 | prompts_pad_left = CBool(True, config=True) | |
181 | quiet = CBool(False, config=True) |
|
180 | quiet = CBool(False, config=True) | |
182 |
|
181 | |||
183 | history_length = Int(10000, config=True) |
|
182 | history_length = Int(10000, config=True) | |
184 |
|
183 | |||
185 | # The readline stuff will eventually be moved to the terminal subclass |
|
184 | # The readline stuff will eventually be moved to the terminal subclass | |
186 | # 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. | |
187 | readline_use = CBool(True, config=True) |
|
186 | readline_use = CBool(True, config=True) | |
188 | readline_merge_completions = CBool(True, config=True) |
|
187 | readline_merge_completions = CBool(True, config=True) | |
189 | 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) | |
190 | readline_remove_delims = Str('-/~', config=True) |
|
189 | readline_remove_delims = Str('-/~', config=True) | |
191 | readline_parse_and_bind = List([ |
|
190 | readline_parse_and_bind = List([ | |
192 | 'tab: complete', |
|
191 | 'tab: complete', | |
193 | '"\C-l": clear-screen', |
|
192 | '"\C-l": clear-screen', | |
194 | 'set show-all-if-ambiguous on', |
|
193 | 'set show-all-if-ambiguous on', | |
195 | '"\C-o": tab-insert', |
|
194 | '"\C-o": tab-insert', | |
196 | '"\M-i": " "', |
|
195 | '"\M-i": " "', | |
197 | '"\M-o": "\d\d\d\d"', |
|
196 | '"\M-o": "\d\d\d\d"', | |
198 | '"\M-I": "\d\d\d\d"', |
|
197 | '"\M-I": "\d\d\d\d"', | |
199 | '"\C-r": reverse-search-history', |
|
198 | '"\C-r": reverse-search-history', | |
200 | '"\C-s": forward-search-history', |
|
199 | '"\C-s": forward-search-history', | |
201 | '"\C-p": history-search-backward', |
|
200 | '"\C-p": history-search-backward', | |
202 | '"\C-n": history-search-forward', |
|
201 | '"\C-n": history-search-forward', | |
203 | '"\e[A": history-search-backward', |
|
202 | '"\e[A": history-search-backward', | |
204 | '"\e[B": history-search-forward', |
|
203 | '"\e[B": history-search-forward', | |
205 | '"\C-k": kill-line', |
|
204 | '"\C-k": kill-line', | |
206 | '"\C-u": unix-line-discard', |
|
205 | '"\C-u": unix-line-discard', | |
207 | ], allow_none=False, config=True) |
|
206 | ], allow_none=False, config=True) | |
208 |
|
207 | |||
209 | # 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. | |
210 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
209 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
211 | separate_in = SeparateStr('\n', config=True) |
|
210 | separate_in = SeparateStr('\n', config=True) | |
212 | separate_out = SeparateStr('', config=True) |
|
211 | separate_out = SeparateStr('', config=True) | |
213 | separate_out2 = SeparateStr('', config=True) |
|
212 | separate_out2 = SeparateStr('', config=True) | |
214 | wildcards_case_sensitive = CBool(True, config=True) |
|
213 | wildcards_case_sensitive = CBool(True, config=True) | |
215 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
214 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
216 | default_value='Context', config=True) |
|
215 | default_value='Context', config=True) | |
217 |
|
216 | |||
218 | # Subcomponents of InteractiveShell |
|
217 | # Subcomponents of InteractiveShell | |
219 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
218 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
220 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
219 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
221 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
220 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
222 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
221 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
223 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
222 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
224 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
223 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
225 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
224 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
226 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
225 | history_manager = Instance('IPython.core.history.HistoryManager') | |
227 |
|
226 | |||
228 | # Private interface |
|
227 | # Private interface | |
229 | _post_execute = set() |
|
228 | _post_execute = set() | |
230 |
|
229 | |||
231 | def __init__(self, config=None, ipython_dir=None, |
|
230 | def __init__(self, config=None, ipython_dir=None, | |
232 | user_ns=None, user_global_ns=None, |
|
231 | user_ns=None, user_global_ns=None, | |
233 | custom_exceptions=((), None)): |
|
232 | custom_exceptions=((), None)): | |
234 |
|
233 | |||
235 | # This is where traits with a config_key argument are updated |
|
234 | # This is where traits with a config_key argument are updated | |
236 | # from the values on config. |
|
235 | # from the values on config. | |
237 | super(InteractiveShell, self).__init__(config=config) |
|
236 | super(InteractiveShell, self).__init__(config=config) | |
238 |
|
237 | |||
239 | # These are relatively independent and stateless |
|
238 | # These are relatively independent and stateless | |
240 | self.init_ipython_dir(ipython_dir) |
|
239 | self.init_ipython_dir(ipython_dir) | |
241 | self.init_instance_attrs() |
|
240 | self.init_instance_attrs() | |
242 | self.init_environment() |
|
241 | self.init_environment() | |
243 |
|
242 | |||
244 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
243 | # Create namespaces (user_ns, user_global_ns, etc.) | |
245 | self.init_create_namespaces(user_ns, user_global_ns) |
|
244 | self.init_create_namespaces(user_ns, user_global_ns) | |
246 | # 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 | |
247 | # something in self.user_ns, but before init_sys_modules, which |
|
246 | # something in self.user_ns, but before init_sys_modules, which | |
248 | # is the first thing to modify sys. |
|
247 | # is the first thing to modify sys. | |
249 | # 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 | |
250 | # 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 | |
251 | # is what we want to do. |
|
250 | # is what we want to do. | |
252 | self.save_sys_module_state() |
|
251 | self.save_sys_module_state() | |
253 | self.init_sys_modules() |
|
252 | self.init_sys_modules() | |
254 |
|
253 | |||
255 | self.init_history() |
|
254 | self.init_history() | |
256 | self.init_encoding() |
|
255 | self.init_encoding() | |
257 | self.init_prefilter() |
|
256 | self.init_prefilter() | |
258 |
|
257 | |||
259 | Magic.__init__(self, self) |
|
258 | Magic.__init__(self, self) | |
260 |
|
259 | |||
261 | self.init_syntax_highlighting() |
|
260 | self.init_syntax_highlighting() | |
262 | self.init_hooks() |
|
261 | self.init_hooks() | |
263 | self.init_pushd_popd_magic() |
|
262 | self.init_pushd_popd_magic() | |
264 | # 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 | |
265 | # because it and init_io have to come after init_readline. |
|
264 | # because it and init_io have to come after init_readline. | |
266 | self.init_user_ns() |
|
265 | self.init_user_ns() | |
267 | self.init_logger() |
|
266 | self.init_logger() | |
268 | self.init_alias() |
|
267 | self.init_alias() | |
269 | self.init_builtins() |
|
268 | self.init_builtins() | |
270 |
|
269 | |||
271 | # pre_config_initialization |
|
270 | # pre_config_initialization | |
272 |
|
271 | |||
273 | # The next section should contain everything that was in ipmaker. |
|
272 | # The next section should contain everything that was in ipmaker. | |
274 | self.init_logstart() |
|
273 | self.init_logstart() | |
275 |
|
274 | |||
276 | # The following was in post_config_initialization |
|
275 | # The following was in post_config_initialization | |
277 | self.init_inspector() |
|
276 | self.init_inspector() | |
278 | # init_readline() must come before init_io(), because init_io uses |
|
277 | # init_readline() must come before init_io(), because init_io uses | |
279 | # readline related things. |
|
278 | # readline related things. | |
280 | self.init_readline() |
|
279 | self.init_readline() | |
281 | # init_completer must come after init_readline, because it needs to |
|
280 | # init_completer must come after init_readline, because it needs to | |
282 | # 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 | |
283 | # completers, since the completion machinery can now operate |
|
282 | # completers, since the completion machinery can now operate | |
284 | # independently of readline (e.g. over the network) |
|
283 | # independently of readline (e.g. over the network) | |
285 | self.init_completer() |
|
284 | self.init_completer() | |
286 | # TODO: init_io() needs to happen before init_traceback handlers |
|
285 | # TODO: init_io() needs to happen before init_traceback handlers | |
287 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
286 | # because the traceback handlers hardcode the stdout/stderr streams. | |
288 | # This logic in in debugger.Pdb and should eventually be changed. |
|
287 | # This logic in in debugger.Pdb and should eventually be changed. | |
289 | self.init_io() |
|
288 | self.init_io() | |
290 | self.init_traceback_handlers(custom_exceptions) |
|
289 | self.init_traceback_handlers(custom_exceptions) | |
291 | self.init_prompts() |
|
290 | self.init_prompts() | |
292 | self.init_display_formatter() |
|
291 | self.init_display_formatter() | |
293 | self.init_display_pub() |
|
292 | self.init_display_pub() | |
294 | self.init_displayhook() |
|
293 | self.init_displayhook() | |
295 | self.init_reload_doctest() |
|
294 | self.init_reload_doctest() | |
296 | self.init_magics() |
|
295 | self.init_magics() | |
297 | self.init_pdb() |
|
296 | self.init_pdb() | |
298 | self.init_extension_manager() |
|
297 | self.init_extension_manager() | |
299 | self.init_plugin_manager() |
|
298 | self.init_plugin_manager() | |
300 | self.init_payload() |
|
299 | self.init_payload() | |
301 | self.hooks.late_startup_hook() |
|
300 | self.hooks.late_startup_hook() | |
302 | atexit.register(self.atexit_operations) |
|
301 | atexit.register(self.atexit_operations) | |
303 |
|
302 | |||
304 | # 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 | |
305 | # needs without keeping redundant references to objects, we have too much |
|
304 | # needs without keeping redundant references to objects, we have too much | |
306 | # 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 | |
307 | # retrieves the underlying object from our new history manager. |
|
306 | # retrieves the underlying object from our new history manager. | |
308 | @property |
|
307 | @property | |
309 | def db(self): |
|
308 | def db(self): | |
310 | return self.history_manager.shadow_db |
|
309 | return self.history_manager.shadow_db | |
311 |
|
310 | |||
312 | @classmethod |
|
311 | @classmethod | |
313 | def instance(cls, *args, **kwargs): |
|
312 | def instance(cls, *args, **kwargs): | |
314 | """Returns a global InteractiveShell instance.""" |
|
313 | """Returns a global InteractiveShell instance.""" | |
315 | if cls._instance is None: |
|
314 | if cls._instance is None: | |
316 | inst = cls(*args, **kwargs) |
|
315 | inst = cls(*args, **kwargs) | |
317 | # Now make sure that the instance will also be returned by |
|
316 | # Now make sure that the instance will also be returned by | |
318 | # the subclasses instance attribute. |
|
317 | # the subclasses instance attribute. | |
319 | for subclass in cls.mro(): |
|
318 | for subclass in cls.mro(): | |
320 | if issubclass(cls, subclass) and \ |
|
319 | if issubclass(cls, subclass) and \ | |
321 | issubclass(subclass, InteractiveShell): |
|
320 | issubclass(subclass, InteractiveShell): | |
322 | subclass._instance = inst |
|
321 | subclass._instance = inst | |
323 | else: |
|
322 | else: | |
324 | break |
|
323 | break | |
325 | if isinstance(cls._instance, cls): |
|
324 | if isinstance(cls._instance, cls): | |
326 | return cls._instance |
|
325 | return cls._instance | |
327 | else: |
|
326 | else: | |
328 | raise MultipleInstanceError( |
|
327 | raise MultipleInstanceError( | |
329 | 'Multiple incompatible subclass instances of ' |
|
328 | 'Multiple incompatible subclass instances of ' | |
330 | 'InteractiveShell are being created.' |
|
329 | 'InteractiveShell are being created.' | |
331 | ) |
|
330 | ) | |
332 |
|
331 | |||
333 | @classmethod |
|
332 | @classmethod | |
334 | def initialized(cls): |
|
333 | def initialized(cls): | |
335 | return hasattr(cls, "_instance") |
|
334 | return hasattr(cls, "_instance") | |
336 |
|
335 | |||
337 | def get_ipython(self): |
|
336 | def get_ipython(self): | |
338 | """Return the currently running IPython instance.""" |
|
337 | """Return the currently running IPython instance.""" | |
339 | return self |
|
338 | return self | |
340 |
|
339 | |||
341 | #------------------------------------------------------------------------- |
|
340 | #------------------------------------------------------------------------- | |
342 | # Trait changed handlers |
|
341 | # Trait changed handlers | |
343 | #------------------------------------------------------------------------- |
|
342 | #------------------------------------------------------------------------- | |
344 |
|
343 | |||
345 | def _ipython_dir_changed(self, name, new): |
|
344 | def _ipython_dir_changed(self, name, new): | |
346 | if not os.path.isdir(new): |
|
345 | if not os.path.isdir(new): | |
347 | os.makedirs(new, mode = 0777) |
|
346 | os.makedirs(new, mode = 0777) | |
348 |
|
347 | |||
349 | def set_autoindent(self,value=None): |
|
348 | def set_autoindent(self,value=None): | |
350 | """Set the autoindent flag, checking for readline support. |
|
349 | """Set the autoindent flag, checking for readline support. | |
351 |
|
350 | |||
352 | If called with no arguments, it acts as a toggle.""" |
|
351 | If called with no arguments, it acts as a toggle.""" | |
353 |
|
352 | |||
354 | if not self.has_readline: |
|
353 | if not self.has_readline: | |
355 | if os.name == 'posix': |
|
354 | if os.name == 'posix': | |
356 | warn("The auto-indent feature requires the readline library") |
|
355 | warn("The auto-indent feature requires the readline library") | |
357 | self.autoindent = 0 |
|
356 | self.autoindent = 0 | |
358 | return |
|
357 | return | |
359 | if value is None: |
|
358 | if value is None: | |
360 | self.autoindent = not self.autoindent |
|
359 | self.autoindent = not self.autoindent | |
361 | else: |
|
360 | else: | |
362 | self.autoindent = value |
|
361 | self.autoindent = value | |
363 |
|
362 | |||
364 | #------------------------------------------------------------------------- |
|
363 | #------------------------------------------------------------------------- | |
365 | # init_* methods called by __init__ |
|
364 | # init_* methods called by __init__ | |
366 | #------------------------------------------------------------------------- |
|
365 | #------------------------------------------------------------------------- | |
367 |
|
366 | |||
368 | def init_ipython_dir(self, ipython_dir): |
|
367 | def init_ipython_dir(self, ipython_dir): | |
369 | if ipython_dir is not None: |
|
368 | if ipython_dir is not None: | |
370 | self.ipython_dir = ipython_dir |
|
369 | self.ipython_dir = ipython_dir | |
371 | self.config.Global.ipython_dir = self.ipython_dir |
|
370 | self.config.Global.ipython_dir = self.ipython_dir | |
372 | return |
|
371 | return | |
373 |
|
372 | |||
374 | if hasattr(self.config.Global, 'ipython_dir'): |
|
373 | if hasattr(self.config.Global, 'ipython_dir'): | |
375 | self.ipython_dir = self.config.Global.ipython_dir |
|
374 | self.ipython_dir = self.config.Global.ipython_dir | |
376 | else: |
|
375 | else: | |
377 | self.ipython_dir = get_ipython_dir() |
|
376 | self.ipython_dir = get_ipython_dir() | |
378 |
|
377 | |||
379 | # All children can just read this |
|
378 | # All children can just read this | |
380 | self.config.Global.ipython_dir = self.ipython_dir |
|
379 | self.config.Global.ipython_dir = self.ipython_dir | |
381 |
|
380 | |||
382 | def init_instance_attrs(self): |
|
381 | def init_instance_attrs(self): | |
383 | self.more = False |
|
382 | self.more = False | |
384 |
|
383 | |||
385 | # command compiler |
|
384 | # command compiler | |
386 | self.compile = CachingCompiler() |
|
385 | self.compile = CachingCompiler() | |
387 |
|
386 | |||
388 | # User input buffers |
|
387 | # User input buffers | |
389 | # 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% | |
390 | # 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, | |
391 | # 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 | |
392 | # frontends via an inputsplitter instance. |
|
391 | # frontends via an inputsplitter instance. | |
393 | self.buffer = [] |
|
392 | self.buffer = [] | |
394 | self.buffer_raw = [] |
|
393 | self.buffer_raw = [] | |
395 |
|
394 | |||
396 | # Make an empty namespace, which extension writers can rely on both |
|
395 | # Make an empty namespace, which extension writers can rely on both | |
397 | # 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 | |
398 | # convenient location for storing additional information and state |
|
397 | # convenient location for storing additional information and state | |
399 | # their extensions may require, without fear of collisions with other |
|
398 | # their extensions may require, without fear of collisions with other | |
400 | # ipython names that may develop later. |
|
399 | # ipython names that may develop later. | |
401 | self.meta = Struct() |
|
400 | self.meta = Struct() | |
402 |
|
401 | |||
403 | # Object variable to store code object waiting execution. This is |
|
402 | # Object variable to store code object waiting execution. This is | |
404 | # 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 | |
405 | # 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 | |
406 | # item which gets cleared once run. |
|
405 | # item which gets cleared once run. | |
407 | self.code_to_run = None |
|
406 | self.code_to_run = None | |
408 |
|
407 | |||
409 | # Temporary files used for various purposes. Deleted at exit. |
|
408 | # Temporary files used for various purposes. Deleted at exit. | |
410 | self.tempfiles = [] |
|
409 | self.tempfiles = [] | |
411 |
|
410 | |||
412 | # Keep track of readline usage (later set by init_readline) |
|
411 | # Keep track of readline usage (later set by init_readline) | |
413 | self.has_readline = False |
|
412 | self.has_readline = False | |
414 |
|
413 | |||
415 | # 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) | |
416 | # This is not being used anywhere currently. |
|
415 | # This is not being used anywhere currently. | |
417 | self.starting_dir = os.getcwd() |
|
416 | self.starting_dir = os.getcwd() | |
418 |
|
417 | |||
419 | # Indentation management |
|
418 | # Indentation management | |
420 | self.indent_current_nsp = 0 |
|
419 | self.indent_current_nsp = 0 | |
421 |
|
420 | |||
422 | def init_environment(self): |
|
421 | def init_environment(self): | |
423 | """Any changes we need to make to the user's environment.""" |
|
422 | """Any changes we need to make to the user's environment.""" | |
424 | pass |
|
423 | pass | |
425 |
|
424 | |||
426 | def init_encoding(self): |
|
425 | def init_encoding(self): | |
427 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
426 | # Get system encoding at startup time. Certain terminals (like Emacs | |
428 | # 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 | |
429 | # encoding to use in the raw_input() method |
|
428 | # encoding to use in the raw_input() method | |
430 | try: |
|
429 | try: | |
431 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
430 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
432 | except AttributeError: |
|
431 | except AttributeError: | |
433 | self.stdin_encoding = 'ascii' |
|
432 | self.stdin_encoding = 'ascii' | |
434 |
|
433 | |||
435 | def init_syntax_highlighting(self): |
|
434 | def init_syntax_highlighting(self): | |
436 | # Python source parser/formatter for syntax highlighting |
|
435 | # Python source parser/formatter for syntax highlighting | |
437 | pyformat = PyColorize.Parser().format |
|
436 | pyformat = PyColorize.Parser().format | |
438 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
437 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
439 |
|
438 | |||
440 | def init_pushd_popd_magic(self): |
|
439 | def init_pushd_popd_magic(self): | |
441 | # for pushd/popd management |
|
440 | # for pushd/popd management | |
442 | try: |
|
441 | try: | |
443 | self.home_dir = get_home_dir() |
|
442 | self.home_dir = get_home_dir() | |
444 | except HomeDirError, msg: |
|
443 | except HomeDirError, msg: | |
445 | fatal(msg) |
|
444 | fatal(msg) | |
446 |
|
445 | |||
447 | self.dir_stack = [] |
|
446 | self.dir_stack = [] | |
448 |
|
447 | |||
449 | def init_logger(self): |
|
448 | def init_logger(self): | |
450 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
449 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
451 | logmode='rotate') |
|
450 | logmode='rotate') | |
452 |
|
451 | |||
453 | def init_logstart(self): |
|
452 | def init_logstart(self): | |
454 | """Initialize logging in case it was requested at the command line. |
|
453 | """Initialize logging in case it was requested at the command line. | |
455 | """ |
|
454 | """ | |
456 | if self.logappend: |
|
455 | if self.logappend: | |
457 | self.magic_logstart(self.logappend + ' append') |
|
456 | self.magic_logstart(self.logappend + ' append') | |
458 | elif self.logfile: |
|
457 | elif self.logfile: | |
459 | self.magic_logstart(self.logfile) |
|
458 | self.magic_logstart(self.logfile) | |
460 | elif self.logstart: |
|
459 | elif self.logstart: | |
461 | self.magic_logstart() |
|
460 | self.magic_logstart() | |
462 |
|
461 | |||
463 | def init_builtins(self): |
|
462 | def init_builtins(self): | |
464 | self.builtin_trap = BuiltinTrap(shell=self) |
|
463 | self.builtin_trap = BuiltinTrap(shell=self) | |
465 |
|
464 | |||
466 | def init_inspector(self): |
|
465 | def init_inspector(self): | |
467 | # Object inspector |
|
466 | # Object inspector | |
468 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
467 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
469 | PyColorize.ANSICodeColors, |
|
468 | PyColorize.ANSICodeColors, | |
470 | 'NoColor', |
|
469 | 'NoColor', | |
471 | self.object_info_string_level) |
|
470 | self.object_info_string_level) | |
472 |
|
471 | |||
473 | def init_io(self): |
|
472 | def init_io(self): | |
474 | # 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 | |
475 | # 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 | |
476 | # *before* instantiating this class, because Term holds onto |
|
475 | # *before* instantiating this class, because Term holds onto | |
477 | # references to the underlying streams. |
|
476 | # references to the underlying streams. | |
478 | if sys.platform == 'win32' and self.has_readline: |
|
477 | if sys.platform == 'win32' and self.has_readline: | |
479 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
478 | Term = io.IOTerm(cout=self.readline._outputfile, | |
480 | cerr=self.readline._outputfile) |
|
479 | cerr=self.readline._outputfile) | |
481 | else: |
|
480 | else: | |
482 | Term = io.IOTerm() |
|
481 | Term = io.IOTerm() | |
483 | io.Term = Term |
|
482 | io.Term = Term | |
484 |
|
483 | |||
485 | def init_prompts(self): |
|
484 | def init_prompts(self): | |
486 | # 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 | |
487 | # the DisplayHook. Once there is a separate prompt manager, this |
|
486 | # the DisplayHook. Once there is a separate prompt manager, this | |
488 | # will initialize that object and all prompt related information. |
|
487 | # will initialize that object and all prompt related information. | |
489 | pass |
|
488 | pass | |
490 |
|
489 | |||
491 | def init_display_formatter(self): |
|
490 | def init_display_formatter(self): | |
492 | self.display_formatter = DisplayFormatter(config=self.config) |
|
491 | self.display_formatter = DisplayFormatter(config=self.config) | |
493 |
|
492 | |||
494 | def init_display_pub(self): |
|
493 | def init_display_pub(self): | |
495 | self.display_pub = self.display_pub_class(config=self.config) |
|
494 | self.display_pub = self.display_pub_class(config=self.config) | |
496 |
|
495 | |||
497 | def init_displayhook(self): |
|
496 | def init_displayhook(self): | |
498 | # Initialize displayhook, set in/out prompts and printing system |
|
497 | # Initialize displayhook, set in/out prompts and printing system | |
499 | self.displayhook = self.displayhook_class( |
|
498 | self.displayhook = self.displayhook_class( | |
500 | config=self.config, |
|
499 | config=self.config, | |
501 | shell=self, |
|
500 | shell=self, | |
502 | cache_size=self.cache_size, |
|
501 | cache_size=self.cache_size, | |
503 | input_sep = self.separate_in, |
|
502 | input_sep = self.separate_in, | |
504 | output_sep = self.separate_out, |
|
503 | output_sep = self.separate_out, | |
505 | output_sep2 = self.separate_out2, |
|
504 | output_sep2 = self.separate_out2, | |
506 | ps1 = self.prompt_in1, |
|
505 | ps1 = self.prompt_in1, | |
507 | ps2 = self.prompt_in2, |
|
506 | ps2 = self.prompt_in2, | |
508 | ps_out = self.prompt_out, |
|
507 | ps_out = self.prompt_out, | |
509 | pad_left = self.prompts_pad_left |
|
508 | pad_left = self.prompts_pad_left | |
510 | ) |
|
509 | ) | |
511 | # This is a context manager that installs/revmoes the displayhook at |
|
510 | # This is a context manager that installs/revmoes the displayhook at | |
512 | # the appropriate time. |
|
511 | # the appropriate time. | |
513 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
512 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
514 |
|
513 | |||
515 | def init_reload_doctest(self): |
|
514 | def init_reload_doctest(self): | |
516 | # Do a proper resetting of doctest, including the necessary displayhook |
|
515 | # Do a proper resetting of doctest, including the necessary displayhook | |
517 | # monkeypatching |
|
516 | # monkeypatching | |
518 | try: |
|
517 | try: | |
519 | doctest_reload() |
|
518 | doctest_reload() | |
520 | except ImportError: |
|
519 | except ImportError: | |
521 | warn("doctest module does not exist.") |
|
520 | warn("doctest module does not exist.") | |
522 |
|
521 | |||
523 | #------------------------------------------------------------------------- |
|
522 | #------------------------------------------------------------------------- | |
524 | # Things related to injections into the sys module |
|
523 | # Things related to injections into the sys module | |
525 | #------------------------------------------------------------------------- |
|
524 | #------------------------------------------------------------------------- | |
526 |
|
525 | |||
527 | def save_sys_module_state(self): |
|
526 | def save_sys_module_state(self): | |
528 | """Save the state of hooks in the sys module. |
|
527 | """Save the state of hooks in the sys module. | |
529 |
|
528 | |||
530 | This has to be called after self.user_ns is created. |
|
529 | This has to be called after self.user_ns is created. | |
531 | """ |
|
530 | """ | |
532 | self._orig_sys_module_state = {} |
|
531 | self._orig_sys_module_state = {} | |
533 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
532 | self._orig_sys_module_state['stdin'] = sys.stdin | |
534 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
533 | self._orig_sys_module_state['stdout'] = sys.stdout | |
535 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
534 | self._orig_sys_module_state['stderr'] = sys.stderr | |
536 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
535 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
537 | try: |
|
536 | try: | |
538 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
537 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
539 | except KeyError: |
|
538 | except KeyError: | |
540 | pass |
|
539 | pass | |
541 |
|
540 | |||
542 | def restore_sys_module_state(self): |
|
541 | def restore_sys_module_state(self): | |
543 | """Restore the state of the sys module.""" |
|
542 | """Restore the state of the sys module.""" | |
544 | try: |
|
543 | try: | |
545 | for k, v in self._orig_sys_module_state.iteritems(): |
|
544 | for k, v in self._orig_sys_module_state.iteritems(): | |
546 | setattr(sys, k, v) |
|
545 | setattr(sys, k, v) | |
547 | except AttributeError: |
|
546 | except AttributeError: | |
548 | pass |
|
547 | pass | |
549 | # Reset what what done in self.init_sys_modules |
|
548 | # Reset what what done in self.init_sys_modules | |
550 | try: |
|
549 | try: | |
551 | 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 | |
552 | except (AttributeError, KeyError): |
|
551 | except (AttributeError, KeyError): | |
553 | pass |
|
552 | pass | |
554 |
|
553 | |||
555 | #------------------------------------------------------------------------- |
|
554 | #------------------------------------------------------------------------- | |
556 | # Things related to hooks |
|
555 | # Things related to hooks | |
557 | #------------------------------------------------------------------------- |
|
556 | #------------------------------------------------------------------------- | |
558 |
|
557 | |||
559 | def init_hooks(self): |
|
558 | def init_hooks(self): | |
560 | # hooks holds pointers used for user-side customizations |
|
559 | # hooks holds pointers used for user-side customizations | |
561 | self.hooks = Struct() |
|
560 | self.hooks = Struct() | |
562 |
|
561 | |||
563 | self.strdispatchers = {} |
|
562 | self.strdispatchers = {} | |
564 |
|
563 | |||
565 | # Set all default hooks, defined in the IPython.hooks module. |
|
564 | # Set all default hooks, defined in the IPython.hooks module. | |
566 | hooks = IPython.core.hooks |
|
565 | hooks = IPython.core.hooks | |
567 | for hook_name in hooks.__all__: |
|
566 | for hook_name in hooks.__all__: | |
568 | # 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 | |
569 | # 0-100 priority |
|
568 | # 0-100 priority | |
570 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
569 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
571 |
|
570 | |||
572 | 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): | |
573 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
572 | """set_hook(name,hook) -> sets an internal IPython hook. | |
574 |
|
573 | |||
575 | 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 | |
576 | 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 | |
577 | behavior to call at runtime your own routines.""" |
|
576 | behavior to call at runtime your own routines.""" | |
578 |
|
577 | |||
579 | # 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 | |
580 | # 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 | |
581 | # of args it's supposed to. |
|
580 | # of args it's supposed to. | |
582 |
|
581 | |||
583 | f = types.MethodType(hook,self) |
|
582 | f = types.MethodType(hook,self) | |
584 |
|
583 | |||
585 | # check if the hook is for strdispatcher first |
|
584 | # check if the hook is for strdispatcher first | |
586 | if str_key is not None: |
|
585 | if str_key is not None: | |
587 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
586 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
588 | sdp.add_s(str_key, f, priority ) |
|
587 | sdp.add_s(str_key, f, priority ) | |
589 | self.strdispatchers[name] = sdp |
|
588 | self.strdispatchers[name] = sdp | |
590 | return |
|
589 | return | |
591 | if re_key is not None: |
|
590 | if re_key is not None: | |
592 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
591 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
593 | sdp.add_re(re.compile(re_key), f, priority ) |
|
592 | sdp.add_re(re.compile(re_key), f, priority ) | |
594 | self.strdispatchers[name] = sdp |
|
593 | self.strdispatchers[name] = sdp | |
595 | return |
|
594 | return | |
596 |
|
595 | |||
597 | dp = getattr(self.hooks, name, None) |
|
596 | dp = getattr(self.hooks, name, None) | |
598 | if name not in IPython.core.hooks.__all__: |
|
597 | if name not in IPython.core.hooks.__all__: | |
599 | print "Warning! Hook '%s' is not one of %s" % \ |
|
598 | print "Warning! Hook '%s' is not one of %s" % \ | |
600 | (name, IPython.core.hooks.__all__ ) |
|
599 | (name, IPython.core.hooks.__all__ ) | |
601 | if not dp: |
|
600 | if not dp: | |
602 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
601 | dp = IPython.core.hooks.CommandChainDispatcher() | |
603 |
|
602 | |||
604 | try: |
|
603 | try: | |
605 | dp.add(f,priority) |
|
604 | dp.add(f,priority) | |
606 | except AttributeError: |
|
605 | except AttributeError: | |
607 | # it was not commandchain, plain old func - replace |
|
606 | # it was not commandchain, plain old func - replace | |
608 | dp = f |
|
607 | dp = f | |
609 |
|
608 | |||
610 | setattr(self.hooks,name, dp) |
|
609 | setattr(self.hooks,name, dp) | |
611 |
|
610 | |||
612 | def register_post_execute(self, func): |
|
611 | def register_post_execute(self, func): | |
613 | """Register a function for calling after code execution. |
|
612 | """Register a function for calling after code execution. | |
614 | """ |
|
613 | """ | |
615 | if not callable(func): |
|
614 | if not callable(func): | |
616 | raise ValueError('argument %s must be callable' % func) |
|
615 | raise ValueError('argument %s must be callable' % func) | |
617 | self._post_execute.add(func) |
|
616 | self._post_execute.add(func) | |
618 |
|
617 | |||
619 | #------------------------------------------------------------------------- |
|
618 | #------------------------------------------------------------------------- | |
620 | # Things related to the "main" module |
|
619 | # Things related to the "main" module | |
621 | #------------------------------------------------------------------------- |
|
620 | #------------------------------------------------------------------------- | |
622 |
|
621 | |||
623 | def new_main_mod(self,ns=None): |
|
622 | def new_main_mod(self,ns=None): | |
624 | """Return a new 'main' module object for user code execution. |
|
623 | """Return a new 'main' module object for user code execution. | |
625 | """ |
|
624 | """ | |
626 | main_mod = self._user_main_module |
|
625 | main_mod = self._user_main_module | |
627 | init_fakemod_dict(main_mod,ns) |
|
626 | init_fakemod_dict(main_mod,ns) | |
628 | return main_mod |
|
627 | return main_mod | |
629 |
|
628 | |||
630 | def cache_main_mod(self,ns,fname): |
|
629 | def cache_main_mod(self,ns,fname): | |
631 | """Cache a main module's namespace. |
|
630 | """Cache a main module's namespace. | |
632 |
|
631 | |||
633 | 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 | |
634 | namespace of their __main__ module (a FakeModule instance) around so |
|
633 | namespace of their __main__ module (a FakeModule instance) around so | |
635 | that Python doesn't clear it, rendering objects defined therein |
|
634 | that Python doesn't clear it, rendering objects defined therein | |
636 | useless. |
|
635 | useless. | |
637 |
|
636 | |||
638 | 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 | |
639 | absolute path of the module object (which corresponds to the script |
|
638 | absolute path of the module object (which corresponds to the script | |
640 | 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 | |
641 | 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 | |
642 | leaks from old references while allowing the objects from the last |
|
641 | leaks from old references while allowing the objects from the last | |
643 | execution to be accessible. |
|
642 | execution to be accessible. | |
644 |
|
643 | |||
645 | 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, | |
646 | 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 | |
647 | references to None without regard for reference counts). This method |
|
646 | references to None without regard for reference counts). This method | |
648 | 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 | |
649 | original module's __dict__ to be cleared and reused. |
|
648 | original module's __dict__ to be cleared and reused. | |
650 |
|
649 | |||
651 |
|
650 | |||
652 | Parameters |
|
651 | Parameters | |
653 | ---------- |
|
652 | ---------- | |
654 | ns : a namespace (a dict, typically) |
|
653 | ns : a namespace (a dict, typically) | |
655 |
|
654 | |||
656 | fname : str |
|
655 | fname : str | |
657 | Filename associated with the namespace. |
|
656 | Filename associated with the namespace. | |
658 |
|
657 | |||
659 | Examples |
|
658 | Examples | |
660 | -------- |
|
659 | -------- | |
661 |
|
660 | |||
662 | In [10]: import IPython |
|
661 | In [10]: import IPython | |
663 |
|
662 | |||
664 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
663 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
665 |
|
664 | |||
666 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
665 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
667 | Out[12]: True |
|
666 | Out[12]: True | |
668 | """ |
|
667 | """ | |
669 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
668 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
670 |
|
669 | |||
671 | def clear_main_mod_cache(self): |
|
670 | def clear_main_mod_cache(self): | |
672 | """Clear the cache of main modules. |
|
671 | """Clear the cache of main modules. | |
673 |
|
672 | |||
674 | Mainly for use by utilities like %reset. |
|
673 | Mainly for use by utilities like %reset. | |
675 |
|
674 | |||
676 | Examples |
|
675 | Examples | |
677 | -------- |
|
676 | -------- | |
678 |
|
677 | |||
679 | In [15]: import IPython |
|
678 | In [15]: import IPython | |
680 |
|
679 | |||
681 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
680 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
682 |
|
681 | |||
683 | In [17]: len(_ip._main_ns_cache) > 0 |
|
682 | In [17]: len(_ip._main_ns_cache) > 0 | |
684 | Out[17]: True |
|
683 | Out[17]: True | |
685 |
|
684 | |||
686 | In [18]: _ip.clear_main_mod_cache() |
|
685 | In [18]: _ip.clear_main_mod_cache() | |
687 |
|
686 | |||
688 | In [19]: len(_ip._main_ns_cache) == 0 |
|
687 | In [19]: len(_ip._main_ns_cache) == 0 | |
689 | Out[19]: True |
|
688 | Out[19]: True | |
690 | """ |
|
689 | """ | |
691 | self._main_ns_cache.clear() |
|
690 | self._main_ns_cache.clear() | |
692 |
|
691 | |||
693 | #------------------------------------------------------------------------- |
|
692 | #------------------------------------------------------------------------- | |
694 | # Things related to debugging |
|
693 | # Things related to debugging | |
695 | #------------------------------------------------------------------------- |
|
694 | #------------------------------------------------------------------------- | |
696 |
|
695 | |||
697 | def init_pdb(self): |
|
696 | def init_pdb(self): | |
698 | # Set calling of pdb on exceptions |
|
697 | # Set calling of pdb on exceptions | |
699 | # self.call_pdb is a property |
|
698 | # self.call_pdb is a property | |
700 | self.call_pdb = self.pdb |
|
699 | self.call_pdb = self.pdb | |
701 |
|
700 | |||
702 | def _get_call_pdb(self): |
|
701 | def _get_call_pdb(self): | |
703 | return self._call_pdb |
|
702 | return self._call_pdb | |
704 |
|
703 | |||
705 | def _set_call_pdb(self,val): |
|
704 | def _set_call_pdb(self,val): | |
706 |
|
705 | |||
707 | if val not in (0,1,False,True): |
|
706 | if val not in (0,1,False,True): | |
708 | raise ValueError,'new call_pdb value must be boolean' |
|
707 | raise ValueError,'new call_pdb value must be boolean' | |
709 |
|
708 | |||
710 | # store value in instance |
|
709 | # store value in instance | |
711 | self._call_pdb = val |
|
710 | self._call_pdb = val | |
712 |
|
711 | |||
713 | # notify the actual exception handlers |
|
712 | # notify the actual exception handlers | |
714 | self.InteractiveTB.call_pdb = val |
|
713 | self.InteractiveTB.call_pdb = val | |
715 |
|
714 | |||
716 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
715 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
717 | 'Control auto-activation of pdb at exceptions') |
|
716 | 'Control auto-activation of pdb at exceptions') | |
718 |
|
717 | |||
719 | def debugger(self,force=False): |
|
718 | def debugger(self,force=False): | |
720 | """Call the pydb/pdb debugger. |
|
719 | """Call the pydb/pdb debugger. | |
721 |
|
720 | |||
722 | Keywords: |
|
721 | Keywords: | |
723 |
|
722 | |||
724 | - force(False): by default, this routine checks the instance call_pdb |
|
723 | - force(False): by default, this routine checks the instance call_pdb | |
725 | 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. | |
726 | 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 | |
727 | is false. |
|
726 | is false. | |
728 | """ |
|
727 | """ | |
729 |
|
728 | |||
730 | if not (force or self.call_pdb): |
|
729 | if not (force or self.call_pdb): | |
731 | return |
|
730 | return | |
732 |
|
731 | |||
733 | if not hasattr(sys,'last_traceback'): |
|
732 | if not hasattr(sys,'last_traceback'): | |
734 | error('No traceback has been produced, nothing to debug.') |
|
733 | error('No traceback has been produced, nothing to debug.') | |
735 | return |
|
734 | return | |
736 |
|
735 | |||
737 | # use pydb if available |
|
736 | # use pydb if available | |
738 | if debugger.has_pydb: |
|
737 | if debugger.has_pydb: | |
739 | from pydb import pm |
|
738 | from pydb import pm | |
740 | else: |
|
739 | else: | |
741 | # fallback to our internal debugger |
|
740 | # fallback to our internal debugger | |
742 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
741 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
743 | self.history_saving_wrapper(pm)() |
|
742 | self.history_saving_wrapper(pm)() | |
744 |
|
743 | |||
745 | #------------------------------------------------------------------------- |
|
744 | #------------------------------------------------------------------------- | |
746 | # Things related to IPython's various namespaces |
|
745 | # Things related to IPython's various namespaces | |
747 | #------------------------------------------------------------------------- |
|
746 | #------------------------------------------------------------------------- | |
748 |
|
747 | |||
749 | 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): | |
750 | # Create the namespace where the user will operate. user_ns is |
|
749 | # Create the namespace where the user will operate. user_ns is | |
751 | # 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 | |
752 | # 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 | |
753 | # given as the exec 'globals' argument, This is useful in embedding |
|
752 | # given as the exec 'globals' argument, This is useful in embedding | |
754 | # situations where the ipython shell opens in a context where the |
|
753 | # situations where the ipython shell opens in a context where the | |
755 | # distinction between locals and globals is meaningful. For |
|
754 | # distinction between locals and globals is meaningful. For | |
756 | # 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. | |
757 |
|
756 | |||
758 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
757 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
759 | # 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 | |
760 | # should really track down where the problem is coming from. Alex |
|
759 | # should really track down where the problem is coming from. Alex | |
761 | # Schmolck reported this problem first. |
|
760 | # Schmolck reported this problem first. | |
762 |
|
761 | |||
763 | # A useful post by Alex Martelli on this topic: |
|
762 | # A useful post by Alex Martelli on this topic: | |
764 | # Re: inconsistent value from __builtins__ |
|
763 | # Re: inconsistent value from __builtins__ | |
765 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
764 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
766 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
765 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
767 | # Gruppen: comp.lang.python |
|
766 | # Gruppen: comp.lang.python | |
768 |
|
767 | |||
769 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
768 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
770 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
769 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
771 | # > <type 'dict'> |
|
770 | # > <type 'dict'> | |
772 | # > >>> print type(__builtins__) |
|
771 | # > >>> print type(__builtins__) | |
773 | # > <type 'module'> |
|
772 | # > <type 'module'> | |
774 | # > Is this difference in return value intentional? |
|
773 | # > Is this difference in return value intentional? | |
775 |
|
774 | |||
776 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
775 | # Well, it's documented that '__builtins__' can be either a dictionary | |
777 | # 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 | |
778 | # 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 | |
779 | # 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 | |
780 | # should start with "import __builtin__" (note, no 's') which will |
|
779 | # should start with "import __builtin__" (note, no 's') which will | |
781 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
780 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
782 |
|
781 | |||
783 | # 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 | |
784 | # 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 | |
785 | # properly initialized namespaces. |
|
784 | # properly initialized namespaces. | |
786 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
785 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
787 | user_global_ns) |
|
786 | user_global_ns) | |
788 |
|
787 | |||
789 | # Assign namespaces |
|
788 | # Assign namespaces | |
790 | # This is the namespace where all normal user variables live |
|
789 | # This is the namespace where all normal user variables live | |
791 | self.user_ns = user_ns |
|
790 | self.user_ns = user_ns | |
792 | self.user_global_ns = user_global_ns |
|
791 | self.user_global_ns = user_global_ns | |
793 |
|
792 | |||
794 | # 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 | |
795 | # 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 | |
796 | # 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 | |
797 | # doesn't need to be separately tracked in the ns_table. |
|
796 | # doesn't need to be separately tracked in the ns_table. | |
798 | self.user_ns_hidden = {} |
|
797 | self.user_ns_hidden = {} | |
799 |
|
798 | |||
800 | # A namespace to keep track of internal data structures to prevent |
|
799 | # A namespace to keep track of internal data structures to prevent | |
801 | # them from cluttering user-visible stuff. Will be updated later |
|
800 | # them from cluttering user-visible stuff. Will be updated later | |
802 | self.internal_ns = {} |
|
801 | self.internal_ns = {} | |
803 |
|
802 | |||
804 | # 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 | |
805 | # problem: after script execution (via %run), the module where the user |
|
804 | # problem: after script execution (via %run), the module where the user | |
806 | # 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 | |
807 | # so docetst and other tools work correctly), the Python module |
|
806 | # so docetst and other tools work correctly), the Python module | |
808 | # teardown mechanism runs over it, and sets to None every variable |
|
807 | # teardown mechanism runs over it, and sets to None every variable | |
809 | # present in that module. Top-level references to objects from the |
|
808 | # present in that module. Top-level references to objects from the | |
810 | # script survive, because the user_ns is updated with them. However, |
|
809 | # script survive, because the user_ns is updated with them. However, | |
811 | # calling functions defined in the script that use other things from |
|
810 | # calling functions defined in the script that use other things from | |
812 | # the script will fail, because the function's closure had references |
|
811 | # the script will fail, because the function's closure had references | |
813 | # 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 | |
814 | # these modules from deletion by keeping a cache. |
|
813 | # these modules from deletion by keeping a cache. | |
815 | # |
|
814 | # | |
816 | # 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 | |
817 | # 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 | |
818 | # 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, | |
819 | # however, that we must cache the module *namespace contents* (their |
|
818 | # however, that we must cache the module *namespace contents* (their | |
820 | # __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 | |
821 | # (uncached) could be destroyed while still holding references (such as |
|
820 | # (uncached) could be destroyed while still holding references (such as | |
822 | # those held by GUI objects that tend to be long-lived)> |
|
821 | # those held by GUI objects that tend to be long-lived)> | |
823 | # |
|
822 | # | |
824 | # 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() | |
825 | # and clear_main_mod_cache() methods for details on use. |
|
824 | # and clear_main_mod_cache() methods for details on use. | |
826 |
|
825 | |||
827 | # This is the cache used for 'main' namespaces |
|
826 | # This is the cache used for 'main' namespaces | |
828 | self._main_ns_cache = {} |
|
827 | self._main_ns_cache = {} | |
829 | # 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 | |
830 | # copying and clearing for reuse on each %run |
|
829 | # copying and clearing for reuse on each %run | |
831 | self._user_main_module = FakeModule() |
|
830 | self._user_main_module = FakeModule() | |
832 |
|
831 | |||
833 | # A table holding all the namespaces IPython deals with, so that |
|
832 | # A table holding all the namespaces IPython deals with, so that | |
834 | # introspection facilities can search easily. |
|
833 | # introspection facilities can search easily. | |
835 | self.ns_table = {'user':user_ns, |
|
834 | self.ns_table = {'user':user_ns, | |
836 | 'user_global':user_global_ns, |
|
835 | 'user_global':user_global_ns, | |
837 | 'internal':self.internal_ns, |
|
836 | 'internal':self.internal_ns, | |
838 | 'builtin':__builtin__.__dict__ |
|
837 | 'builtin':__builtin__.__dict__ | |
839 | } |
|
838 | } | |
840 |
|
839 | |||
841 | # Similarly, track all namespaces where references can be held and that |
|
840 | # Similarly, track all namespaces where references can be held and that | |
842 | # 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 | |
843 | # 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 | |
844 | # 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 | |
845 | # causes errors in object __del__ methods. Instead, the reset() method |
|
844 | # causes errors in object __del__ methods. Instead, the reset() method | |
846 | # clears them manually and carefully. |
|
845 | # clears them manually and carefully. | |
847 | self.ns_refs_table = [ self.user_ns_hidden, |
|
846 | self.ns_refs_table = [ self.user_ns_hidden, | |
848 | self.internal_ns, self._main_ns_cache ] |
|
847 | self.internal_ns, self._main_ns_cache ] | |
849 |
|
848 | |||
850 | 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): | |
851 | """Return a valid local and global user interactive namespaces. |
|
850 | """Return a valid local and global user interactive namespaces. | |
852 |
|
851 | |||
853 | 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 | |
854 | valid IPython user namespace, which you can pass to the various |
|
853 | valid IPython user namespace, which you can pass to the various | |
855 | embedding classes in ipython. The default implementation returns the |
|
854 | embedding classes in ipython. The default implementation returns the | |
856 | 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 | |
857 | refer to variables in the namespace. Customized implementations can |
|
856 | refer to variables in the namespace. Customized implementations can | |
858 | return different dicts. The locals dictionary can actually be anything |
|
857 | return different dicts. The locals dictionary can actually be anything | |
859 | 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 | |
860 | 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 | |
861 | custom object for the locals namespace synchronize with the globals |
|
860 | custom object for the locals namespace synchronize with the globals | |
862 | dict somehow. |
|
861 | dict somehow. | |
863 |
|
862 | |||
864 | 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. | |
865 |
|
864 | |||
866 | Parameters |
|
865 | Parameters | |
867 | ---------- |
|
866 | ---------- | |
868 | user_ns : dict-like, optional |
|
867 | user_ns : dict-like, optional | |
869 | The current user namespace. The items in this namespace should |
|
868 | The current user namespace. The items in this namespace should | |
870 | be included in the output. If None, an appropriate blank |
|
869 | be included in the output. If None, an appropriate blank | |
871 | namespace should be created. |
|
870 | namespace should be created. | |
872 | user_global_ns : dict, optional |
|
871 | user_global_ns : dict, optional | |
873 | The current user global namespace. The items in this namespace |
|
872 | The current user global namespace. The items in this namespace | |
874 | should be included in the output. If None, an appropriate |
|
873 | should be included in the output. If None, an appropriate | |
875 | blank namespace should be created. |
|
874 | blank namespace should be created. | |
876 |
|
875 | |||
877 | Returns |
|
876 | Returns | |
878 | ------- |
|
877 | ------- | |
879 | 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 | |
880 | 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. | |
881 | """ |
|
880 | """ | |
882 |
|
881 | |||
883 |
|
882 | |||
884 | # We must ensure that __builtin__ (without the final 's') is always |
|
883 | # We must ensure that __builtin__ (without the final 's') is always | |
885 | # available and pointing to the __builtin__ *module*. For more details: |
|
884 | # available and pointing to the __builtin__ *module*. For more details: | |
886 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
885 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
887 |
|
886 | |||
888 | if user_ns is None: |
|
887 | if user_ns is None: | |
889 | # Set __name__ to __main__ to better match the behavior of the |
|
888 | # Set __name__ to __main__ to better match the behavior of the | |
890 | # normal interpreter. |
|
889 | # normal interpreter. | |
891 | user_ns = {'__name__' :'__main__', |
|
890 | user_ns = {'__name__' :'__main__', | |
892 | '__builtin__' : __builtin__, |
|
891 | '__builtin__' : __builtin__, | |
893 | '__builtins__' : __builtin__, |
|
892 | '__builtins__' : __builtin__, | |
894 | } |
|
893 | } | |
895 | else: |
|
894 | else: | |
896 | user_ns.setdefault('__name__','__main__') |
|
895 | user_ns.setdefault('__name__','__main__') | |
897 | user_ns.setdefault('__builtin__',__builtin__) |
|
896 | user_ns.setdefault('__builtin__',__builtin__) | |
898 | user_ns.setdefault('__builtins__',__builtin__) |
|
897 | user_ns.setdefault('__builtins__',__builtin__) | |
899 |
|
898 | |||
900 | if user_global_ns is None: |
|
899 | if user_global_ns is None: | |
901 | user_global_ns = user_ns |
|
900 | user_global_ns = user_ns | |
902 | if type(user_global_ns) is not dict: |
|
901 | if type(user_global_ns) is not dict: | |
903 | 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" | |
904 | % type(user_global_ns)) |
|
903 | % type(user_global_ns)) | |
905 |
|
904 | |||
906 | return user_ns, user_global_ns |
|
905 | return user_ns, user_global_ns | |
907 |
|
906 | |||
908 | def init_sys_modules(self): |
|
907 | def init_sys_modules(self): | |
909 | # 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 | |
910 | # module but which accesses the IPython namespace, for shelve and |
|
909 | # module but which accesses the IPython namespace, for shelve and | |
911 | # pickle to work interactively. Normally they rely on getting |
|
910 | # pickle to work interactively. Normally they rely on getting | |
912 | # everything out of __main__, but for embedding purposes each IPython |
|
911 | # everything out of __main__, but for embedding purposes each IPython | |
913 | # 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 | |
914 | # everything into __main__. |
|
913 | # everything into __main__. | |
915 |
|
914 | |||
916 | # note, however, that we should only do this for non-embedded |
|
915 | # note, however, that we should only do this for non-embedded | |
917 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
916 | # ipythons, which really mimic the __main__.__dict__ with their own | |
918 | # namespace. Embedded instances, on the other hand, should not do |
|
917 | # namespace. Embedded instances, on the other hand, should not do | |
919 | # this because they need to manage the user local/global namespaces |
|
918 | # this because they need to manage the user local/global namespaces | |
920 | # only, but they live within a 'normal' __main__ (meaning, they |
|
919 | # only, but they live within a 'normal' __main__ (meaning, they | |
921 | # shouldn't overtake the execution environment of the script they're |
|
920 | # shouldn't overtake the execution environment of the script they're | |
922 | # embedded in). |
|
921 | # embedded in). | |
923 |
|
922 | |||
924 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
923 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
925 |
|
924 | |||
926 | try: |
|
925 | try: | |
927 | main_name = self.user_ns['__name__'] |
|
926 | main_name = self.user_ns['__name__'] | |
928 | except KeyError: |
|
927 | except KeyError: | |
929 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
928 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
930 | else: |
|
929 | else: | |
931 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
930 | sys.modules[main_name] = FakeModule(self.user_ns) | |
932 |
|
931 | |||
933 | def init_user_ns(self): |
|
932 | def init_user_ns(self): | |
934 | """Initialize all user-visible namespaces to their minimum defaults. |
|
933 | """Initialize all user-visible namespaces to their minimum defaults. | |
935 |
|
934 | |||
936 | Certain history lists are also initialized here, as they effectively |
|
935 | Certain history lists are also initialized here, as they effectively | |
937 | act as user namespaces. |
|
936 | act as user namespaces. | |
938 |
|
937 | |||
939 | Notes |
|
938 | Notes | |
940 | ----- |
|
939 | ----- | |
941 | 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 | |
942 | 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 | |
943 | therm. |
|
942 | therm. | |
944 | """ |
|
943 | """ | |
945 | # 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 | |
946 | # 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 | |
947 | # 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 | |
948 | # 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 | |
949 | # session (probably nothing, so theye really only see their own stuff) |
|
948 | # session (probably nothing, so theye really only see their own stuff) | |
950 |
|
949 | |||
951 | # The user dict must *always* have a __builtin__ reference to the |
|
950 | # The user dict must *always* have a __builtin__ reference to the | |
952 | # Python standard __builtin__ namespace, which must be imported. |
|
951 | # Python standard __builtin__ namespace, which must be imported. | |
953 | # This is so that certain operations in prompt evaluation can be |
|
952 | # This is so that certain operations in prompt evaluation can be | |
954 | # reliably executed with builtins. Note that we can NOT use |
|
953 | # reliably executed with builtins. Note that we can NOT use | |
955 | # __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 | |
956 | # module, and can even mutate at runtime, depending on the context |
|
955 | # module, and can even mutate at runtime, depending on the context | |
957 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
956 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
958 | # always a module object, though it must be explicitly imported. |
|
957 | # always a module object, though it must be explicitly imported. | |
959 |
|
958 | |||
960 | # For more details: |
|
959 | # For more details: | |
961 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
960 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
962 | ns = dict(__builtin__ = __builtin__) |
|
961 | ns = dict(__builtin__ = __builtin__) | |
963 |
|
962 | |||
964 | # Put 'help' in the user namespace |
|
963 | # Put 'help' in the user namespace | |
965 | try: |
|
964 | try: | |
966 | from site import _Helper |
|
965 | from site import _Helper | |
967 | ns['help'] = _Helper() |
|
966 | ns['help'] = _Helper() | |
968 | except ImportError: |
|
967 | except ImportError: | |
969 | warn('help() not available - check site.py') |
|
968 | warn('help() not available - check site.py') | |
970 |
|
969 | |||
971 | # make global variables for user access to the histories |
|
970 | # make global variables for user access to the histories | |
972 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
971 | ns['_ih'] = self.history_manager.input_hist_parsed | |
973 | ns['_oh'] = self.history_manager.output_hist |
|
972 | ns['_oh'] = self.history_manager.output_hist | |
974 | ns['_dh'] = self.history_manager.dir_hist |
|
973 | ns['_dh'] = self.history_manager.dir_hist | |
975 |
|
974 | |||
976 | ns['_sh'] = shadowns |
|
975 | ns['_sh'] = shadowns | |
977 |
|
976 | |||
978 | # 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 | |
979 | # in %who, as they can have very large reprs. |
|
978 | # in %who, as they can have very large reprs. | |
980 | ns['In'] = self.history_manager.input_hist_parsed |
|
979 | ns['In'] = self.history_manager.input_hist_parsed | |
981 | ns['Out'] = self.history_manager.output_hist |
|
980 | ns['Out'] = self.history_manager.output_hist | |
982 |
|
981 | |||
983 | # Store myself as the public api!!! |
|
982 | # Store myself as the public api!!! | |
984 | ns['get_ipython'] = self.get_ipython |
|
983 | ns['get_ipython'] = self.get_ipython | |
985 |
|
984 | |||
986 | # 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 | |
987 | # by %who |
|
986 | # by %who | |
988 | self.user_ns_hidden.update(ns) |
|
987 | self.user_ns_hidden.update(ns) | |
989 |
|
988 | |||
990 | # 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 | |
991 | # 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 | |
992 | # stuff, not our variables. |
|
991 | # stuff, not our variables. | |
993 |
|
992 | |||
994 | # Finally, update the real user's namespace |
|
993 | # Finally, update the real user's namespace | |
995 | self.user_ns.update(ns) |
|
994 | self.user_ns.update(ns) | |
996 |
|
995 | |||
997 | def reset(self): |
|
996 | def reset(self): | |
998 | """Clear all internal namespaces. |
|
997 | """Clear all internal namespaces. | |
999 |
|
998 | |||
1000 | 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 | |
1001 | fully all namespaces, as well as all input/output lists. |
|
1000 | fully all namespaces, as well as all input/output lists. | |
1002 | """ |
|
1001 | """ | |
1003 | # Clear histories |
|
1002 | # Clear histories | |
1004 | self.history_manager.reset() |
|
1003 | self.history_manager.reset() | |
1005 |
|
1004 | |||
1006 | # Reset counter used to index all histories |
|
1005 | # Reset counter used to index all histories | |
1007 | self.execution_count = 0 |
|
1006 | self.execution_count = 0 | |
1008 |
|
1007 | |||
1009 | # Restore the user namespaces to minimal usability |
|
1008 | # Restore the user namespaces to minimal usability | |
1010 | for ns in self.ns_refs_table: |
|
1009 | for ns in self.ns_refs_table: | |
1011 | ns.clear() |
|
1010 | ns.clear() | |
1012 |
|
1011 | |||
1013 | # The main execution namespaces must be cleared very carefully, |
|
1012 | # The main execution namespaces must be cleared very carefully, | |
1014 | # skipping the deletion of the builtin-related keys, because doing so |
|
1013 | # skipping the deletion of the builtin-related keys, because doing so | |
1015 | # would cause errors in many object's __del__ methods. |
|
1014 | # would cause errors in many object's __del__ methods. | |
1016 | for ns in [self.user_ns, self.user_global_ns]: |
|
1015 | for ns in [self.user_ns, self.user_global_ns]: | |
1017 | drop_keys = set(ns.keys()) |
|
1016 | drop_keys = set(ns.keys()) | |
1018 | drop_keys.discard('__builtin__') |
|
1017 | drop_keys.discard('__builtin__') | |
1019 | drop_keys.discard('__builtins__') |
|
1018 | drop_keys.discard('__builtins__') | |
1020 | for k in drop_keys: |
|
1019 | for k in drop_keys: | |
1021 | del ns[k] |
|
1020 | del ns[k] | |
1022 |
|
1021 | |||
1023 | # Restore the user namespaces to minimal usability |
|
1022 | # Restore the user namespaces to minimal usability | |
1024 | self.init_user_ns() |
|
1023 | self.init_user_ns() | |
1025 |
|
1024 | |||
1026 | # Restore the default and user aliases |
|
1025 | # Restore the default and user aliases | |
1027 | self.alias_manager.clear_aliases() |
|
1026 | self.alias_manager.clear_aliases() | |
1028 | self.alias_manager.init_aliases() |
|
1027 | self.alias_manager.init_aliases() | |
1029 |
|
1028 | |||
1030 | def reset_selective(self, regex=None): |
|
1029 | def reset_selective(self, regex=None): | |
1031 | """Clear selective variables from internal namespaces based on a |
|
1030 | """Clear selective variables from internal namespaces based on a | |
1032 | specified regular expression. |
|
1031 | specified regular expression. | |
1033 |
|
1032 | |||
1034 | Parameters |
|
1033 | Parameters | |
1035 | ---------- |
|
1034 | ---------- | |
1036 | regex : string or compiled pattern, optional |
|
1035 | regex : string or compiled pattern, optional | |
1037 | A regular expression pattern that will be used in searching |
|
1036 | A regular expression pattern that will be used in searching | |
1038 | variable names in the users namespaces. |
|
1037 | variable names in the users namespaces. | |
1039 | """ |
|
1038 | """ | |
1040 | if regex is not None: |
|
1039 | if regex is not None: | |
1041 | try: |
|
1040 | try: | |
1042 | m = re.compile(regex) |
|
1041 | m = re.compile(regex) | |
1043 | except TypeError: |
|
1042 | except TypeError: | |
1044 | raise TypeError('regex must be a string or compiled pattern') |
|
1043 | raise TypeError('regex must be a string or compiled pattern') | |
1045 | # Search for keys in each namespace that match the given regex |
|
1044 | # Search for keys in each namespace that match the given regex | |
1046 | # If a match is found, delete the key/value pair. |
|
1045 | # If a match is found, delete the key/value pair. | |
1047 | for ns in self.ns_refs_table: |
|
1046 | for ns in self.ns_refs_table: | |
1048 | for var in ns: |
|
1047 | for var in ns: | |
1049 | if m.search(var): |
|
1048 | if m.search(var): | |
1050 | del ns[var] |
|
1049 | del ns[var] | |
1051 |
|
1050 | |||
1052 | def push(self, variables, interactive=True): |
|
1051 | def push(self, variables, interactive=True): | |
1053 | """Inject a group of variables into the IPython user namespace. |
|
1052 | """Inject a group of variables into the IPython user namespace. | |
1054 |
|
1053 | |||
1055 | Parameters |
|
1054 | Parameters | |
1056 | ---------- |
|
1055 | ---------- | |
1057 | variables : dict, str or list/tuple of str |
|
1056 | variables : dict, str or list/tuple of str | |
1058 | 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 | |
1059 | 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 | |
1060 | 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 | |
1061 | 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 | |
1062 | 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 | |
1063 | callers frame. |
|
1062 | callers frame. | |
1064 | interactive : bool |
|
1063 | interactive : bool | |
1065 | If True (default), the variables will be listed with the ``who`` |
|
1064 | If True (default), the variables will be listed with the ``who`` | |
1066 | magic. |
|
1065 | magic. | |
1067 | """ |
|
1066 | """ | |
1068 | vdict = None |
|
1067 | vdict = None | |
1069 |
|
1068 | |||
1070 | # 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. | |
1071 | if isinstance(variables, dict): |
|
1070 | if isinstance(variables, dict): | |
1072 | vdict = variables |
|
1071 | vdict = variables | |
1073 | elif isinstance(variables, (basestring, list, tuple)): |
|
1072 | elif isinstance(variables, (basestring, list, tuple)): | |
1074 | if isinstance(variables, basestring): |
|
1073 | if isinstance(variables, basestring): | |
1075 | vlist = variables.split() |
|
1074 | vlist = variables.split() | |
1076 | else: |
|
1075 | else: | |
1077 | vlist = variables |
|
1076 | vlist = variables | |
1078 | vdict = {} |
|
1077 | vdict = {} | |
1079 | cf = sys._getframe(1) |
|
1078 | cf = sys._getframe(1) | |
1080 | for name in vlist: |
|
1079 | for name in vlist: | |
1081 | try: |
|
1080 | try: | |
1082 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1081 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1083 | except: |
|
1082 | except: | |
1084 | print ('Could not get variable %s from %s' % |
|
1083 | print ('Could not get variable %s from %s' % | |
1085 | (name,cf.f_code.co_name)) |
|
1084 | (name,cf.f_code.co_name)) | |
1086 | else: |
|
1085 | else: | |
1087 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1086 | raise ValueError('variables must be a dict/str/list/tuple') | |
1088 |
|
1087 | |||
1089 | # Propagate variables to user namespace |
|
1088 | # Propagate variables to user namespace | |
1090 | self.user_ns.update(vdict) |
|
1089 | self.user_ns.update(vdict) | |
1091 |
|
1090 | |||
1092 | # And configure interactive visibility |
|
1091 | # And configure interactive visibility | |
1093 | config_ns = self.user_ns_hidden |
|
1092 | config_ns = self.user_ns_hidden | |
1094 | if interactive: |
|
1093 | if interactive: | |
1095 | for name, val in vdict.iteritems(): |
|
1094 | for name, val in vdict.iteritems(): | |
1096 | config_ns.pop(name, None) |
|
1095 | config_ns.pop(name, None) | |
1097 | else: |
|
1096 | else: | |
1098 | for name,val in vdict.iteritems(): |
|
1097 | for name,val in vdict.iteritems(): | |
1099 | config_ns[name] = val |
|
1098 | config_ns[name] = val | |
1100 |
|
1099 | |||
1101 | #------------------------------------------------------------------------- |
|
1100 | #------------------------------------------------------------------------- | |
1102 | # Things related to object introspection |
|
1101 | # Things related to object introspection | |
1103 | #------------------------------------------------------------------------- |
|
1102 | #------------------------------------------------------------------------- | |
1104 |
|
1103 | |||
1105 | def _ofind(self, oname, namespaces=None): |
|
1104 | def _ofind(self, oname, namespaces=None): | |
1106 | """Find an object in the available namespaces. |
|
1105 | """Find an object in the available namespaces. | |
1107 |
|
1106 | |||
1108 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1107 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1109 |
|
1108 | |||
1110 | Has special code to detect magic functions. |
|
1109 | Has special code to detect magic functions. | |
1111 | """ |
|
1110 | """ | |
1112 | #oname = oname.strip() |
|
1111 | #oname = oname.strip() | |
1113 | #print '1- oname: <%r>' % oname # dbg |
|
1112 | #print '1- oname: <%r>' % oname # dbg | |
1114 | try: |
|
1113 | try: | |
1115 | oname = oname.strip().encode('ascii') |
|
1114 | oname = oname.strip().encode('ascii') | |
1116 | #print '2- oname: <%r>' % oname # dbg |
|
1115 | #print '2- oname: <%r>' % oname # dbg | |
1117 | except UnicodeEncodeError: |
|
1116 | except UnicodeEncodeError: | |
1118 | print 'Python identifiers can only contain ascii characters.' |
|
1117 | print 'Python identifiers can only contain ascii characters.' | |
1119 | return dict(found=False) |
|
1118 | return dict(found=False) | |
1120 |
|
1119 | |||
1121 | alias_ns = None |
|
1120 | alias_ns = None | |
1122 | if namespaces is None: |
|
1121 | if namespaces is None: | |
1123 | # Namespaces to search in: |
|
1122 | # Namespaces to search in: | |
1124 | # 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 | |
1125 | # find things in the same order that Python finds them. |
|
1124 | # find things in the same order that Python finds them. | |
1126 | namespaces = [ ('Interactive', self.user_ns), |
|
1125 | namespaces = [ ('Interactive', self.user_ns), | |
1127 | ('IPython internal', self.internal_ns), |
|
1126 | ('IPython internal', self.internal_ns), | |
1128 | ('Python builtin', __builtin__.__dict__), |
|
1127 | ('Python builtin', __builtin__.__dict__), | |
1129 | ('Alias', self.alias_manager.alias_table), |
|
1128 | ('Alias', self.alias_manager.alias_table), | |
1130 | ] |
|
1129 | ] | |
1131 | alias_ns = self.alias_manager.alias_table |
|
1130 | alias_ns = self.alias_manager.alias_table | |
1132 |
|
1131 | |||
1133 | # initialize results to 'null' |
|
1132 | # initialize results to 'null' | |
1134 | found = False; obj = None; ospace = None; ds = None; |
|
1133 | found = False; obj = None; ospace = None; ds = None; | |
1135 | ismagic = False; isalias = False; parent = None |
|
1134 | ismagic = False; isalias = False; parent = None | |
1136 |
|
1135 | |||
1137 | # 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 | |
1138 | # 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 | |
1139 | # loaded with a future import. In this case, just bail. |
|
1138 | # loaded with a future import. In this case, just bail. | |
1140 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1139 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1141 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1140 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1142 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1143 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1144 |
|
1143 | |||
1145 | # 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 | |
1146 | # 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 | |
1147 | # declare success if we can find them all. |
|
1146 | # declare success if we can find them all. | |
1148 | oname_parts = oname.split('.') |
|
1147 | oname_parts = oname.split('.') | |
1149 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1148 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1150 | for nsname,ns in namespaces: |
|
1149 | for nsname,ns in namespaces: | |
1151 | try: |
|
1150 | try: | |
1152 | obj = ns[oname_head] |
|
1151 | obj = ns[oname_head] | |
1153 | except KeyError: |
|
1152 | except KeyError: | |
1154 | continue |
|
1153 | continue | |
1155 | else: |
|
1154 | else: | |
1156 | #print 'oname_rest:', oname_rest # dbg |
|
1155 | #print 'oname_rest:', oname_rest # dbg | |
1157 | for part in oname_rest: |
|
1156 | for part in oname_rest: | |
1158 | try: |
|
1157 | try: | |
1159 | parent = obj |
|
1158 | parent = obj | |
1160 | obj = getattr(obj,part) |
|
1159 | obj = getattr(obj,part) | |
1161 | except: |
|
1160 | except: | |
1162 | # Blanket except b/c some badly implemented objects |
|
1161 | # Blanket except b/c some badly implemented objects | |
1163 | # allow __getattr__ to raise exceptions other than |
|
1162 | # allow __getattr__ to raise exceptions other than | |
1164 | # AttributeError, which then crashes IPython. |
|
1163 | # AttributeError, which then crashes IPython. | |
1165 | break |
|
1164 | break | |
1166 | else: |
|
1165 | else: | |
1167 | # 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 | |
1168 | found = True |
|
1167 | found = True | |
1169 | ospace = nsname |
|
1168 | ospace = nsname | |
1170 | if ns == alias_ns: |
|
1169 | if ns == alias_ns: | |
1171 | isalias = True |
|
1170 | isalias = True | |
1172 | break # namespace loop |
|
1171 | break # namespace loop | |
1173 |
|
1172 | |||
1174 | # Try to see if it's magic |
|
1173 | # Try to see if it's magic | |
1175 | if not found: |
|
1174 | if not found: | |
1176 | if oname.startswith(ESC_MAGIC): |
|
1175 | if oname.startswith(ESC_MAGIC): | |
1177 | oname = oname[1:] |
|
1176 | oname = oname[1:] | |
1178 | obj = getattr(self,'magic_'+oname,None) |
|
1177 | obj = getattr(self,'magic_'+oname,None) | |
1179 | if obj is not None: |
|
1178 | if obj is not None: | |
1180 | found = True |
|
1179 | found = True | |
1181 | ospace = 'IPython internal' |
|
1180 | ospace = 'IPython internal' | |
1182 | ismagic = True |
|
1181 | ismagic = True | |
1183 |
|
1182 | |||
1184 | # Last try: special-case some literals like '', [], {}, etc: |
|
1183 | # Last try: special-case some literals like '', [], {}, etc: | |
1185 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1184 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1186 | obj = eval(oname_head) |
|
1185 | obj = eval(oname_head) | |
1187 | found = True |
|
1186 | found = True | |
1188 | ospace = 'Interactive' |
|
1187 | ospace = 'Interactive' | |
1189 |
|
1188 | |||
1190 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1189 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1191 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1190 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1192 |
|
1191 | |||
1193 | def _ofind_property(self, oname, info): |
|
1192 | def _ofind_property(self, oname, info): | |
1194 | """Second part of object finding, to look for property details.""" |
|
1193 | """Second part of object finding, to look for property details.""" | |
1195 | if info.found: |
|
1194 | if info.found: | |
1196 | # Get the docstring of the class property if it exists. |
|
1195 | # Get the docstring of the class property if it exists. | |
1197 | path = oname.split('.') |
|
1196 | path = oname.split('.') | |
1198 | root = '.'.join(path[:-1]) |
|
1197 | root = '.'.join(path[:-1]) | |
1199 | if info.parent is not None: |
|
1198 | if info.parent is not None: | |
1200 | try: |
|
1199 | try: | |
1201 | target = getattr(info.parent, '__class__') |
|
1200 | target = getattr(info.parent, '__class__') | |
1202 | # The object belongs to a class instance. |
|
1201 | # The object belongs to a class instance. | |
1203 | try: |
|
1202 | try: | |
1204 | target = getattr(target, path[-1]) |
|
1203 | target = getattr(target, path[-1]) | |
1205 | # The class defines the object. |
|
1204 | # The class defines the object. | |
1206 | if isinstance(target, property): |
|
1205 | if isinstance(target, property): | |
1207 | oname = root + '.__class__.' + path[-1] |
|
1206 | oname = root + '.__class__.' + path[-1] | |
1208 | info = Struct(self._ofind(oname)) |
|
1207 | info = Struct(self._ofind(oname)) | |
1209 | except AttributeError: pass |
|
1208 | except AttributeError: pass | |
1210 | except AttributeError: pass |
|
1209 | except AttributeError: pass | |
1211 |
|
1210 | |||
1212 | # 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 | |
1213 | # hadn't been found |
|
1212 | # hadn't been found | |
1214 | return info |
|
1213 | return info | |
1215 |
|
1214 | |||
1216 | def _object_find(self, oname, namespaces=None): |
|
1215 | def _object_find(self, oname, namespaces=None): | |
1217 | """Find an object and return a struct with info about it.""" |
|
1216 | """Find an object and return a struct with info about it.""" | |
1218 | inf = Struct(self._ofind(oname, namespaces)) |
|
1217 | inf = Struct(self._ofind(oname, namespaces)) | |
1219 | return Struct(self._ofind_property(oname, inf)) |
|
1218 | return Struct(self._ofind_property(oname, inf)) | |
1220 |
|
1219 | |||
1221 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1220 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1222 | """Generic interface to the inspector system. |
|
1221 | """Generic interface to the inspector system. | |
1223 |
|
1222 | |||
1224 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1223 | This function is meant to be called by pdef, pdoc & friends.""" | |
1225 | info = self._object_find(oname) |
|
1224 | info = self._object_find(oname) | |
1226 | if info.found: |
|
1225 | if info.found: | |
1227 | pmethod = getattr(self.inspector, meth) |
|
1226 | pmethod = getattr(self.inspector, meth) | |
1228 | formatter = format_screen if info.ismagic else None |
|
1227 | formatter = format_screen if info.ismagic else None | |
1229 | if meth == 'pdoc': |
|
1228 | if meth == 'pdoc': | |
1230 | pmethod(info.obj, oname, formatter) |
|
1229 | pmethod(info.obj, oname, formatter) | |
1231 | elif meth == 'pinfo': |
|
1230 | elif meth == 'pinfo': | |
1232 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1231 | pmethod(info.obj, oname, formatter, info, **kw) | |
1233 | else: |
|
1232 | else: | |
1234 | pmethod(info.obj, oname) |
|
1233 | pmethod(info.obj, oname) | |
1235 | else: |
|
1234 | else: | |
1236 | print 'Object `%s` not found.' % oname |
|
1235 | print 'Object `%s` not found.' % oname | |
1237 | return 'not found' # so callers can take other action |
|
1236 | return 'not found' # so callers can take other action | |
1238 |
|
1237 | |||
1239 | def object_inspect(self, oname): |
|
1238 | def object_inspect(self, oname): | |
1240 | info = self._object_find(oname) |
|
1239 | info = self._object_find(oname) | |
1241 | if info.found: |
|
1240 | if info.found: | |
1242 | return self.inspector.info(info.obj, oname, info=info) |
|
1241 | return self.inspector.info(info.obj, oname, info=info) | |
1243 | else: |
|
1242 | else: | |
1244 | return oinspect.object_info(name=oname, found=False) |
|
1243 | return oinspect.object_info(name=oname, found=False) | |
1245 |
|
1244 | |||
1246 | #------------------------------------------------------------------------- |
|
1245 | #------------------------------------------------------------------------- | |
1247 | # Things related to history management |
|
1246 | # Things related to history management | |
1248 | #------------------------------------------------------------------------- |
|
1247 | #------------------------------------------------------------------------- | |
1249 |
|
1248 | |||
1250 | def init_history(self): |
|
1249 | def init_history(self): | |
1251 | """Sets up the command history, and starts regular autosaves.""" |
|
1250 | """Sets up the command history, and starts regular autosaves.""" | |
1252 | self.history_manager = HistoryManager(shell=self) |
|
1251 | self.history_manager = HistoryManager(shell=self) | |
1253 |
|
1252 | |||
1254 | def save_history(self): |
|
1253 | def save_history(self): | |
1255 | """Save input history to a file (via readline library).""" |
|
1254 | """Save input history to a file (via readline library).""" | |
1256 | self.history_manager.save_history() |
|
1255 | self.history_manager.save_history() | |
1257 |
|
1256 | |||
1258 | def reload_history(self): |
|
1257 | def reload_history(self): | |
1259 | """Reload the input history from disk file.""" |
|
1258 | """Reload the input history from disk file.""" | |
1260 | self.history_manager.reload_history() |
|
1259 | self.history_manager.reload_history() | |
1261 |
|
1260 | |||
1262 | def history_saving_wrapper(self, func): |
|
1261 | def history_saving_wrapper(self, func): | |
1263 | """ Wrap func for readline history saving |
|
1262 | """ Wrap func for readline history saving | |
1264 |
|
1263 | |||
1265 | Convert func into callable that saves & restores |
|
1264 | Convert func into callable that saves & restores | |
1266 | history around the call """ |
|
1265 | history around the call """ | |
1267 |
|
1266 | |||
1268 | if self.has_readline: |
|
1267 | if self.has_readline: | |
1269 | from IPython.utils import rlineimpl as readline |
|
1268 | from IPython.utils import rlineimpl as readline | |
1270 | else: |
|
1269 | else: | |
1271 | return func |
|
1270 | return func | |
1272 |
|
1271 | |||
1273 | def wrapper(): |
|
1272 | def wrapper(): | |
1274 | self.save_history() |
|
1273 | self.save_history() | |
1275 | try: |
|
1274 | try: | |
1276 | func() |
|
1275 | func() | |
1277 | finally: |
|
1276 | finally: | |
1278 | self.reload_history() |
|
1277 | self.reload_history() | |
1279 | return wrapper |
|
1278 | return wrapper | |
1280 |
|
1279 | |||
1281 | def get_history(self, index=None, raw=False, output=True): |
|
1280 | def get_history(self, index=None, raw=False, output=True): | |
1282 | return self.history_manager.get_history(index, raw, output) |
|
1281 | return self.history_manager.get_history(index, raw, output) | |
1283 |
|
1282 | |||
1284 |
|
1283 | |||
1285 | #------------------------------------------------------------------------- |
|
1284 | #------------------------------------------------------------------------- | |
1286 | # Things related to exception handling and tracebacks (not debugging) |
|
1285 | # Things related to exception handling and tracebacks (not debugging) | |
1287 | #------------------------------------------------------------------------- |
|
1286 | #------------------------------------------------------------------------- | |
1288 |
|
1287 | |||
1289 | def init_traceback_handlers(self, custom_exceptions): |
|
1288 | def init_traceback_handlers(self, custom_exceptions): | |
1290 | # Syntax error handler. |
|
1289 | # Syntax error handler. | |
1291 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1290 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1292 |
|
1291 | |||
1293 | # The interactive one is initialized with an offset, meaning we always |
|
1292 | # The interactive one is initialized with an offset, meaning we always | |
1294 | # 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 | |
1295 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1294 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1296 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1295 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1297 | color_scheme='NoColor', |
|
1296 | color_scheme='NoColor', | |
1298 | tb_offset = 1, |
|
1297 | tb_offset = 1, | |
1299 | check_cache=self.compile.check_cache) |
|
1298 | check_cache=self.compile.check_cache) | |
1300 |
|
1299 | |||
1301 | # 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, | |
1302 | # 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 | |
1303 | # during the read-eval loop, it may get temporarily overwritten. |
|
1302 | # during the read-eval loop, it may get temporarily overwritten. | |
1304 | self.sys_excepthook = sys.excepthook |
|
1303 | self.sys_excepthook = sys.excepthook | |
1305 |
|
1304 | |||
1306 | # and add any custom exception handlers the user may have specified |
|
1305 | # and add any custom exception handlers the user may have specified | |
1307 | self.set_custom_exc(*custom_exceptions) |
|
1306 | self.set_custom_exc(*custom_exceptions) | |
1308 |
|
1307 | |||
1309 | # Set the exception mode |
|
1308 | # Set the exception mode | |
1310 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1309 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1311 |
|
1310 | |||
1312 | def set_custom_exc(self, exc_tuple, handler): |
|
1311 | def set_custom_exc(self, exc_tuple, handler): | |
1313 | """set_custom_exc(exc_tuple,handler) |
|
1312 | """set_custom_exc(exc_tuple,handler) | |
1314 |
|
1313 | |||
1315 | 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 | |
1316 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1315 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1317 | run_code() method. |
|
1316 | run_code() method. | |
1318 |
|
1317 | |||
1319 | Inputs: |
|
1318 | Inputs: | |
1320 |
|
1319 | |||
1321 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1320 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1322 | 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 | |
1323 | 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 | |
1324 | 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: | |
1325 |
|
1324 | |||
1326 | exc_tuple == (MyCustomException,) |
|
1325 | exc_tuple == (MyCustomException,) | |
1327 |
|
1326 | |||
1328 | - handler: this must be defined as a function with the following |
|
1327 | - handler: this must be defined as a function with the following | |
1329 | basic interface:: |
|
1328 | basic interface:: | |
1330 |
|
1329 | |||
1331 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1330 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1332 | ... |
|
1331 | ... | |
1333 | # The return value must be |
|
1332 | # The return value must be | |
1334 | return structured_traceback |
|
1333 | return structured_traceback | |
1335 |
|
1334 | |||
1336 | This will be made into an instance method (via types.MethodType) |
|
1335 | This will be made into an instance method (via types.MethodType) | |
1337 | 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 | |
1338 | 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 | |
1339 | internal basic one is used, which just prints basic info. |
|
1338 | internal basic one is used, which just prints basic info. | |
1340 |
|
1339 | |||
1341 | 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 | |
1342 | 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 | |
1343 | 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.""" | |
1344 |
|
1343 | |||
1345 | assert type(exc_tuple)==type(()) , \ |
|
1344 | assert type(exc_tuple)==type(()) , \ | |
1346 | "The custom exceptions must be given AS A TUPLE." |
|
1345 | "The custom exceptions must be given AS A TUPLE." | |
1347 |
|
1346 | |||
1348 | def dummy_handler(self,etype,value,tb): |
|
1347 | def dummy_handler(self,etype,value,tb): | |
1349 | print '*** Simple custom exception handler ***' |
|
1348 | print '*** Simple custom exception handler ***' | |
1350 | print 'Exception type :',etype |
|
1349 | print 'Exception type :',etype | |
1351 | print 'Exception value:',value |
|
1350 | print 'Exception value:',value | |
1352 | print 'Traceback :',tb |
|
1351 | print 'Traceback :',tb | |
1353 | print 'Source code :','\n'.join(self.buffer) |
|
1352 | print 'Source code :','\n'.join(self.buffer) | |
1354 |
|
1353 | |||
1355 | if handler is None: handler = dummy_handler |
|
1354 | if handler is None: handler = dummy_handler | |
1356 |
|
1355 | |||
1357 | self.CustomTB = types.MethodType(handler,self) |
|
1356 | self.CustomTB = types.MethodType(handler,self) | |
1358 | self.custom_exceptions = exc_tuple |
|
1357 | self.custom_exceptions = exc_tuple | |
1359 |
|
1358 | |||
1360 | def excepthook(self, etype, value, tb): |
|
1359 | def excepthook(self, etype, value, tb): | |
1361 | """One more defense for GUI apps that call sys.excepthook. |
|
1360 | """One more defense for GUI apps that call sys.excepthook. | |
1362 |
|
1361 | |||
1363 | GUI frameworks like wxPython trap exceptions and call |
|
1362 | GUI frameworks like wxPython trap exceptions and call | |
1364 | sys.excepthook themselves. I guess this is a feature that |
|
1363 | sys.excepthook themselves. I guess this is a feature that | |
1365 | enables them to keep running after exceptions that would |
|
1364 | enables them to keep running after exceptions that would | |
1366 | otherwise kill their mainloop. This is a bother for IPython |
|
1365 | otherwise kill their mainloop. This is a bother for IPython | |
1367 | 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: | |
1368 | except: statement. |
|
1367 | except: statement. | |
1369 |
|
1368 | |||
1370 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1369 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1371 | 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 | |
1372 | 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 | |
1373 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1372 | CrashHandler and replace it with this excepthook instead, which prints a | |
1374 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1373 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1375 | call sys.excepthook will generate a regular-looking exception from |
|
1374 | call sys.excepthook will generate a regular-looking exception from | |
1376 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1375 | IPython, and the CrashHandler will only be triggered by real IPython | |
1377 | crashes. |
|
1376 | crashes. | |
1378 |
|
1377 | |||
1379 | 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 | |
1380 | to be true IPython errors. |
|
1379 | to be true IPython errors. | |
1381 | """ |
|
1380 | """ | |
1382 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1381 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1383 |
|
1382 | |||
1384 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1383 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1385 | exception_only=False): |
|
1384 | exception_only=False): | |
1386 | """Display the exception that just occurred. |
|
1385 | """Display the exception that just occurred. | |
1387 |
|
1386 | |||
1388 | 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 | |
1389 | should be used throughout the code for presenting user tracebacks, |
|
1388 | should be used throughout the code for presenting user tracebacks, | |
1390 | rather than directly invoking the InteractiveTB object. |
|
1389 | rather than directly invoking the InteractiveTB object. | |
1391 |
|
1390 | |||
1392 | A specific showsyntaxerror() also exists, but this method can take |
|
1391 | A specific showsyntaxerror() also exists, but this method can take | |
1393 | 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 | |
1394 | SyntaxError exception, don't try to analyze the stack manually and |
|
1393 | SyntaxError exception, don't try to analyze the stack manually and | |
1395 | simply call this method.""" |
|
1394 | simply call this method.""" | |
1396 |
|
1395 | |||
1397 | try: |
|
1396 | try: | |
1398 | if exc_tuple is None: |
|
1397 | if exc_tuple is None: | |
1399 | etype, value, tb = sys.exc_info() |
|
1398 | etype, value, tb = sys.exc_info() | |
1400 | else: |
|
1399 | else: | |
1401 | etype, value, tb = exc_tuple |
|
1400 | etype, value, tb = exc_tuple | |
1402 |
|
1401 | |||
1403 | if etype is None: |
|
1402 | if etype is None: | |
1404 | if hasattr(sys, 'last_type'): |
|
1403 | if hasattr(sys, 'last_type'): | |
1405 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1404 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1406 | sys.last_traceback |
|
1405 | sys.last_traceback | |
1407 | else: |
|
1406 | else: | |
1408 | self.write_err('No traceback available to show.\n') |
|
1407 | self.write_err('No traceback available to show.\n') | |
1409 | return |
|
1408 | return | |
1410 |
|
1409 | |||
1411 | if etype is SyntaxError: |
|
1410 | if etype is SyntaxError: | |
1412 | # 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 | |
1413 | # line, there may be SyntaxError cases whith imported code. |
|
1412 | # line, there may be SyntaxError cases whith imported code. | |
1414 | self.showsyntaxerror(filename) |
|
1413 | self.showsyntaxerror(filename) | |
1415 | elif etype is UsageError: |
|
1414 | elif etype is UsageError: | |
1416 | print "UsageError:", value |
|
1415 | print "UsageError:", value | |
1417 | else: |
|
1416 | else: | |
1418 | # WARNING: these variables are somewhat deprecated and not |
|
1417 | # WARNING: these variables are somewhat deprecated and not | |
1419 | # necessarily safe to use in a threaded environment, but tools |
|
1418 | # necessarily safe to use in a threaded environment, but tools | |
1420 | # 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 | |
1421 | # 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. | |
1422 | sys.last_type = etype |
|
1421 | sys.last_type = etype | |
1423 | sys.last_value = value |
|
1422 | sys.last_value = value | |
1424 | sys.last_traceback = tb |
|
1423 | sys.last_traceback = tb | |
1425 |
|
1424 | |||
1426 | if etype in self.custom_exceptions: |
|
1425 | if etype in self.custom_exceptions: | |
1427 | # FIXME: Old custom traceback objects may just return a |
|
1426 | # FIXME: Old custom traceback objects may just return a | |
1428 | # string, in that case we just put it into a list |
|
1427 | # string, in that case we just put it into a list | |
1429 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1428 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1430 | if isinstance(ctb, basestring): |
|
1429 | if isinstance(ctb, basestring): | |
1431 | stb = [stb] |
|
1430 | stb = [stb] | |
1432 | else: |
|
1431 | else: | |
1433 | if exception_only: |
|
1432 | if exception_only: | |
1434 | stb = ['An exception has occurred, use %tb to see ' |
|
1433 | stb = ['An exception has occurred, use %tb to see ' | |
1435 | 'the full traceback.\n'] |
|
1434 | 'the full traceback.\n'] | |
1436 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1435 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1437 | value)) |
|
1436 | value)) | |
1438 | else: |
|
1437 | else: | |
1439 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1438 | stb = self.InteractiveTB.structured_traceback(etype, | |
1440 | value, tb, tb_offset=tb_offset) |
|
1439 | value, tb, tb_offset=tb_offset) | |
1441 | # FIXME: the pdb calling should be done by us, not by |
|
1440 | # FIXME: the pdb calling should be done by us, not by | |
1442 | # the code computing the traceback. |
|
1441 | # the code computing the traceback. | |
1443 | if self.InteractiveTB.call_pdb: |
|
1442 | if self.InteractiveTB.call_pdb: | |
1444 | # pdb mucks up readline, fix it back |
|
1443 | # pdb mucks up readline, fix it back | |
1445 | self.set_readline_completer() |
|
1444 | self.set_readline_completer() | |
1446 |
|
1445 | |||
1447 | # Actually show the traceback |
|
1446 | # Actually show the traceback | |
1448 | self._showtraceback(etype, value, stb) |
|
1447 | self._showtraceback(etype, value, stb) | |
1449 |
|
1448 | |||
1450 | except KeyboardInterrupt: |
|
1449 | except KeyboardInterrupt: | |
1451 | self.write_err("\nKeyboardInterrupt\n") |
|
1450 | self.write_err("\nKeyboardInterrupt\n") | |
1452 |
|
1451 | |||
1453 | def _showtraceback(self, etype, evalue, stb): |
|
1452 | def _showtraceback(self, etype, evalue, stb): | |
1454 | """Actually show a traceback. |
|
1453 | """Actually show a traceback. | |
1455 |
|
1454 | |||
1456 | 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 | |
1457 | place, like a side channel. |
|
1456 | place, like a side channel. | |
1458 | """ |
|
1457 | """ | |
1459 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1458 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1460 |
|
1459 | |||
1461 | def showsyntaxerror(self, filename=None): |
|
1460 | def showsyntaxerror(self, filename=None): | |
1462 | """Display the syntax error that just occurred. |
|
1461 | """Display the syntax error that just occurred. | |
1463 |
|
1462 | |||
1464 | 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. | |
1465 |
|
1464 | |||
1466 | 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 | |
1467 | of what was there before (because Python's parser always uses |
|
1466 | of what was there before (because Python's parser always uses | |
1468 | "<string>" when reading from a string). |
|
1467 | "<string>" when reading from a string). | |
1469 | """ |
|
1468 | """ | |
1470 | etype, value, last_traceback = sys.exc_info() |
|
1469 | etype, value, last_traceback = sys.exc_info() | |
1471 |
|
1470 | |||
1472 | # See note about these variables in showtraceback() above |
|
1471 | # See note about these variables in showtraceback() above | |
1473 | sys.last_type = etype |
|
1472 | sys.last_type = etype | |
1474 | sys.last_value = value |
|
1473 | sys.last_value = value | |
1475 | sys.last_traceback = last_traceback |
|
1474 | sys.last_traceback = last_traceback | |
1476 |
|
1475 | |||
1477 | if filename and etype is SyntaxError: |
|
1476 | if filename and etype is SyntaxError: | |
1478 | # Work hard to stuff the correct filename in the exception |
|
1477 | # Work hard to stuff the correct filename in the exception | |
1479 | try: |
|
1478 | try: | |
1480 | msg, (dummy_filename, lineno, offset, line) = value |
|
1479 | msg, (dummy_filename, lineno, offset, line) = value | |
1481 | except: |
|
1480 | except: | |
1482 | # Not the format we expect; leave it alone |
|
1481 | # Not the format we expect; leave it alone | |
1483 | pass |
|
1482 | pass | |
1484 | else: |
|
1483 | else: | |
1485 | # Stuff in the right filename |
|
1484 | # Stuff in the right filename | |
1486 | try: |
|
1485 | try: | |
1487 | # Assume SyntaxError is a class exception |
|
1486 | # Assume SyntaxError is a class exception | |
1488 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1487 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1489 | except: |
|
1488 | except: | |
1490 | # If that failed, assume SyntaxError is a string |
|
1489 | # If that failed, assume SyntaxError is a string | |
1491 | value = msg, (filename, lineno, offset, line) |
|
1490 | value = msg, (filename, lineno, offset, line) | |
1492 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1491 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1493 | self._showtraceback(etype, value, stb) |
|
1492 | self._showtraceback(etype, value, stb) | |
1494 |
|
1493 | |||
1495 | #------------------------------------------------------------------------- |
|
1494 | #------------------------------------------------------------------------- | |
1496 | # Things related to readline |
|
1495 | # Things related to readline | |
1497 | #------------------------------------------------------------------------- |
|
1496 | #------------------------------------------------------------------------- | |
1498 |
|
1497 | |||
1499 | def init_readline(self): |
|
1498 | def init_readline(self): | |
1500 | """Command history completion/saving/reloading.""" |
|
1499 | """Command history completion/saving/reloading.""" | |
1501 |
|
1500 | |||
1502 | if self.readline_use: |
|
1501 | if self.readline_use: | |
1503 | import IPython.utils.rlineimpl as readline |
|
1502 | import IPython.utils.rlineimpl as readline | |
1504 |
|
1503 | |||
1505 | self.rl_next_input = None |
|
1504 | self.rl_next_input = None | |
1506 | self.rl_do_indent = False |
|
1505 | self.rl_do_indent = False | |
1507 |
|
1506 | |||
1508 | if not self.readline_use or not readline.have_readline: |
|
1507 | if not self.readline_use or not readline.have_readline: | |
1509 | self.has_readline = False |
|
1508 | self.has_readline = False | |
1510 | self.readline = None |
|
1509 | self.readline = None | |
1511 | # 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 | |
1512 | self.set_readline_completer = no_op |
|
1511 | self.set_readline_completer = no_op | |
1513 | self.set_custom_completer = no_op |
|
1512 | self.set_custom_completer = no_op | |
1514 | self.set_completer_frame = no_op |
|
1513 | self.set_completer_frame = no_op | |
1515 | warn('Readline services not available or not loaded.') |
|
1514 | warn('Readline services not available or not loaded.') | |
1516 | else: |
|
1515 | else: | |
1517 | self.has_readline = True |
|
1516 | self.has_readline = True | |
1518 | self.readline = readline |
|
1517 | self.readline = readline | |
1519 | sys.modules['readline'] = readline |
|
1518 | sys.modules['readline'] = readline | |
1520 |
|
1519 | |||
1521 | # Platform-specific configuration |
|
1520 | # Platform-specific configuration | |
1522 | if os.name == 'nt': |
|
1521 | if os.name == 'nt': | |
1523 | # FIXME - check with Frederick to see if we can harmonize |
|
1522 | # FIXME - check with Frederick to see if we can harmonize | |
1524 | # naming conventions with pyreadline to avoid this |
|
1523 | # naming conventions with pyreadline to avoid this | |
1525 | # platform-dependent check |
|
1524 | # platform-dependent check | |
1526 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1525 | self.readline_startup_hook = readline.set_pre_input_hook | |
1527 | else: |
|
1526 | else: | |
1528 | self.readline_startup_hook = readline.set_startup_hook |
|
1527 | self.readline_startup_hook = readline.set_startup_hook | |
1529 |
|
1528 | |||
1530 | # Load user's initrc file (readline config) |
|
1529 | # Load user's initrc file (readline config) | |
1531 | # Or if libedit is used, load editrc. |
|
1530 | # Or if libedit is used, load editrc. | |
1532 | inputrc_name = os.environ.get('INPUTRC') |
|
1531 | inputrc_name = os.environ.get('INPUTRC') | |
1533 | if inputrc_name is None: |
|
1532 | if inputrc_name is None: | |
1534 | home_dir = get_home_dir() |
|
1533 | home_dir = get_home_dir() | |
1535 | if home_dir is not None: |
|
1534 | if home_dir is not None: | |
1536 | inputrc_name = '.inputrc' |
|
1535 | inputrc_name = '.inputrc' | |
1537 | if readline.uses_libedit: |
|
1536 | if readline.uses_libedit: | |
1538 | inputrc_name = '.editrc' |
|
1537 | inputrc_name = '.editrc' | |
1539 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1538 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1540 | if os.path.isfile(inputrc_name): |
|
1539 | if os.path.isfile(inputrc_name): | |
1541 | try: |
|
1540 | try: | |
1542 | readline.read_init_file(inputrc_name) |
|
1541 | readline.read_init_file(inputrc_name) | |
1543 | except: |
|
1542 | except: | |
1544 | warn('Problems reading readline initialization file <%s>' |
|
1543 | warn('Problems reading readline initialization file <%s>' | |
1545 | % inputrc_name) |
|
1544 | % inputrc_name) | |
1546 |
|
1545 | |||
1547 | # Configure readline according to user's prefs |
|
1546 | # Configure readline according to user's prefs | |
1548 | # 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 | |
1549 | # is being used (as on Leopard) the readline config is |
|
1548 | # is being used (as on Leopard) the readline config is | |
1550 | # not run as the syntax for libedit is different. |
|
1549 | # not run as the syntax for libedit is different. | |
1551 | if not readline.uses_libedit: |
|
1550 | if not readline.uses_libedit: | |
1552 | for rlcommand in self.readline_parse_and_bind: |
|
1551 | for rlcommand in self.readline_parse_and_bind: | |
1553 | #print "loading rl:",rlcommand # dbg |
|
1552 | #print "loading rl:",rlcommand # dbg | |
1554 | readline.parse_and_bind(rlcommand) |
|
1553 | readline.parse_and_bind(rlcommand) | |
1555 |
|
1554 | |||
1556 | # Remove some chars from the delimiters list. If we encounter |
|
1555 | # Remove some chars from the delimiters list. If we encounter | |
1557 | # unicode chars, discard them. |
|
1556 | # unicode chars, discard them. | |
1558 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1557 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1559 | delims = delims.translate(None, self.readline_remove_delims) |
|
1558 | delims = delims.translate(None, self.readline_remove_delims) | |
1560 | delims = delims.replace(ESC_MAGIC, '') |
|
1559 | delims = delims.replace(ESC_MAGIC, '') | |
1561 | readline.set_completer_delims(delims) |
|
1560 | readline.set_completer_delims(delims) | |
1562 | # otherwise we end up with a monster history after a while: |
|
1561 | # otherwise we end up with a monster history after a while: | |
1563 | readline.set_history_length(self.history_length) |
|
1562 | readline.set_history_length(self.history_length) | |
1564 | try: |
|
1563 | try: | |
1565 | #print '*** Reading readline history' # dbg |
|
1564 | #print '*** Reading readline history' # dbg | |
1566 | self.reload_history() |
|
1565 | self.reload_history() | |
1567 | except IOError: |
|
1566 | except IOError: | |
1568 | pass # It doesn't exist yet. |
|
1567 | pass # It doesn't exist yet. | |
1569 |
|
1568 | |||
1570 | # Configure auto-indent for all platforms |
|
1569 | # Configure auto-indent for all platforms | |
1571 | self.set_autoindent(self.autoindent) |
|
1570 | self.set_autoindent(self.autoindent) | |
1572 |
|
1571 | |||
1573 | def set_next_input(self, s): |
|
1572 | def set_next_input(self, s): | |
1574 | """ Sets the 'default' input string for the next command line. |
|
1573 | """ Sets the 'default' input string for the next command line. | |
1575 |
|
1574 | |||
1576 | Requires readline. |
|
1575 | Requires readline. | |
1577 |
|
1576 | |||
1578 | Example: |
|
1577 | Example: | |
1579 |
|
1578 | |||
1580 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1579 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1581 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1580 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1582 | """ |
|
1581 | """ | |
1583 |
|
1582 | |||
1584 | self.rl_next_input = s |
|
1583 | self.rl_next_input = s | |
1585 |
|
1584 | |||
1586 | # Maybe move this to the terminal subclass? |
|
1585 | # Maybe move this to the terminal subclass? | |
1587 | def pre_readline(self): |
|
1586 | def pre_readline(self): | |
1588 | """readline hook to be used at the start of each line. |
|
1587 | """readline hook to be used at the start of each line. | |
1589 |
|
1588 | |||
1590 | Currently it handles auto-indent only.""" |
|
1589 | Currently it handles auto-indent only.""" | |
1591 |
|
1590 | |||
1592 | if self.rl_do_indent: |
|
1591 | if self.rl_do_indent: | |
1593 | self.readline.insert_text(self._indent_current_str()) |
|
1592 | self.readline.insert_text(self._indent_current_str()) | |
1594 | if self.rl_next_input is not None: |
|
1593 | if self.rl_next_input is not None: | |
1595 | self.readline.insert_text(self.rl_next_input) |
|
1594 | self.readline.insert_text(self.rl_next_input) | |
1596 | self.rl_next_input = None |
|
1595 | self.rl_next_input = None | |
1597 |
|
1596 | |||
1598 | def _indent_current_str(self): |
|
1597 | def _indent_current_str(self): | |
1599 | """return the current level of indentation as a string""" |
|
1598 | """return the current level of indentation as a string""" | |
1600 | return self.input_splitter.indent_spaces * ' ' |
|
1599 | return self.input_splitter.indent_spaces * ' ' | |
1601 |
|
1600 | |||
1602 | #------------------------------------------------------------------------- |
|
1601 | #------------------------------------------------------------------------- | |
1603 | # Things related to text completion |
|
1602 | # Things related to text completion | |
1604 | #------------------------------------------------------------------------- |
|
1603 | #------------------------------------------------------------------------- | |
1605 |
|
1604 | |||
1606 | def init_completer(self): |
|
1605 | def init_completer(self): | |
1607 | """Initialize the completion machinery. |
|
1606 | """Initialize the completion machinery. | |
1608 |
|
1607 | |||
1609 | This creates completion machinery that can be used by client code, |
|
1608 | This creates completion machinery that can be used by client code, | |
1610 | either interactively in-process (typically triggered by the readline |
|
1609 | either interactively in-process (typically triggered by the readline | |
1611 | library), programatically (such as in test suites) or out-of-prcess |
|
1610 | library), programatically (such as in test suites) or out-of-prcess | |
1612 | (typically over the network by remote frontends). |
|
1611 | (typically over the network by remote frontends). | |
1613 | """ |
|
1612 | """ | |
1614 | from IPython.core.completer import IPCompleter |
|
1613 | from IPython.core.completer import IPCompleter | |
1615 | from IPython.core.completerlib import (module_completer, |
|
1614 | from IPython.core.completerlib import (module_completer, | |
1616 | magic_run_completer, cd_completer) |
|
1615 | magic_run_completer, cd_completer) | |
1617 |
|
1616 | |||
1618 | self.Completer = IPCompleter(self, |
|
1617 | self.Completer = IPCompleter(self, | |
1619 | self.user_ns, |
|
1618 | self.user_ns, | |
1620 | self.user_global_ns, |
|
1619 | self.user_global_ns, | |
1621 | self.readline_omit__names, |
|
1620 | self.readline_omit__names, | |
1622 | self.alias_manager.alias_table, |
|
1621 | self.alias_manager.alias_table, | |
1623 | self.has_readline) |
|
1622 | self.has_readline) | |
1624 |
|
1623 | |||
1625 | # Add custom completers to the basic ones built into IPCompleter |
|
1624 | # Add custom completers to the basic ones built into IPCompleter | |
1626 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1625 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1627 | self.strdispatchers['complete_command'] = sdisp |
|
1626 | self.strdispatchers['complete_command'] = sdisp | |
1628 | self.Completer.custom_completers = sdisp |
|
1627 | self.Completer.custom_completers = sdisp | |
1629 |
|
1628 | |||
1630 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1629 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1631 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1630 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1632 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1631 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1633 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1632 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1634 |
|
1633 | |||
1635 | # Only configure readline if we truly are using readline. IPython can |
|
1634 | # Only configure readline if we truly are using readline. IPython can | |
1636 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1635 | # do tab-completion over the network, in GUIs, etc, where readline | |
1637 | # itself may be absent |
|
1636 | # itself may be absent | |
1638 | if self.has_readline: |
|
1637 | if self.has_readline: | |
1639 | self.set_readline_completer() |
|
1638 | self.set_readline_completer() | |
1640 |
|
1639 | |||
1641 | def complete(self, text, line=None, cursor_pos=None): |
|
1640 | def complete(self, text, line=None, cursor_pos=None): | |
1642 | """Return the completed text and a list of completions. |
|
1641 | """Return the completed text and a list of completions. | |
1643 |
|
1642 | |||
1644 | Parameters |
|
1643 | Parameters | |
1645 | ---------- |
|
1644 | ---------- | |
1646 |
|
1645 | |||
1647 | text : string |
|
1646 | text : string | |
1648 | 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 | |
1649 | instead a line/position pair are given. In this case, the |
|
1648 | instead a line/position pair are given. In this case, the | |
1650 | completer itself will split the line like readline does. |
|
1649 | completer itself will split the line like readline does. | |
1651 |
|
1650 | |||
1652 | line : string, optional |
|
1651 | line : string, optional | |
1653 | The complete line that text is part of. |
|
1652 | The complete line that text is part of. | |
1654 |
|
1653 | |||
1655 | cursor_pos : int, optional |
|
1654 | cursor_pos : int, optional | |
1656 | The position of the cursor on the input line. |
|
1655 | The position of the cursor on the input line. | |
1657 |
|
1656 | |||
1658 | Returns |
|
1657 | Returns | |
1659 | ------- |
|
1658 | ------- | |
1660 | text : string |
|
1659 | text : string | |
1661 | The actual text that was completed. |
|
1660 | The actual text that was completed. | |
1662 |
|
1661 | |||
1663 | matches : list |
|
1662 | matches : list | |
1664 | A sorted list with all possible completions. |
|
1663 | A sorted list with all possible completions. | |
1665 |
|
1664 | |||
1666 | The optional arguments allow the completion to take more context into |
|
1665 | The optional arguments allow the completion to take more context into | |
1667 | account, and are part of the low-level completion API. |
|
1666 | account, and are part of the low-level completion API. | |
1668 |
|
1667 | |||
1669 | This is a wrapper around the completion mechanism, similar to what |
|
1668 | This is a wrapper around the completion mechanism, similar to what | |
1670 | 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 | |
1671 | 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 | |
1672 | environments (such as GUIs) for text completion. |
|
1671 | environments (such as GUIs) for text completion. | |
1673 |
|
1672 | |||
1674 | Simple usage example: |
|
1673 | Simple usage example: | |
1675 |
|
1674 | |||
1676 | In [1]: x = 'hello' |
|
1675 | In [1]: x = 'hello' | |
1677 |
|
1676 | |||
1678 | In [2]: _ip.complete('x.l') |
|
1677 | In [2]: _ip.complete('x.l') | |
1679 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1678 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1680 | """ |
|
1679 | """ | |
1681 |
|
1680 | |||
1682 | # 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. | |
1683 | with self.builtin_trap: |
|
1682 | with self.builtin_trap: | |
1684 | return self.Completer.complete(text, line, cursor_pos) |
|
1683 | return self.Completer.complete(text, line, cursor_pos) | |
1685 |
|
1684 | |||
1686 | def set_custom_completer(self, completer, pos=0): |
|
1685 | def set_custom_completer(self, completer, pos=0): | |
1687 | """Adds a new custom completer function. |
|
1686 | """Adds a new custom completer function. | |
1688 |
|
1687 | |||
1689 | 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 | |
1690 | list where you want the completer to be inserted.""" |
|
1689 | list where you want the completer to be inserted.""" | |
1691 |
|
1690 | |||
1692 | newcomp = types.MethodType(completer,self.Completer) |
|
1691 | newcomp = types.MethodType(completer,self.Completer) | |
1693 | self.Completer.matchers.insert(pos,newcomp) |
|
1692 | self.Completer.matchers.insert(pos,newcomp) | |
1694 |
|
1693 | |||
1695 | def set_readline_completer(self): |
|
1694 | def set_readline_completer(self): | |
1696 | """Reset readline's completer to be our own.""" |
|
1695 | """Reset readline's completer to be our own.""" | |
1697 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1696 | self.readline.set_completer(self.Completer.rlcomplete) | |
1698 |
|
1697 | |||
1699 | def set_completer_frame(self, frame=None): |
|
1698 | def set_completer_frame(self, frame=None): | |
1700 | """Set the frame of the completer.""" |
|
1699 | """Set the frame of the completer.""" | |
1701 | if frame: |
|
1700 | if frame: | |
1702 | self.Completer.namespace = frame.f_locals |
|
1701 | self.Completer.namespace = frame.f_locals | |
1703 | self.Completer.global_namespace = frame.f_globals |
|
1702 | self.Completer.global_namespace = frame.f_globals | |
1704 | else: |
|
1703 | else: | |
1705 | self.Completer.namespace = self.user_ns |
|
1704 | self.Completer.namespace = self.user_ns | |
1706 | self.Completer.global_namespace = self.user_global_ns |
|
1705 | self.Completer.global_namespace = self.user_global_ns | |
1707 |
|
1706 | |||
1708 | #------------------------------------------------------------------------- |
|
1707 | #------------------------------------------------------------------------- | |
1709 | # Things related to magics |
|
1708 | # Things related to magics | |
1710 | #------------------------------------------------------------------------- |
|
1709 | #------------------------------------------------------------------------- | |
1711 |
|
1710 | |||
1712 | def init_magics(self): |
|
1711 | def init_magics(self): | |
1713 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1712 | # FIXME: Move the color initialization to the DisplayHook, which | |
1714 | # should be split into a prompt manager and displayhook. We probably |
|
1713 | # should be split into a prompt manager and displayhook. We probably | |
1715 | # even need a centralize colors management object. |
|
1714 | # even need a centralize colors management object. | |
1716 | self.magic_colors(self.colors) |
|
1715 | self.magic_colors(self.colors) | |
1717 | # History was moved to a separate module |
|
1716 | # History was moved to a separate module | |
1718 | from . import history |
|
1717 | from . import history | |
1719 | history.init_ipython(self) |
|
1718 | history.init_ipython(self) | |
1720 |
|
1719 | |||
1721 | def magic(self,arg_s): |
|
1720 | def magic(self,arg_s): | |
1722 | """Call a magic function by name. |
|
1721 | """Call a magic function by name. | |
1723 |
|
1722 | |||
1724 | 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 | |
1725 | any additional arguments to be passed to the magic. |
|
1724 | any additional arguments to be passed to the magic. | |
1726 |
|
1725 | |||
1727 | 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 | |
1728 | prompt: |
|
1727 | prompt: | |
1729 |
|
1728 | |||
1730 | In[1]: %name -opt foo bar |
|
1729 | In[1]: %name -opt foo bar | |
1731 |
|
1730 | |||
1732 | To call a magic without arguments, simply use magic('name'). |
|
1731 | To call a magic without arguments, simply use magic('name'). | |
1733 |
|
1732 | |||
1734 | 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 | |
1735 | 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 | |
1736 | compound statements. |
|
1735 | compound statements. | |
1737 | """ |
|
1736 | """ | |
1738 | args = arg_s.split(' ',1) |
|
1737 | args = arg_s.split(' ',1) | |
1739 | magic_name = args[0] |
|
1738 | magic_name = args[0] | |
1740 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1739 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1741 |
|
1740 | |||
1742 | try: |
|
1741 | try: | |
1743 | magic_args = args[1] |
|
1742 | magic_args = args[1] | |
1744 | except IndexError: |
|
1743 | except IndexError: | |
1745 | magic_args = '' |
|
1744 | magic_args = '' | |
1746 | fn = getattr(self,'magic_'+magic_name,None) |
|
1745 | fn = getattr(self,'magic_'+magic_name,None) | |
1747 | if fn is None: |
|
1746 | if fn is None: | |
1748 | error("Magic function `%s` not found." % magic_name) |
|
1747 | error("Magic function `%s` not found." % magic_name) | |
1749 | else: |
|
1748 | else: | |
1750 | magic_args = self.var_expand(magic_args,1) |
|
1749 | magic_args = self.var_expand(magic_args,1) | |
1751 | with nested(self.builtin_trap,): |
|
1750 | with nested(self.builtin_trap,): | |
1752 | result = fn(magic_args) |
|
1751 | result = fn(magic_args) | |
1753 | return result |
|
1752 | return result | |
1754 |
|
1753 | |||
1755 | def define_magic(self, magicname, func): |
|
1754 | def define_magic(self, magicname, func): | |
1756 | """Expose own function as magic function for ipython |
|
1755 | """Expose own function as magic function for ipython | |
1757 |
|
1756 | |||
1758 | def foo_impl(self,parameter_s=''): |
|
1757 | def foo_impl(self,parameter_s=''): | |
1759 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1758 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1760 | print 'Magic function. Passed parameter is between < >:' |
|
1759 | print 'Magic function. Passed parameter is between < >:' | |
1761 | print '<%s>' % parameter_s |
|
1760 | print '<%s>' % parameter_s | |
1762 | print 'The self object is:',self |
|
1761 | print 'The self object is:',self | |
1763 |
|
1762 | |||
1764 | self.define_magic('foo',foo_impl) |
|
1763 | self.define_magic('foo',foo_impl) | |
1765 | """ |
|
1764 | """ | |
1766 |
|
1765 | |||
1767 | import new |
|
1766 | import new | |
1768 | im = types.MethodType(func,self) |
|
1767 | im = types.MethodType(func,self) | |
1769 | old = getattr(self, "magic_" + magicname, None) |
|
1768 | old = getattr(self, "magic_" + magicname, None) | |
1770 | setattr(self, "magic_" + magicname, im) |
|
1769 | setattr(self, "magic_" + magicname, im) | |
1771 | return old |
|
1770 | return old | |
1772 |
|
1771 | |||
1773 | #------------------------------------------------------------------------- |
|
1772 | #------------------------------------------------------------------------- | |
1774 | # Things related to macros |
|
1773 | # Things related to macros | |
1775 | #------------------------------------------------------------------------- |
|
1774 | #------------------------------------------------------------------------- | |
1776 |
|
1775 | |||
1777 | def define_macro(self, name, themacro): |
|
1776 | def define_macro(self, name, themacro): | |
1778 | """Define a new macro |
|
1777 | """Define a new macro | |
1779 |
|
1778 | |||
1780 | Parameters |
|
1779 | Parameters | |
1781 | ---------- |
|
1780 | ---------- | |
1782 | name : str |
|
1781 | name : str | |
1783 | The name of the macro. |
|
1782 | The name of the macro. | |
1784 | themacro : str or Macro |
|
1783 | themacro : str or Macro | |
1785 | 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 | |
1786 | Macro object is created by passing the string to it. |
|
1785 | Macro object is created by passing the string to it. | |
1787 | """ |
|
1786 | """ | |
1788 |
|
1787 | |||
1789 | from IPython.core import macro |
|
1788 | from IPython.core import macro | |
1790 |
|
1789 | |||
1791 | if isinstance(themacro, basestring): |
|
1790 | if isinstance(themacro, basestring): | |
1792 | themacro = macro.Macro(themacro) |
|
1791 | themacro = macro.Macro(themacro) | |
1793 | if not isinstance(themacro, macro.Macro): |
|
1792 | if not isinstance(themacro, macro.Macro): | |
1794 | 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.') | |
1795 | self.user_ns[name] = themacro |
|
1794 | self.user_ns[name] = themacro | |
1796 |
|
1795 | |||
1797 | #------------------------------------------------------------------------- |
|
1796 | #------------------------------------------------------------------------- | |
1798 | # Things related to the running of system commands |
|
1797 | # Things related to the running of system commands | |
1799 | #------------------------------------------------------------------------- |
|
1798 | #------------------------------------------------------------------------- | |
1800 |
|
1799 | |||
1801 | def system(self, cmd): |
|
1800 | def system(self, cmd): | |
1802 | """Call the given cmd in a subprocess. |
|
1801 | """Call the given cmd in a subprocess. | |
1803 |
|
1802 | |||
1804 | Parameters |
|
1803 | Parameters | |
1805 | ---------- |
|
1804 | ---------- | |
1806 | cmd : str |
|
1805 | cmd : str | |
1807 | Command to execute (can not end in '&', as bacground processes are |
|
1806 | Command to execute (can not end in '&', as bacground processes are | |
1808 | not supported. |
|
1807 | not supported. | |
1809 | """ |
|
1808 | """ | |
1810 | # We do not support backgrounding processes because we either use |
|
1809 | # We do not support backgrounding processes because we either use | |
1811 | # pexpect or pipes to read from. Users can always just call |
|
1810 | # pexpect or pipes to read from. Users can always just call | |
1812 | # os.system() if they really want a background process. |
|
1811 | # os.system() if they really want a background process. | |
1813 | if cmd.endswith('&'): |
|
1812 | if cmd.endswith('&'): | |
1814 | raise OSError("Background processes not supported.") |
|
1813 | raise OSError("Background processes not supported.") | |
1815 |
|
1814 | |||
1816 | return system(self.var_expand(cmd, depth=2)) |
|
1815 | return system(self.var_expand(cmd, depth=2)) | |
1817 |
|
1816 | |||
1818 | def getoutput(self, cmd, split=True): |
|
1817 | def getoutput(self, cmd, split=True): | |
1819 | """Get output (possibly including stderr) from a subprocess. |
|
1818 | """Get output (possibly including stderr) from a subprocess. | |
1820 |
|
1819 | |||
1821 | Parameters |
|
1820 | Parameters | |
1822 | ---------- |
|
1821 | ---------- | |
1823 | cmd : str |
|
1822 | cmd : str | |
1824 | Command to execute (can not end in '&', as background processes are |
|
1823 | Command to execute (can not end in '&', as background processes are | |
1825 | not supported. |
|
1824 | not supported. | |
1826 | split : bool, optional |
|
1825 | split : bool, optional | |
1827 |
|
1826 | |||
1828 | If True, split the output into an IPython SList. Otherwise, an |
|
1827 | If True, split the output into an IPython SList. Otherwise, an | |
1829 | IPython LSString is returned. These are objects similar to normal |
|
1828 | IPython LSString is returned. These are objects similar to normal | |
1830 | lists and strings, with a few convenience attributes for easier |
|
1829 | lists and strings, with a few convenience attributes for easier | |
1831 | manipulation of line-based output. You can use '?' on them for |
|
1830 | manipulation of line-based output. You can use '?' on them for | |
1832 | details. |
|
1831 | details. | |
1833 | """ |
|
1832 | """ | |
1834 | if cmd.endswith('&'): |
|
1833 | if cmd.endswith('&'): | |
1835 | raise OSError("Background processes not supported.") |
|
1834 | raise OSError("Background processes not supported.") | |
1836 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1835 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1837 | if split: |
|
1836 | if split: | |
1838 | out = SList(out.splitlines()) |
|
1837 | out = SList(out.splitlines()) | |
1839 | else: |
|
1838 | else: | |
1840 | out = LSString(out) |
|
1839 | out = LSString(out) | |
1841 | return out |
|
1840 | return out | |
1842 |
|
1841 | |||
1843 | #------------------------------------------------------------------------- |
|
1842 | #------------------------------------------------------------------------- | |
1844 | # Things related to aliases |
|
1843 | # Things related to aliases | |
1845 | #------------------------------------------------------------------------- |
|
1844 | #------------------------------------------------------------------------- | |
1846 |
|
1845 | |||
1847 | def init_alias(self): |
|
1846 | def init_alias(self): | |
1848 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1847 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1849 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1848 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1850 |
|
1849 | |||
1851 | #------------------------------------------------------------------------- |
|
1850 | #------------------------------------------------------------------------- | |
1852 | # Things related to extensions and plugins |
|
1851 | # Things related to extensions and plugins | |
1853 | #------------------------------------------------------------------------- |
|
1852 | #------------------------------------------------------------------------- | |
1854 |
|
1853 | |||
1855 | def init_extension_manager(self): |
|
1854 | def init_extension_manager(self): | |
1856 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1855 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1857 |
|
1856 | |||
1858 | def init_plugin_manager(self): |
|
1857 | def init_plugin_manager(self): | |
1859 | self.plugin_manager = PluginManager(config=self.config) |
|
1858 | self.plugin_manager = PluginManager(config=self.config) | |
1860 |
|
1859 | |||
1861 | #------------------------------------------------------------------------- |
|
1860 | #------------------------------------------------------------------------- | |
1862 | # Things related to payloads |
|
1861 | # Things related to payloads | |
1863 | #------------------------------------------------------------------------- |
|
1862 | #------------------------------------------------------------------------- | |
1864 |
|
1863 | |||
1865 | def init_payload(self): |
|
1864 | def init_payload(self): | |
1866 | self.payload_manager = PayloadManager(config=self.config) |
|
1865 | self.payload_manager = PayloadManager(config=self.config) | |
1867 |
|
1866 | |||
1868 | #------------------------------------------------------------------------- |
|
1867 | #------------------------------------------------------------------------- | |
1869 | # Things related to the prefilter |
|
1868 | # Things related to the prefilter | |
1870 | #------------------------------------------------------------------------- |
|
1869 | #------------------------------------------------------------------------- | |
1871 |
|
1870 | |||
1872 | def init_prefilter(self): |
|
1871 | def init_prefilter(self): | |
1873 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1872 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1874 | # Ultimately this will be refactored in the new interpreter code, but |
|
1873 | # Ultimately this will be refactored in the new interpreter code, but | |
1875 | # 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 | |
1876 | # code out there that may rely on this). |
|
1875 | # code out there that may rely on this). | |
1877 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1876 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1878 |
|
1877 | |||
1879 | def auto_rewrite_input(self, cmd): |
|
1878 | def auto_rewrite_input(self, cmd): | |
1880 | """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. | |
1881 |
|
1880 | |||
1882 | This shows visual feedback by rewriting input lines that cause |
|
1881 | This shows visual feedback by rewriting input lines that cause | |
1883 | automatic calling to kick in, like:: |
|
1882 | automatic calling to kick in, like:: | |
1884 |
|
1883 | |||
1885 | /f x |
|
1884 | /f x | |
1886 |
|
1885 | |||
1887 | into:: |
|
1886 | into:: | |
1888 |
|
1887 | |||
1889 | ------> f(x) |
|
1888 | ------> f(x) | |
1890 |
|
1889 | |||
1891 | 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 | |
1892 | input line was transformed automatically by IPython. |
|
1891 | input line was transformed automatically by IPython. | |
1893 | """ |
|
1892 | """ | |
1894 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1893 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1895 |
|
1894 | |||
1896 | try: |
|
1895 | try: | |
1897 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1896 | # plain ascii works better w/ pyreadline, on some machines, so | |
1898 | # 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 | |
1899 | rw = str(rw) |
|
1898 | rw = str(rw) | |
1900 | print >> IPython.utils.io.Term.cout, rw |
|
1899 | print >> IPython.utils.io.Term.cout, rw | |
1901 | except UnicodeEncodeError: |
|
1900 | except UnicodeEncodeError: | |
1902 | print "------> " + cmd |
|
1901 | print "------> " + cmd | |
1903 |
|
1902 | |||
1904 | #------------------------------------------------------------------------- |
|
1903 | #------------------------------------------------------------------------- | |
1905 | # Things related to extracting values/expressions from kernel and user_ns |
|
1904 | # Things related to extracting values/expressions from kernel and user_ns | |
1906 | #------------------------------------------------------------------------- |
|
1905 | #------------------------------------------------------------------------- | |
1907 |
|
1906 | |||
1908 | def _simple_error(self): |
|
1907 | def _simple_error(self): | |
1909 | etype, value = sys.exc_info()[:2] |
|
1908 | etype, value = sys.exc_info()[:2] | |
1910 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1909 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1911 |
|
1910 | |||
1912 | def user_variables(self, names): |
|
1911 | def user_variables(self, names): | |
1913 | """Get a list of variable names from the user's namespace. |
|
1912 | """Get a list of variable names from the user's namespace. | |
1914 |
|
1913 | |||
1915 | Parameters |
|
1914 | Parameters | |
1916 | ---------- |
|
1915 | ---------- | |
1917 | names : list of strings |
|
1916 | names : list of strings | |
1918 | 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. | |
1919 |
|
1918 | |||
1920 | Returns |
|
1919 | Returns | |
1921 | ------- |
|
1920 | ------- | |
1922 | 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. | |
1923 | """ |
|
1922 | """ | |
1924 | out = {} |
|
1923 | out = {} | |
1925 | user_ns = self.user_ns |
|
1924 | user_ns = self.user_ns | |
1926 | for varname in names: |
|
1925 | for varname in names: | |
1927 | try: |
|
1926 | try: | |
1928 | value = repr(user_ns[varname]) |
|
1927 | value = repr(user_ns[varname]) | |
1929 | except: |
|
1928 | except: | |
1930 | value = self._simple_error() |
|
1929 | value = self._simple_error() | |
1931 | out[varname] = value |
|
1930 | out[varname] = value | |
1932 | return out |
|
1931 | return out | |
1933 |
|
1932 | |||
1934 | def user_expressions(self, expressions): |
|
1933 | def user_expressions(self, expressions): | |
1935 | """Evaluate a dict of expressions in the user's namespace. |
|
1934 | """Evaluate a dict of expressions in the user's namespace. | |
1936 |
|
1935 | |||
1937 | Parameters |
|
1936 | Parameters | |
1938 | ---------- |
|
1937 | ---------- | |
1939 | expressions : dict |
|
1938 | expressions : dict | |
1940 | A dict with string keys and string values. The expression values |
|
1939 | A dict with string keys and string values. The expression values | |
1941 | should be valid Python expressions, each of which will be evaluated |
|
1940 | should be valid Python expressions, each of which will be evaluated | |
1942 | in the user namespace. |
|
1941 | in the user namespace. | |
1943 |
|
1942 | |||
1944 | Returns |
|
1943 | Returns | |
1945 | ------- |
|
1944 | ------- | |
1946 | 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 | |
1947 | value. |
|
1946 | value. | |
1948 | """ |
|
1947 | """ | |
1949 | out = {} |
|
1948 | out = {} | |
1950 | user_ns = self.user_ns |
|
1949 | user_ns = self.user_ns | |
1951 | global_ns = self.user_global_ns |
|
1950 | global_ns = self.user_global_ns | |
1952 | for key, expr in expressions.iteritems(): |
|
1951 | for key, expr in expressions.iteritems(): | |
1953 | try: |
|
1952 | try: | |
1954 | value = repr(eval(expr, global_ns, user_ns)) |
|
1953 | value = repr(eval(expr, global_ns, user_ns)) | |
1955 | except: |
|
1954 | except: | |
1956 | value = self._simple_error() |
|
1955 | value = self._simple_error() | |
1957 | out[key] = value |
|
1956 | out[key] = value | |
1958 | return out |
|
1957 | return out | |
1959 |
|
1958 | |||
1960 | #------------------------------------------------------------------------- |
|
1959 | #------------------------------------------------------------------------- | |
1961 | # Things related to the running of code |
|
1960 | # Things related to the running of code | |
1962 | #------------------------------------------------------------------------- |
|
1961 | #------------------------------------------------------------------------- | |
1963 |
|
1962 | |||
1964 | def ex(self, cmd): |
|
1963 | def ex(self, cmd): | |
1965 | """Execute a normal python statement in user namespace.""" |
|
1964 | """Execute a normal python statement in user namespace.""" | |
1966 | with nested(self.builtin_trap,): |
|
1965 | with nested(self.builtin_trap,): | |
1967 | exec cmd in self.user_global_ns, self.user_ns |
|
1966 | exec cmd in self.user_global_ns, self.user_ns | |
1968 |
|
1967 | |||
1969 | def ev(self, expr): |
|
1968 | def ev(self, expr): | |
1970 | """Evaluate python expression expr in user namespace. |
|
1969 | """Evaluate python expression expr in user namespace. | |
1971 |
|
1970 | |||
1972 | Returns the result of evaluation |
|
1971 | Returns the result of evaluation | |
1973 | """ |
|
1972 | """ | |
1974 | with nested(self.builtin_trap,): |
|
1973 | with nested(self.builtin_trap,): | |
1975 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1974 | return eval(expr, self.user_global_ns, self.user_ns) | |
1976 |
|
1975 | |||
1977 | def safe_execfile(self, fname, *where, **kw): |
|
1976 | def safe_execfile(self, fname, *where, **kw): | |
1978 | """A safe version of the builtin execfile(). |
|
1977 | """A safe version of the builtin execfile(). | |
1979 |
|
1978 | |||
1980 | This version will never throw an exception, but instead print |
|
1979 | This version will never throw an exception, but instead print | |
1981 | helpful error messages to the screen. This only works on pure |
|
1980 | helpful error messages to the screen. This only works on pure | |
1982 | Python files with the .py extension. |
|
1981 | Python files with the .py extension. | |
1983 |
|
1982 | |||
1984 | Parameters |
|
1983 | Parameters | |
1985 | ---------- |
|
1984 | ---------- | |
1986 | fname : string |
|
1985 | fname : string | |
1987 | The name of the file to be executed. |
|
1986 | The name of the file to be executed. | |
1988 | where : tuple |
|
1987 | where : tuple | |
1989 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1988 | One or two namespaces, passed to execfile() as (globals,locals). | |
1990 | If only one is given, it is passed as both. |
|
1989 | If only one is given, it is passed as both. | |
1991 | exit_ignore : bool (False) |
|
1990 | exit_ignore : bool (False) | |
1992 | 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 | |
1993 | silenced for zero status, as it is so common). |
|
1992 | silenced for zero status, as it is so common). | |
1994 | """ |
|
1993 | """ | |
1995 | kw.setdefault('exit_ignore', False) |
|
1994 | kw.setdefault('exit_ignore', False) | |
1996 |
|
1995 | |||
1997 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1996 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1998 |
|
1997 | |||
1999 | # Make sure we have a .py file |
|
1998 | # Make sure we have a .py file | |
2000 | if not fname.endswith('.py'): |
|
1999 | if not fname.endswith('.py'): | |
2001 | 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) | |
2002 |
|
2001 | |||
2003 | # Make sure we can open the file |
|
2002 | # Make sure we can open the file | |
2004 | try: |
|
2003 | try: | |
2005 | with open(fname) as thefile: |
|
2004 | with open(fname) as thefile: | |
2006 | pass |
|
2005 | pass | |
2007 | except: |
|
2006 | except: | |
2008 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2007 | warn('Could not open file <%s> for safe execution.' % fname) | |
2009 | return |
|
2008 | return | |
2010 |
|
2009 | |||
2011 | # 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 | |
2012 | # behavior of running a script from the system command line, where |
|
2011 | # behavior of running a script from the system command line, where | |
2013 | # Python inserts the script's directory into sys.path |
|
2012 | # Python inserts the script's directory into sys.path | |
2014 | dname = os.path.dirname(fname) |
|
2013 | dname = os.path.dirname(fname) | |
2015 |
|
2014 | |||
2016 | with prepended_to_syspath(dname): |
|
2015 | with prepended_to_syspath(dname): | |
2017 | try: |
|
2016 | try: | |
2018 | execfile(fname,*where) |
|
2017 | execfile(fname,*where) | |
2019 | except SystemExit, status: |
|
2018 | except SystemExit, status: | |
2020 | # 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) | |
2021 | # 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 | |
2022 | # these are considered normal by the OS: |
|
2021 | # these are considered normal by the OS: | |
2023 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2022 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2024 | # 0 |
|
2023 | # 0 | |
2025 | # > python -c'import sys;sys.exit()'; echo $? |
|
2024 | # > python -c'import sys;sys.exit()'; echo $? | |
2026 | # 0 |
|
2025 | # 0 | |
2027 | # For other exit status, we show the exception unless |
|
2026 | # For other exit status, we show the exception unless | |
2028 | # explicitly silenced, but only in short form. |
|
2027 | # explicitly silenced, but only in short form. | |
2029 | 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']: | |
2030 | self.showtraceback(exception_only=True) |
|
2029 | self.showtraceback(exception_only=True) | |
2031 | except: |
|
2030 | except: | |
2032 | self.showtraceback() |
|
2031 | self.showtraceback() | |
2033 |
|
2032 | |||
2034 | def safe_execfile_ipy(self, fname): |
|
2033 | def safe_execfile_ipy(self, fname): | |
2035 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2034 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2036 |
|
2035 | |||
2037 | Parameters |
|
2036 | Parameters | |
2038 | ---------- |
|
2037 | ---------- | |
2039 | fname : str |
|
2038 | fname : str | |
2040 | 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 | |
2041 | .ipy extension. |
|
2040 | .ipy extension. | |
2042 | """ |
|
2041 | """ | |
2043 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2042 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2044 |
|
2043 | |||
2045 | # Make sure we have a .py file |
|
2044 | # Make sure we have a .py file | |
2046 | if not fname.endswith('.ipy'): |
|
2045 | if not fname.endswith('.ipy'): | |
2047 | 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) | |
2048 |
|
2047 | |||
2049 | # Make sure we can open the file |
|
2048 | # Make sure we can open the file | |
2050 | try: |
|
2049 | try: | |
2051 | with open(fname) as thefile: |
|
2050 | with open(fname) as thefile: | |
2052 | pass |
|
2051 | pass | |
2053 | except: |
|
2052 | except: | |
2054 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2053 | warn('Could not open file <%s> for safe execution.' % fname) | |
2055 | return |
|
2054 | return | |
2056 |
|
2055 | |||
2057 | # 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 | |
2058 | # behavior of running a script from the system command line, where |
|
2057 | # behavior of running a script from the system command line, where | |
2059 | # Python inserts the script's directory into sys.path |
|
2058 | # Python inserts the script's directory into sys.path | |
2060 | dname = os.path.dirname(fname) |
|
2059 | dname = os.path.dirname(fname) | |
2061 |
|
2060 | |||
2062 | with prepended_to_syspath(dname): |
|
2061 | with prepended_to_syspath(dname): | |
2063 | try: |
|
2062 | try: | |
2064 | with open(fname) as thefile: |
|
2063 | with open(fname) as thefile: | |
2065 | # self.run_cell currently captures all exceptions |
|
2064 | # self.run_cell currently captures all exceptions | |
2066 | # raised in user code. It would be nice if there were |
|
2065 | # raised in user code. It would be nice if there were | |
2067 | # versions of runlines, execfile that did raise, so |
|
2066 | # versions of runlines, execfile that did raise, so | |
2068 | # we could catch the errors. |
|
2067 | # we could catch the errors. | |
2069 | self.run_cell(thefile.read()) |
|
2068 | self.run_cell(thefile.read()) | |
2070 | except: |
|
2069 | except: | |
2071 | self.showtraceback() |
|
2070 | self.showtraceback() | |
2072 | warn('Unknown failure executing file: <%s>' % fname) |
|
2071 | warn('Unknown failure executing file: <%s>' % fname) | |
2073 |
|
2072 | |||
2074 | def run_cell(self, cell): |
|
2073 | def run_cell(self, cell): | |
2075 | """Run the contents of an entire multiline 'cell' of code. |
|
2074 | """Run the contents of an entire multiline 'cell' of code. | |
2076 |
|
2075 | |||
2077 | The cell is split into separate blocks which can be executed |
|
2076 | The cell is split into separate blocks which can be executed | |
2078 | individually. Then, based on how many blocks there are, they are |
|
2077 | individually. Then, based on how many blocks there are, they are | |
2079 | executed as follows: |
|
2078 | executed as follows: | |
2080 |
|
2079 | |||
2081 | - A single block: 'single' mode. |
|
2080 | - A single block: 'single' mode. | |
2082 |
|
2081 | |||
2083 | If there's more than one block, it depends: |
|
2082 | If there's more than one block, it depends: | |
2084 |
|
2083 | |||
2085 | - 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 | |
2086 | 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 | |
2087 | 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. - | |
2088 | otherwise (last one is also multiline), run all in 'exec' mode |
|
2087 | otherwise (last one is also multiline), run all in 'exec' mode | |
2089 |
|
2088 | |||
2090 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2089 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, | |
2091 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2090 | results are displayed and output prompts are computed. In 'exec' mode, | |
2092 | no results are displayed unless :func:`print` is called explicitly; |
|
2091 | no results are displayed unless :func:`print` is called explicitly; | |
2093 | this mode is more akin to running a script. |
|
2092 | this mode is more akin to running a script. | |
2094 |
|
2093 | |||
2095 | Parameters |
|
2094 | Parameters | |
2096 | ---------- |
|
2095 | ---------- | |
2097 | cell : str |
|
2096 | cell : str | |
2098 | A single or multiline string. |
|
2097 | A single or multiline string. | |
2099 | """ |
|
2098 | """ | |
2100 |
|
2099 | |||
2101 | # 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 | |
2102 | # in 'single' mode, to provide comfortable user behavior. |
|
2101 | # in 'single' mode, to provide comfortable user behavior. | |
2103 | blocks = self.input_splitter.split_blocks(cell) |
|
2102 | blocks = self.input_splitter.split_blocks(cell) | |
2104 |
|
2103 | |||
2105 | if not blocks: |
|
2104 | if not blocks: | |
2106 | return |
|
2105 | return | |
2107 |
|
2106 | |||
2108 | # 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 | |
2109 | # needs to go into the translated history and get executed (the |
|
2108 | # needs to go into the translated history and get executed (the | |
2110 | # original cell may contain non-python syntax). |
|
2109 | # original cell may contain non-python syntax). | |
2111 | ipy_cell = ''.join(blocks) |
|
2110 | ipy_cell = ''.join(blocks) | |
2112 |
|
2111 | |||
2113 | # Store raw and processed history |
|
2112 | # Store raw and processed history | |
2114 | self.history_manager.store_inputs(ipy_cell, cell) |
|
2113 | self.history_manager.store_inputs(ipy_cell, cell) | |
2115 |
|
2114 | |||
2116 | self.logger.log(ipy_cell, cell) |
|
2115 | self.logger.log(ipy_cell, cell) | |
2117 | # dbg code!!! |
|
2116 | # dbg code!!! | |
2118 | if 0: |
|
2117 | if 0: | |
2119 | def myapp(self, val): # dbg |
|
2118 | def myapp(self, val): # dbg | |
2120 | import traceback as tb |
|
2119 | import traceback as tb | |
2121 | stack = ''.join(tb.format_stack()) |
|
2120 | stack = ''.join(tb.format_stack()) | |
2122 | print 'Value:', val |
|
2121 | print 'Value:', val | |
2123 | print 'Stack:\n', stack |
|
2122 | print 'Stack:\n', stack | |
2124 | list.append(self, val) |
|
2123 | list.append(self, val) | |
2125 |
|
2124 | |||
2126 | import new |
|
2125 | import new | |
2127 | self.history_manager.input_hist_parsed.append = types.MethodType(myapp, |
|
2126 | self.history_manager.input_hist_parsed.append = types.MethodType(myapp, | |
2128 | self.history_manager.input_hist_parsed) |
|
2127 | self.history_manager.input_hist_parsed) | |
2129 | # End dbg |
|
2128 | # End dbg | |
2130 |
|
2129 | |||
2131 | # All user code execution must happen with our context managers active |
|
2130 | # All user code execution must happen with our context managers active | |
2132 | with nested(self.builtin_trap, self.display_trap): |
|
2131 | with nested(self.builtin_trap, self.display_trap): | |
2133 |
|
2132 | |||
2134 | # Single-block input should behave like an interactive prompt |
|
2133 | # Single-block input should behave like an interactive prompt | |
2135 | if len(blocks) == 1: |
|
2134 | if len(blocks) == 1: | |
2136 | # since we return here, we need to update the execution count |
|
2135 | # since we return here, we need to update the execution count | |
2137 | out = self.run_one_block(blocks[0]) |
|
2136 | out = self.run_one_block(blocks[0]) | |
2138 | self.execution_count += 1 |
|
2137 | self.execution_count += 1 | |
2139 | return out |
|
2138 | return out | |
2140 |
|
2139 | |||
2141 | # 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 | |
2142 | # lines) expression, run it in single mode so it produces output. |
|
2141 | # lines) expression, run it in single mode so it produces output. | |
2143 | # 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 | |
2144 | # a reasonable usability design. |
|
2143 | # a reasonable usability design. | |
2145 | last = blocks[-1] |
|
2144 | last = blocks[-1] | |
2146 | last_nlines = len(last.splitlines()) |
|
2145 | last_nlines = len(last.splitlines()) | |
2147 |
|
2146 | |||
2148 | # Note: below, whenever we call run_code, we must sync history |
|
2147 | # Note: below, whenever we call run_code, we must sync history | |
2149 | # 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. | |
2150 | if last_nlines < 2: |
|
2149 | if last_nlines < 2: | |
2151 | # Here we consider the cell split between 'body' and 'last', |
|
2150 | # Here we consider the cell split between 'body' and 'last', | |
2152 | # store all history and execute 'body', and if successful, then |
|
2151 | # store all history and execute 'body', and if successful, then | |
2153 | # proceed to execute 'last'. |
|
2152 | # proceed to execute 'last'. | |
2154 |
|
2153 | |||
2155 | # Get the main body to run as a cell |
|
2154 | # Get the main body to run as a cell | |
2156 | ipy_body = ''.join(blocks[:-1]) |
|
2155 | ipy_body = ''.join(blocks[:-1]) | |
2157 | retcode = self.run_source(ipy_body, symbol='exec', |
|
2156 | retcode = self.run_source(ipy_body, symbol='exec', | |
2158 | post_execute=False) |
|
2157 | post_execute=False) | |
2159 | if retcode==0: |
|
2158 | if retcode==0: | |
2160 | # And the last expression via runlines so it produces output |
|
2159 | # And the last expression via runlines so it produces output | |
2161 | self.run_one_block(last) |
|
2160 | self.run_one_block(last) | |
2162 | else: |
|
2161 | else: | |
2163 | # Run the whole cell as one entity, storing both raw and |
|
2162 | # Run the whole cell as one entity, storing both raw and | |
2164 | # processed input in history |
|
2163 | # processed input in history | |
2165 | self.run_source(ipy_cell, symbol='exec') |
|
2164 | self.run_source(ipy_cell, symbol='exec') | |
2166 |
|
2165 | |||
2167 | # 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 | |
2168 | self.execution_count += 1 |
|
2167 | self.execution_count += 1 | |
2169 |
|
2168 | |||
2170 | def run_one_block(self, block): |
|
2169 | def run_one_block(self, block): | |
2171 | """Run a single interactive block. |
|
2170 | """Run a single interactive block. | |
2172 |
|
2171 | |||
2173 | 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 | |
2174 | (like automagics, autocall and alias recognition). |
|
2173 | (like automagics, autocall and alias recognition). | |
2175 | """ |
|
2174 | """ | |
2176 | if len(block.splitlines()) <= 1: |
|
2175 | if len(block.splitlines()) <= 1: | |
2177 | out = self.run_single_line(block) |
|
2176 | out = self.run_single_line(block) | |
2178 | else: |
|
2177 | else: | |
2179 | out = self.run_code(block) |
|
2178 | out = self.run_code(block) | |
2180 | return out |
|
2179 | return out | |
2181 |
|
2180 | |||
2182 | def run_single_line(self, line): |
|
2181 | def run_single_line(self, line): | |
2183 | """Run a single-line interactive statement. |
|
2182 | """Run a single-line interactive statement. | |
2184 |
|
2183 | |||
2185 | This assumes the input has been transformed to IPython syntax by |
|
2184 | This assumes the input has been transformed to IPython syntax by | |
2186 | applying all static transformations (those with an explicit prefix like |
|
2185 | applying all static transformations (those with an explicit prefix like | |
2187 | % or !), but it will further try to apply the dynamic ones. |
|
2186 | % or !), but it will further try to apply the dynamic ones. | |
2188 |
|
2187 | |||
2189 | It does not update history. |
|
2188 | It does not update history. | |
2190 | """ |
|
2189 | """ | |
2191 | tline = self.prefilter_manager.prefilter_line(line) |
|
2190 | tline = self.prefilter_manager.prefilter_line(line) | |
2192 | return self.run_source(tline) |
|
2191 | return self.run_source(tline) | |
2193 |
|
2192 | |||
2194 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2193 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2195 | # input logic has been 100% moved to frontends and is stable. |
|
2194 | # input logic has been 100% moved to frontends and is stable. | |
2196 | def runlines(self, lines, clean=False): |
|
2195 | def runlines(self, lines, clean=False): | |
2197 | """Run a string of one or more lines of source. |
|
2196 | """Run a string of one or more lines of source. | |
2198 |
|
2197 | |||
2199 | This method is capable of running a string containing multiple source |
|
2198 | This method is capable of running a string containing multiple source | |
2200 | 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 | |
2201 | exposes IPython's processing machinery, the given strings can contain |
|
2200 | exposes IPython's processing machinery, the given strings can contain | |
2202 | magic calls (%magic), special shell access (!cmd), etc. |
|
2201 | magic calls (%magic), special shell access (!cmd), etc. | |
2203 | """ |
|
2202 | """ | |
2204 |
|
2203 | |||
2205 | if isinstance(lines, (list, tuple)): |
|
2204 | if isinstance(lines, (list, tuple)): | |
2206 | lines = '\n'.join(lines) |
|
2205 | lines = '\n'.join(lines) | |
2207 |
|
2206 | |||
2208 | if clean: |
|
2207 | if clean: | |
2209 | lines = self._cleanup_ipy_script(lines) |
|
2208 | lines = self._cleanup_ipy_script(lines) | |
2210 |
|
2209 | |||
2211 | # 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 | |
2212 | # interactive IPython session (via a magic, for example). |
|
2211 | # interactive IPython session (via a magic, for example). | |
2213 | self.reset_buffer() |
|
2212 | self.reset_buffer() | |
2214 | lines = lines.splitlines() |
|
2213 | lines = lines.splitlines() | |
2215 |
|
2214 | |||
2216 | # 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 | |
2217 | # before we apply any transformations |
|
2216 | # before we apply any transformations | |
2218 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2217 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2219 |
|
2218 | |||
2220 | more = False |
|
2219 | more = False | |
2221 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2220 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2222 | with nested(self.builtin_trap, self.display_trap): |
|
2221 | with nested(self.builtin_trap, self.display_trap): | |
2223 | for line in lines: |
|
2222 | for line in lines: | |
2224 | # 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 | |
2225 | # 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 | |
2226 | # is true) |
|
2225 | # is true) | |
2227 |
|
2226 | |||
2228 | if line or more: |
|
2227 | if line or more: | |
2229 | more = self.push_line(prefilter_lines(line, more)) |
|
2228 | more = self.push_line(prefilter_lines(line, more)) | |
2230 | # IPython's run_source returns None if there was an error |
|
2229 | # IPython's run_source returns None if there was an error | |
2231 | # compiling the code. This allows us to stop processing |
|
2230 | # compiling the code. This allows us to stop processing | |
2232 | # right away, so the user gets the error message at the |
|
2231 | # right away, so the user gets the error message at the | |
2233 | # right place. |
|
2232 | # right place. | |
2234 | if more is None: |
|
2233 | if more is None: | |
2235 | break |
|
2234 | break | |
2236 | # 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 | |
2237 | # actually does get executed |
|
2236 | # actually does get executed | |
2238 | if more: |
|
2237 | if more: | |
2239 | self.push_line('\n') |
|
2238 | self.push_line('\n') | |
2240 |
|
2239 | |||
2241 | def run_source(self, source, filename=None, |
|
2240 | def run_source(self, source, filename=None, | |
2242 | symbol='single', post_execute=True): |
|
2241 | symbol='single', post_execute=True): | |
2243 | """Compile and run some source in the interpreter. |
|
2242 | """Compile and run some source in the interpreter. | |
2244 |
|
2243 | |||
2245 | Arguments are as for compile_command(). |
|
2244 | Arguments are as for compile_command(). | |
2246 |
|
2245 | |||
2247 | One several things can happen: |
|
2246 | One several things can happen: | |
2248 |
|
2247 | |||
2249 | 1) The input is incorrect; compile_command() raised an |
|
2248 | 1) The input is incorrect; compile_command() raised an | |
2250 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2249 | exception (SyntaxError or OverflowError). A syntax traceback | |
2251 | will be printed by calling the showsyntaxerror() method. |
|
2250 | will be printed by calling the showsyntaxerror() method. | |
2252 |
|
2251 | |||
2253 | 2) The input is incomplete, and more input is required; |
|
2252 | 2) The input is incomplete, and more input is required; | |
2254 | compile_command() returned None. Nothing happens. |
|
2253 | compile_command() returned None. Nothing happens. | |
2255 |
|
2254 | |||
2256 | 3) The input is complete; compile_command() returned a code |
|
2255 | 3) The input is complete; compile_command() returned a code | |
2257 | object. The code is executed by calling self.run_code() (which |
|
2256 | object. The code is executed by calling self.run_code() (which | |
2258 | also handles run-time exceptions, except for SystemExit). |
|
2257 | also handles run-time exceptions, except for SystemExit). | |
2259 |
|
2258 | |||
2260 | The return value is: |
|
2259 | The return value is: | |
2261 |
|
2260 | |||
2262 | - True in case 2 |
|
2261 | - True in case 2 | |
2263 |
|
2262 | |||
2264 | - False in the other cases, unless an exception is raised, where |
|
2263 | - False in the other cases, unless an exception is raised, where | |
2265 | 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 | |
2266 | know whether to continue feeding input or not. |
|
2265 | know whether to continue feeding input or not. | |
2267 |
|
2266 | |||
2268 | 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 | |
2269 | sys.ps2 to prompt the next line.""" |
|
2268 | sys.ps2 to prompt the next line.""" | |
2270 |
|
2269 | |||
2271 | # 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. | |
2272 | if type(source)==str: |
|
2271 | if type(source)==str: | |
2273 | usource = source.decode(self.stdin_encoding) |
|
2272 | usource = source.decode(self.stdin_encoding) | |
2274 | else: |
|
2273 | else: | |
2275 | usource = source |
|
2274 | usource = source | |
2276 |
|
2275 | |||
2277 | if 0: # dbg |
|
2276 | if 0: # dbg | |
2278 | print 'Source:', repr(source) # dbg |
|
2277 | print 'Source:', repr(source) # dbg | |
2279 | print 'USource:', repr(usource) # dbg |
|
2278 | print 'USource:', repr(usource) # dbg | |
2280 | print 'type:', type(source) # dbg |
|
2279 | print 'type:', type(source) # dbg | |
2281 | print 'encoding', self.stdin_encoding # dbg |
|
2280 | print 'encoding', self.stdin_encoding # dbg | |
2282 |
|
2281 | |||
2283 | try: |
|
2282 | try: | |
2284 | code = self.compile(usource, symbol, self.execution_count) |
|
2283 | code = self.compile(usource, symbol, self.execution_count) | |
2285 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2284 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2286 | # Case 1 |
|
2285 | # Case 1 | |
2287 | self.showsyntaxerror(filename) |
|
2286 | self.showsyntaxerror(filename) | |
2288 | return None |
|
2287 | return None | |
2289 |
|
2288 | |||
2290 | if code is None: |
|
2289 | if code is None: | |
2291 | # Case 2 |
|
2290 | # Case 2 | |
2292 | return True |
|
2291 | return True | |
2293 |
|
2292 | |||
2294 | # Case 3 |
|
2293 | # Case 3 | |
2295 | # We store the code object so that threaded shells and |
|
2294 | # We store the code object so that threaded shells and | |
2296 | # custom exception handlers can access all this info if needed. |
|
2295 | # custom exception handlers can access all this info if needed. | |
2297 | # The source corresponding to this can be obtained from the |
|
2296 | # The source corresponding to this can be obtained from the | |
2298 | # buffer attribute as '\n'.join(self.buffer). |
|
2297 | # buffer attribute as '\n'.join(self.buffer). | |
2299 | self.code_to_run = code |
|
2298 | self.code_to_run = code | |
2300 | # now actually execute the code object |
|
2299 | # now actually execute the code object | |
2301 | if self.run_code(code, post_execute) == 0: |
|
2300 | if self.run_code(code, post_execute) == 0: | |
2302 | return False |
|
2301 | return False | |
2303 | else: |
|
2302 | else: | |
2304 | return None |
|
2303 | return None | |
2305 |
|
2304 | |||
2306 | # For backwards compatibility |
|
2305 | # For backwards compatibility | |
2307 | runsource = run_source |
|
2306 | runsource = run_source | |
2308 |
|
2307 | |||
2309 | def run_code(self, code_obj, post_execute=True): |
|
2308 | def run_code(self, code_obj, post_execute=True): | |
2310 | """Execute a code object. |
|
2309 | """Execute a code object. | |
2311 |
|
2310 | |||
2312 | When an exception occurs, self.showtraceback() is called to display a |
|
2311 | When an exception occurs, self.showtraceback() is called to display a | |
2313 | traceback. |
|
2312 | traceback. | |
2314 |
|
2313 | |||
2315 | 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 | |
2316 | successfully: |
|
2315 | successfully: | |
2317 |
|
2316 | |||
2318 | - 0: successful execution. |
|
2317 | - 0: successful execution. | |
2319 | - 1: an error occurred. |
|
2318 | - 1: an error occurred. | |
2320 | """ |
|
2319 | """ | |
2321 |
|
2320 | |||
2322 | # 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 | |
2323 | # directly, so that the IPython crash handler doesn't get triggered |
|
2322 | # directly, so that the IPython crash handler doesn't get triggered | |
2324 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2323 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2325 |
|
2324 | |||
2326 | # 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 | |
2327 | # code (such as magics) needs access to it. |
|
2326 | # code (such as magics) needs access to it. | |
2328 | self.sys_excepthook = old_excepthook |
|
2327 | self.sys_excepthook = old_excepthook | |
2329 | 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 | |
2330 | try: |
|
2329 | try: | |
2331 | try: |
|
2330 | try: | |
2332 | self.hooks.pre_run_code_hook() |
|
2331 | self.hooks.pre_run_code_hook() | |
2333 | #rprint('Running code') # dbg |
|
2332 | #rprint('Running code') # dbg | |
2334 | exec code_obj in self.user_global_ns, self.user_ns |
|
2333 | exec code_obj in self.user_global_ns, self.user_ns | |
2335 | finally: |
|
2334 | finally: | |
2336 | # Reset our crash handler in place |
|
2335 | # Reset our crash handler in place | |
2337 | sys.excepthook = old_excepthook |
|
2336 | sys.excepthook = old_excepthook | |
2338 | except SystemExit: |
|
2337 | except SystemExit: | |
2339 | self.reset_buffer() |
|
2338 | self.reset_buffer() | |
2340 | self.showtraceback(exception_only=True) |
|
2339 | self.showtraceback(exception_only=True) | |
2341 | 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) | |
2342 | except self.custom_exceptions: |
|
2341 | except self.custom_exceptions: | |
2343 | etype,value,tb = sys.exc_info() |
|
2342 | etype,value,tb = sys.exc_info() | |
2344 | self.CustomTB(etype,value,tb) |
|
2343 | self.CustomTB(etype,value,tb) | |
2345 | except: |
|
2344 | except: | |
2346 | self.showtraceback() |
|
2345 | self.showtraceback() | |
2347 | else: |
|
2346 | else: | |
2348 | outflag = 0 |
|
2347 | outflag = 0 | |
2349 | if softspace(sys.stdout, 0): |
|
2348 | if softspace(sys.stdout, 0): | |
2350 |
|
2349 | |||
2351 |
|
2350 | |||
2352 | # Execute any registered post-execution functions. Here, any errors |
|
2351 | # Execute any registered post-execution functions. Here, any errors | |
2353 | # are reported only minimally and just on the terminal, because the |
|
2352 | # are reported only minimally and just on the terminal, because the | |
2354 | # main exception channel may be occupied with a user traceback. |
|
2353 | # main exception channel may be occupied with a user traceback. | |
2355 | # FIXME: we need to think this mechanism a little more carefully. |
|
2354 | # FIXME: we need to think this mechanism a little more carefully. | |
2356 | if post_execute: |
|
2355 | if post_execute: | |
2357 | for func in self._post_execute: |
|
2356 | for func in self._post_execute: | |
2358 | try: |
|
2357 | try: | |
2359 | func() |
|
2358 | func() | |
2360 | except: |
|
2359 | except: | |
2361 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2360 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2362 | func |
|
2361 | func | |
2363 | print >> io.Term.cout, head |
|
2362 | print >> io.Term.cout, head | |
2364 | print >> io.Term.cout, self._simple_error() |
|
2363 | print >> io.Term.cout, self._simple_error() | |
2365 | print >> io.Term.cout, 'Removing from post_execute' |
|
2364 | print >> io.Term.cout, 'Removing from post_execute' | |
2366 | self._post_execute.remove(func) |
|
2365 | self._post_execute.remove(func) | |
2367 |
|
2366 | |||
2368 | # Flush out code object which has been run (and source) |
|
2367 | # Flush out code object which has been run (and source) | |
2369 | self.code_to_run = None |
|
2368 | self.code_to_run = None | |
2370 | return outflag |
|
2369 | return outflag | |
2371 |
|
2370 | |||
2372 | # For backwards compatibility |
|
2371 | # For backwards compatibility | |
2373 | runcode = run_code |
|
2372 | runcode = run_code | |
2374 |
|
2373 | |||
2375 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2374 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2376 | # input logic has been 100% moved to frontends and is stable. |
|
2375 | # input logic has been 100% moved to frontends and is stable. | |
2377 | def push_line(self, line): |
|
2376 | def push_line(self, line): | |
2378 | """Push a line to the interpreter. |
|
2377 | """Push a line to the interpreter. | |
2379 |
|
2378 | |||
2380 | The line should not have a trailing newline; it may have |
|
2379 | The line should not have a trailing newline; it may have | |
2381 | internal newlines. The line is appended to a buffer and the |
|
2380 | internal newlines. The line is appended to a buffer and the | |
2382 | interpreter's run_source() method is called with the |
|
2381 | interpreter's run_source() method is called with the | |
2383 | concatenated contents of the buffer as source. If this |
|
2382 | concatenated contents of the buffer as source. If this | |
2384 | indicates that the command was executed or invalid, the buffer |
|
2383 | indicates that the command was executed or invalid, the buffer | |
2385 | is reset; otherwise, the command is incomplete, and the buffer |
|
2384 | is reset; otherwise, the command is incomplete, and the buffer | |
2386 | 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 | |
2387 | 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 | |
2388 | with in some way (this is the same as run_source()). |
|
2387 | with in some way (this is the same as run_source()). | |
2389 | """ |
|
2388 | """ | |
2390 |
|
2389 | |||
2391 | # autoindent management should be done here, and not in the |
|
2390 | # autoindent management should be done here, and not in the | |
2392 | # 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 | |
2393 | # 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 | |
2394 | # push). |
|
2393 | # push). | |
2395 |
|
2394 | |||
2396 | #print 'push line: <%s>' % line # dbg |
|
2395 | #print 'push line: <%s>' % line # dbg | |
2397 | self.buffer.append(line) |
|
2396 | self.buffer.append(line) | |
2398 | full_source = '\n'.join(self.buffer) |
|
2397 | full_source = '\n'.join(self.buffer) | |
2399 | more = self.run_source(full_source, self.filename) |
|
2398 | more = self.run_source(full_source, self.filename) | |
2400 | if not more: |
|
2399 | if not more: | |
2401 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), |
|
2400 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), | |
2402 | full_source) |
|
2401 | full_source) | |
2403 | self.reset_buffer() |
|
2402 | self.reset_buffer() | |
2404 | self.execution_count += 1 |
|
2403 | self.execution_count += 1 | |
2405 | return more |
|
2404 | return more | |
2406 |
|
2405 | |||
2407 | def reset_buffer(self): |
|
2406 | def reset_buffer(self): | |
2408 | """Reset the input buffer.""" |
|
2407 | """Reset the input buffer.""" | |
2409 | self.buffer[:] = [] |
|
2408 | self.buffer[:] = [] | |
2410 | self.buffer_raw[:] = [] |
|
2409 | self.buffer_raw[:] = [] | |
2411 | self.input_splitter.reset() |
|
2410 | self.input_splitter.reset() | |
2412 |
|
2411 | |||
2413 | # For backwards compatibility |
|
2412 | # For backwards compatibility | |
2414 | resetbuffer = reset_buffer |
|
2413 | resetbuffer = reset_buffer | |
2415 |
|
2414 | |||
2416 | def _is_secondary_block_start(self, s): |
|
2415 | def _is_secondary_block_start(self, s): | |
2417 | if not s.endswith(':'): |
|
2416 | if not s.endswith(':'): | |
2418 | return False |
|
2417 | return False | |
2419 | if (s.startswith('elif') or |
|
2418 | if (s.startswith('elif') or | |
2420 | s.startswith('else') or |
|
2419 | s.startswith('else') or | |
2421 | s.startswith('except') or |
|
2420 | s.startswith('except') or | |
2422 | s.startswith('finally')): |
|
2421 | s.startswith('finally')): | |
2423 | return True |
|
2422 | return True | |
2424 |
|
2423 | |||
2425 | def _cleanup_ipy_script(self, script): |
|
2424 | def _cleanup_ipy_script(self, script): | |
2426 | """Make a script safe for self.runlines() |
|
2425 | """Make a script safe for self.runlines() | |
2427 |
|
2426 | |||
2428 | Currently, IPython is lines based, with blocks being detected by |
|
2427 | Currently, IPython is lines based, with blocks being detected by | |
2429 | 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 | |
2430 | not have empty lines after blocks. This script adds those empty |
|
2429 | not have empty lines after blocks. This script adds those empty | |
2431 | 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 | |
2432 | IPython. |
|
2431 | IPython. | |
2433 | """ |
|
2432 | """ | |
2434 | res = [] |
|
2433 | res = [] | |
2435 | lines = script.splitlines() |
|
2434 | lines = script.splitlines() | |
2436 | level = 0 |
|
2435 | level = 0 | |
2437 |
|
2436 | |||
2438 | for l in lines: |
|
2437 | for l in lines: | |
2439 | lstripped = l.lstrip() |
|
2438 | lstripped = l.lstrip() | |
2440 | stripped = l.strip() |
|
2439 | stripped = l.strip() | |
2441 | if not stripped: |
|
2440 | if not stripped: | |
2442 | continue |
|
2441 | continue | |
2443 | newlevel = len(l) - len(lstripped) |
|
2442 | newlevel = len(l) - len(lstripped) | |
2444 | if level > 0 and newlevel == 0 and \ |
|
2443 | if level > 0 and newlevel == 0 and \ | |
2445 | not self._is_secondary_block_start(stripped): |
|
2444 | not self._is_secondary_block_start(stripped): | |
2446 | # add empty line |
|
2445 | # add empty line | |
2447 | res.append('') |
|
2446 | res.append('') | |
2448 | res.append(l) |
|
2447 | res.append(l) | |
2449 | level = newlevel |
|
2448 | level = newlevel | |
2450 |
|
2449 | |||
2451 | return '\n'.join(res) + '\n' |
|
2450 | return '\n'.join(res) + '\n' | |
2452 |
|
2451 | |||
2453 | #------------------------------------------------------------------------- |
|
2452 | #------------------------------------------------------------------------- | |
2454 | # Things related to GUI support and pylab |
|
2453 | # Things related to GUI support and pylab | |
2455 | #------------------------------------------------------------------------- |
|
2454 | #------------------------------------------------------------------------- | |
2456 |
|
2455 | |||
2457 | def enable_pylab(self, gui=None): |
|
2456 | def enable_pylab(self, gui=None): | |
2458 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2457 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2459 |
|
2458 | |||
2460 | #------------------------------------------------------------------------- |
|
2459 | #------------------------------------------------------------------------- | |
2461 | # Utilities |
|
2460 | # Utilities | |
2462 | #------------------------------------------------------------------------- |
|
2461 | #------------------------------------------------------------------------- | |
2463 |
|
2462 | |||
2464 | def var_expand(self,cmd,depth=0): |
|
2463 | def var_expand(self,cmd,depth=0): | |
2465 | """Expand python variables in a string. |
|
2464 | """Expand python variables in a string. | |
2466 |
|
2465 | |||
2467 | The depth argument indicates how many frames above the caller should |
|
2466 | The depth argument indicates how many frames above the caller should | |
2468 | 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. | |
2469 |
|
2468 | |||
2470 | The global namespace for expansion is always the user's interactive |
|
2469 | The global namespace for expansion is always the user's interactive | |
2471 | namespace. |
|
2470 | namespace. | |
2472 | """ |
|
2471 | """ | |
2473 |
|
2472 | |||
2474 | return str(ItplNS(cmd, |
|
2473 | return str(ItplNS(cmd, | |
2475 | self.user_ns, # globals |
|
2474 | self.user_ns, # globals | |
2476 | # Skip our own frame in searching for locals: |
|
2475 | # Skip our own frame in searching for locals: | |
2477 | sys._getframe(depth+1).f_locals # locals |
|
2476 | sys._getframe(depth+1).f_locals # locals | |
2478 | )) |
|
2477 | )) | |
2479 |
|
2478 | |||
2480 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2479 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2481 | """Make a new tempfile and return its filename. |
|
2480 | """Make a new tempfile and return its filename. | |
2482 |
|
2481 | |||
2483 | 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 | |
2484 | filename internally so ipython cleans it up at exit time. |
|
2483 | filename internally so ipython cleans it up at exit time. | |
2485 |
|
2484 | |||
2486 | Optional inputs: |
|
2485 | Optional inputs: | |
2487 |
|
2486 | |||
2488 | - 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 | |
2489 | immediately, and the file is closed again.""" |
|
2488 | immediately, and the file is closed again.""" | |
2490 |
|
2489 | |||
2491 | filename = tempfile.mktemp('.py', prefix) |
|
2490 | filename = tempfile.mktemp('.py', prefix) | |
2492 | self.tempfiles.append(filename) |
|
2491 | self.tempfiles.append(filename) | |
2493 |
|
2492 | |||
2494 | if data: |
|
2493 | if data: | |
2495 | tmp_file = open(filename,'w') |
|
2494 | tmp_file = open(filename,'w') | |
2496 | tmp_file.write(data) |
|
2495 | tmp_file.write(data) | |
2497 | tmp_file.close() |
|
2496 | tmp_file.close() | |
2498 | return filename |
|
2497 | return filename | |
2499 |
|
2498 | |||
2500 | # TODO: This should be removed when Term is refactored. |
|
2499 | # TODO: This should be removed when Term is refactored. | |
2501 | def write(self,data): |
|
2500 | def write(self,data): | |
2502 | """Write a string to the default output""" |
|
2501 | """Write a string to the default output""" | |
2503 | io.Term.cout.write(data) |
|
2502 | io.Term.cout.write(data) | |
2504 |
|
2503 | |||
2505 | # TODO: This should be removed when Term is refactored. |
|
2504 | # TODO: This should be removed when Term is refactored. | |
2506 | def write_err(self,data): |
|
2505 | def write_err(self,data): | |
2507 | """Write a string to the default error output""" |
|
2506 | """Write a string to the default error output""" | |
2508 | io.Term.cerr.write(data) |
|
2507 | io.Term.cerr.write(data) | |
2509 |
|
2508 | |||
2510 | def ask_yes_no(self,prompt,default=True): |
|
2509 | def ask_yes_no(self,prompt,default=True): | |
2511 | if self.quiet: |
|
2510 | if self.quiet: | |
2512 | return True |
|
2511 | return True | |
2513 | return ask_yes_no(prompt,default) |
|
2512 | return ask_yes_no(prompt,default) | |
2514 |
|
2513 | |||
2515 | def show_usage(self): |
|
2514 | def show_usage(self): | |
2516 | """Show a usage message""" |
|
2515 | """Show a usage message""" | |
2517 | page.page(IPython.core.usage.interactive_usage) |
|
2516 | page.page(IPython.core.usage.interactive_usage) | |
2518 |
|
2517 | |||
2519 | #------------------------------------------------------------------------- |
|
2518 | #------------------------------------------------------------------------- | |
2520 | # Things related to IPython exiting |
|
2519 | # Things related to IPython exiting | |
2521 | #------------------------------------------------------------------------- |
|
2520 | #------------------------------------------------------------------------- | |
2522 | def atexit_operations(self): |
|
2521 | def atexit_operations(self): | |
2523 | """This will be executed at the time of exit. |
|
2522 | """This will be executed at the time of exit. | |
2524 |
|
2523 | |||
2525 | Cleanup operations and saving of persistent data that is done |
|
2524 | Cleanup operations and saving of persistent data that is done | |
2526 | unconditionally by IPython should be performed here. |
|
2525 | unconditionally by IPython should be performed here. | |
2527 |
|
2526 | |||
2528 | 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 | |
2529 | 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 | |
2530 | code that has the appropriate information, rather than trying to |
|
2529 | code that has the appropriate information, rather than trying to | |
2531 | clutter |
|
2530 | clutter | |
2532 | """ |
|
2531 | """ | |
2533 | # Cleanup all tempfiles left around |
|
2532 | # Cleanup all tempfiles left around | |
2534 | for tfile in self.tempfiles: |
|
2533 | for tfile in self.tempfiles: | |
2535 | try: |
|
2534 | try: | |
2536 | os.unlink(tfile) |
|
2535 | os.unlink(tfile) | |
2537 | except OSError: |
|
2536 | except OSError: | |
2538 | pass |
|
2537 | pass | |
2539 |
|
2538 | |||
2540 | self.save_history() |
|
2539 | self.save_history() | |
2541 |
|
2540 | |||
2542 | # Clear all user namespaces to release all references cleanly. |
|
2541 | # Clear all user namespaces to release all references cleanly. | |
2543 | self.reset() |
|
2542 | self.reset() | |
2544 |
|
2543 | |||
2545 | # Run user hooks |
|
2544 | # Run user hooks | |
2546 | self.hooks.shutdown_hook() |
|
2545 | self.hooks.shutdown_hook() | |
2547 |
|
2546 | |||
2548 | def cleanup(self): |
|
2547 | def cleanup(self): | |
2549 | self.restore_sys_module_state() |
|
2548 | self.restore_sys_module_state() | |
2550 |
|
2549 | |||
2551 |
|
2550 | |||
2552 | class InteractiveShellABC(object): |
|
2551 | class InteractiveShellABC(object): | |
2553 | """An abstract base class for InteractiveShell.""" |
|
2552 | """An abstract base class for InteractiveShell.""" | |
2554 | __metaclass__ = abc.ABCMeta |
|
2553 | __metaclass__ = abc.ABCMeta | |
2555 |
|
2554 | |||
2556 | InteractiveShellABC.register(InteractiveShell) |
|
2555 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3367 +1,3372 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 The IPython Development Team | |
9 |
|
9 | |||
10 | # 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 | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.macro import Macro |
|
49 | from IPython.core.macro import Macro | |
50 | from IPython.core import page |
|
50 | from IPython.core import page | |
51 | from IPython.core.prefilter import ESC_MAGIC |
|
51 | from IPython.core.prefilter import ESC_MAGIC | |
52 | from IPython.lib.pylabtools import mpl_runner |
|
52 | from IPython.lib.pylabtools import mpl_runner | |
53 | from IPython.external.Itpl import itpl, printpl |
|
53 | from IPython.external.Itpl import itpl, printpl | |
54 | from IPython.testing import decorators as testdec |
|
54 | from IPython.testing import decorators as testdec | |
55 | from IPython.utils.io import file_read, nlprint |
|
55 | from IPython.utils.io import file_read, nlprint | |
56 | import IPython.utils.io |
|
56 | import IPython.utils.io | |
57 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Utility functions |
|
67 | # Utility functions | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
91 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
92 |
|
92 | |||
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
94 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
96 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
97 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
97 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
99 | # make Magic a configurable that InteractiveShell does not subclass. |
|
99 | # make Magic a configurable that InteractiveShell does not subclass. | |
100 |
|
100 | |||
101 | class Magic: |
|
101 | class Magic: | |
102 | """Magic functions for InteractiveShell. |
|
102 | """Magic functions for InteractiveShell. | |
103 |
|
103 | |||
104 | Shell functions which can be reached as %function_name. All magic |
|
104 | Shell functions which can be reached as %function_name. All magic | |
105 | functions should accept a string, which they can parse for their own |
|
105 | functions should accept a string, which they can parse for their own | |
106 | needs. This can make some functions easier to type, eg `%cd ../` |
|
106 | needs. This can make some functions easier to type, eg `%cd ../` | |
107 | vs. `%cd("../")` |
|
107 | vs. `%cd("../")` | |
108 |
|
108 | |||
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
110 | at the command line, but it is is needed in the definition. """ |
|
110 | at the command line, but it is is needed in the definition. """ | |
111 |
|
111 | |||
112 | # class globals |
|
112 | # class globals | |
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
115 |
|
115 | |||
116 | #...................................................................... |
|
116 | #...................................................................... | |
117 | # some utility functions |
|
117 | # some utility functions | |
118 |
|
118 | |||
119 | def __init__(self,shell): |
|
119 | def __init__(self,shell): | |
120 |
|
120 | |||
121 | self.options_table = {} |
|
121 | self.options_table = {} | |
122 | if profile is None: |
|
122 | if profile is None: | |
123 | self.magic_prun = self.profile_missing_notice |
|
123 | self.magic_prun = self.profile_missing_notice | |
124 | self.shell = shell |
|
124 | self.shell = shell | |
125 |
|
125 | |||
126 | # namespace for holding state we may need |
|
126 | # namespace for holding state we may need | |
127 | self._magic_state = Bunch() |
|
127 | self._magic_state = Bunch() | |
128 |
|
128 | |||
129 | def profile_missing_notice(self, *args, **kwargs): |
|
129 | def profile_missing_notice(self, *args, **kwargs): | |
130 | error("""\ |
|
130 | error("""\ | |
131 | The profile module could not be found. It has been removed from the standard |
|
131 | The profile module could not be found. It has been removed from the standard | |
132 | python packages because of its non-free license. To use profiling, install the |
|
132 | python packages because of its non-free license. To use profiling, install the | |
133 | python-profiler package from non-free.""") |
|
133 | python-profiler package from non-free.""") | |
134 |
|
134 | |||
135 | def default_option(self,fn,optstr): |
|
135 | def default_option(self,fn,optstr): | |
136 | """Make an entry in the options_table for fn, with value optstr""" |
|
136 | """Make an entry in the options_table for fn, with value optstr""" | |
137 |
|
137 | |||
138 | if fn not in self.lsmagic(): |
|
138 | if fn not in self.lsmagic(): | |
139 | error("%s is not a magic function" % fn) |
|
139 | error("%s is not a magic function" % fn) | |
140 | self.options_table[fn] = optstr |
|
140 | self.options_table[fn] = optstr | |
141 |
|
141 | |||
142 | def lsmagic(self): |
|
142 | def lsmagic(self): | |
143 | """Return a list of currently available magic functions. |
|
143 | """Return a list of currently available magic functions. | |
144 |
|
144 | |||
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
146 | ['magic_ls','magic_cd',...]""" |
|
146 | ['magic_ls','magic_cd',...]""" | |
147 |
|
147 | |||
148 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
148 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
149 |
|
149 | |||
150 | # magics in class definition |
|
150 | # magics in class definition | |
151 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
152 | callable(Magic.__dict__[fn]) |
|
152 | callable(Magic.__dict__[fn]) | |
153 | # in instance namespace (run-time user additions) |
|
153 | # in instance namespace (run-time user additions) | |
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
155 | callable(self.__dict__[fn]) |
|
155 | callable(self.__dict__[fn]) | |
156 | # and bound magics by user (so they can access self): |
|
156 | # and bound magics by user (so they can access self): | |
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
158 | callable(self.__class__.__dict__[fn]) |
|
158 | callable(self.__class__.__dict__[fn]) | |
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
160 | filter(inst_magic,self.__dict__.keys()) + \ |
|
160 | filter(inst_magic,self.__dict__.keys()) + \ | |
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
162 | out = [] |
|
162 | out = [] | |
163 | for fn in set(magics): |
|
163 | for fn in set(magics): | |
164 | out.append(fn.replace('magic_','',1)) |
|
164 | out.append(fn.replace('magic_','',1)) | |
165 | out.sort() |
|
165 | out.sort() | |
166 | return out |
|
166 | return out | |
167 |
|
167 | |||
168 | def extract_input_slices(self,slices,raw=False): |
|
168 | def extract_input_slices(self,slices,raw=False): | |
169 | """Return as a string a set of input history slices. |
|
169 | """Return as a string a set of input history slices. | |
170 |
|
170 | |||
171 | Inputs: |
|
171 | Inputs: | |
172 |
|
172 | |||
173 | - slices: the set of slices is given as a list of strings (like |
|
173 | - slices: the set of slices is given as a list of strings (like | |
174 | ['1','4:8','9'], since this function is for use by magic functions |
|
174 | ['1','4:8','9'], since this function is for use by magic functions | |
175 | which get their arguments as strings. |
|
175 | which get their arguments as strings. | |
176 |
|
176 | |||
177 | Optional inputs: |
|
177 | Optional inputs: | |
178 |
|
178 | |||
179 | - raw(False): by default, the processed input is used. If this is |
|
179 | - raw(False): by default, the processed input is used. If this is | |
180 | true, the raw input history is used instead. |
|
180 | true, the raw input history is used instead. | |
181 |
|
181 | |||
182 | Note that slices can be called with two notations: |
|
182 | Note that slices can be called with two notations: | |
183 |
|
183 | |||
184 | N:M -> standard python form, means including items N...(M-1). |
|
184 | N:M -> standard python form, means including items N...(M-1). | |
185 |
|
185 | |||
186 | N-M -> include items N..M (closed endpoint).""" |
|
186 | N-M -> include items N..M (closed endpoint).""" | |
187 |
|
187 | |||
188 | if raw: |
|
188 | if raw: | |
189 | hist = self.shell.history_manager.input_hist_raw |
|
189 | hist = self.shell.history_manager.input_hist_raw | |
190 | else: |
|
190 | else: | |
191 | hist = self.shell.history_manager.input_hist_parsed |
|
191 | hist = self.shell.history_manager.input_hist_parsed | |
192 |
|
192 | |||
193 | cmds = [] |
|
193 | cmds = [] | |
194 | for chunk in slices: |
|
194 | for chunk in slices: | |
195 | if ':' in chunk: |
|
195 | if ':' in chunk: | |
196 | ini,fin = map(int,chunk.split(':')) |
|
196 | ini,fin = map(int,chunk.split(':')) | |
197 | elif '-' in chunk: |
|
197 | elif '-' in chunk: | |
198 | ini,fin = map(int,chunk.split('-')) |
|
198 | ini,fin = map(int,chunk.split('-')) | |
199 | fin += 1 |
|
199 | fin += 1 | |
200 | else: |
|
200 | else: | |
201 | ini = int(chunk) |
|
201 | ini = int(chunk) | |
202 | fin = ini+1 |
|
202 | fin = ini+1 | |
203 | cmds.append(''.join(hist[ini:fin])) |
|
203 | cmds.append(''.join(hist[ini:fin])) | |
204 | return cmds |
|
204 | return cmds | |
205 |
|
205 | |||
206 | def arg_err(self,func): |
|
206 | def arg_err(self,func): | |
207 | """Print docstring if incorrect arguments were passed""" |
|
207 | """Print docstring if incorrect arguments were passed""" | |
208 | print 'Error in arguments:' |
|
208 | print 'Error in arguments:' | |
209 | print oinspect.getdoc(func) |
|
209 | print oinspect.getdoc(func) | |
210 |
|
210 | |||
211 | def format_latex(self,strng): |
|
211 | def format_latex(self,strng): | |
212 | """Format a string for latex inclusion.""" |
|
212 | """Format a string for latex inclusion.""" | |
213 |
|
213 | |||
214 | # Characters that need to be escaped for latex: |
|
214 | # Characters that need to be escaped for latex: | |
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
216 | # Magic command names as headers: |
|
216 | # Magic command names as headers: | |
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
218 | re.MULTILINE) |
|
218 | re.MULTILINE) | |
219 | # Magic commands |
|
219 | # Magic commands | |
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
221 | re.MULTILINE) |
|
221 | re.MULTILINE) | |
222 | # Paragraph continue |
|
222 | # Paragraph continue | |
223 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
223 | par_re = re.compile(r'\\$',re.MULTILINE) | |
224 |
|
224 | |||
225 | # The "\n" symbol |
|
225 | # The "\n" symbol | |
226 | newline_re = re.compile(r'\\n') |
|
226 | newline_re = re.compile(r'\\n') | |
227 |
|
227 | |||
228 | # Now build the string for output: |
|
228 | # Now build the string for output: | |
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
231 | strng) |
|
231 | strng) | |
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
233 | strng = par_re.sub(r'\\\\',strng) |
|
233 | strng = par_re.sub(r'\\\\',strng) | |
234 | strng = escape_re.sub(r'\\\1',strng) |
|
234 | strng = escape_re.sub(r'\\\1',strng) | |
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
236 | return strng |
|
236 | return strng | |
237 |
|
237 | |||
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
239 | """Parse options passed to an argument string. |
|
239 | """Parse options passed to an argument string. | |
240 |
|
240 | |||
241 | The interface is similar to that of getopt(), but it returns back a |
|
241 | The interface is similar to that of getopt(), but it returns back a | |
242 | Struct with the options as keys and the stripped argument string still |
|
242 | Struct with the options as keys and the stripped argument string still | |
243 | as a string. |
|
243 | as a string. | |
244 |
|
244 | |||
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
246 | This allows us to easily expand variables, glob files, quote |
|
246 | This allows us to easily expand variables, glob files, quote | |
247 | arguments, etc. |
|
247 | arguments, etc. | |
248 |
|
248 | |||
249 | Options: |
|
249 | Options: | |
250 | -mode: default 'string'. If given as 'list', the argument string is |
|
250 | -mode: default 'string'. If given as 'list', the argument string is | |
251 | returned as a list (split on whitespace) instead of a string. |
|
251 | returned as a list (split on whitespace) instead of a string. | |
252 |
|
252 | |||
253 | -list_all: put all option values in lists. Normally only options |
|
253 | -list_all: put all option values in lists. Normally only options | |
254 | appearing more than once are put in a list. |
|
254 | appearing more than once are put in a list. | |
255 |
|
255 | |||
256 | -posix (True): whether to split the input line in POSIX mode or not, |
|
256 | -posix (True): whether to split the input line in POSIX mode or not, | |
257 | as per the conventions outlined in the shlex module from the |
|
257 | as per the conventions outlined in the shlex module from the | |
258 | standard library.""" |
|
258 | standard library.""" | |
259 |
|
259 | |||
260 | # inject default options at the beginning of the input line |
|
260 | # inject default options at the beginning of the input line | |
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
263 |
|
263 | |||
264 | mode = kw.get('mode','string') |
|
264 | mode = kw.get('mode','string') | |
265 | if mode not in ['string','list']: |
|
265 | if mode not in ['string','list']: | |
266 | raise ValueError,'incorrect mode given: %s' % mode |
|
266 | raise ValueError,'incorrect mode given: %s' % mode | |
267 | # Get options |
|
267 | # Get options | |
268 | list_all = kw.get('list_all',0) |
|
268 | list_all = kw.get('list_all',0) | |
269 | posix = kw.get('posix', os.name == 'posix') |
|
269 | posix = kw.get('posix', os.name == 'posix') | |
270 |
|
270 | |||
271 | # Check if we have more than one argument to warrant extra processing: |
|
271 | # Check if we have more than one argument to warrant extra processing: | |
272 | odict = {} # Dictionary with options |
|
272 | odict = {} # Dictionary with options | |
273 | args = arg_str.split() |
|
273 | args = arg_str.split() | |
274 | if len(args) >= 1: |
|
274 | if len(args) >= 1: | |
275 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
275 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
276 | # need to look for options |
|
276 | # need to look for options | |
277 | argv = arg_split(arg_str,posix) |
|
277 | argv = arg_split(arg_str,posix) | |
278 | # Do regular option processing |
|
278 | # Do regular option processing | |
279 | try: |
|
279 | try: | |
280 | opts,args = getopt(argv,opt_str,*long_opts) |
|
280 | opts,args = getopt(argv,opt_str,*long_opts) | |
281 | except GetoptError,e: |
|
281 | except GetoptError,e: | |
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
283 | " ".join(long_opts))) |
|
283 | " ".join(long_opts))) | |
284 | for o,a in opts: |
|
284 | for o,a in opts: | |
285 | if o.startswith('--'): |
|
285 | if o.startswith('--'): | |
286 | o = o[2:] |
|
286 | o = o[2:] | |
287 | else: |
|
287 | else: | |
288 | o = o[1:] |
|
288 | o = o[1:] | |
289 | try: |
|
289 | try: | |
290 | odict[o].append(a) |
|
290 | odict[o].append(a) | |
291 | except AttributeError: |
|
291 | except AttributeError: | |
292 | odict[o] = [odict[o],a] |
|
292 | odict[o] = [odict[o],a] | |
293 | except KeyError: |
|
293 | except KeyError: | |
294 | if list_all: |
|
294 | if list_all: | |
295 | odict[o] = [a] |
|
295 | odict[o] = [a] | |
296 | else: |
|
296 | else: | |
297 | odict[o] = a |
|
297 | odict[o] = a | |
298 |
|
298 | |||
299 | # Prepare opts,args for return |
|
299 | # Prepare opts,args for return | |
300 | opts = Struct(odict) |
|
300 | opts = Struct(odict) | |
301 | if mode == 'string': |
|
301 | if mode == 'string': | |
302 | args = ' '.join(args) |
|
302 | args = ' '.join(args) | |
303 |
|
303 | |||
304 | return opts,args |
|
304 | return opts,args | |
305 |
|
305 | |||
306 | #...................................................................... |
|
306 | #...................................................................... | |
307 | # And now the actual magic functions |
|
307 | # And now the actual magic functions | |
308 |
|
308 | |||
309 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
309 | # Functions for IPython shell work (vars,funcs, config, etc) | |
310 | def magic_lsmagic(self, parameter_s = ''): |
|
310 | def magic_lsmagic(self, parameter_s = ''): | |
311 | """List currently available magic functions.""" |
|
311 | """List currently available magic functions.""" | |
312 | mesc = ESC_MAGIC |
|
312 | mesc = ESC_MAGIC | |
313 | print 'Available magic functions:\n'+mesc+\ |
|
313 | print 'Available magic functions:\n'+mesc+\ | |
314 | (' '+mesc).join(self.lsmagic()) |
|
314 | (' '+mesc).join(self.lsmagic()) | |
315 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
315 | print '\n' + Magic.auto_status[self.shell.automagic] | |
316 | return None |
|
316 | return None | |
317 |
|
317 | |||
318 | def magic_magic(self, parameter_s = ''): |
|
318 | def magic_magic(self, parameter_s = ''): | |
319 | """Print information about the magic function system. |
|
319 | """Print information about the magic function system. | |
320 |
|
320 | |||
321 | Supported formats: -latex, -brief, -rest |
|
321 | Supported formats: -latex, -brief, -rest | |
322 | """ |
|
322 | """ | |
323 |
|
323 | |||
324 | mode = '' |
|
324 | mode = '' | |
325 | try: |
|
325 | try: | |
326 | if parameter_s.split()[0] == '-latex': |
|
326 | if parameter_s.split()[0] == '-latex': | |
327 | mode = 'latex' |
|
327 | mode = 'latex' | |
328 | if parameter_s.split()[0] == '-brief': |
|
328 | if parameter_s.split()[0] == '-brief': | |
329 | mode = 'brief' |
|
329 | mode = 'brief' | |
330 | if parameter_s.split()[0] == '-rest': |
|
330 | if parameter_s.split()[0] == '-rest': | |
331 | mode = 'rest' |
|
331 | mode = 'rest' | |
332 | rest_docs = [] |
|
332 | rest_docs = [] | |
333 | except: |
|
333 | except: | |
334 | pass |
|
334 | pass | |
335 |
|
335 | |||
336 | magic_docs = [] |
|
336 | magic_docs = [] | |
337 | for fname in self.lsmagic(): |
|
337 | for fname in self.lsmagic(): | |
338 | mname = 'magic_' + fname |
|
338 | mname = 'magic_' + fname | |
339 | for space in (Magic,self,self.__class__): |
|
339 | for space in (Magic,self,self.__class__): | |
340 | try: |
|
340 | try: | |
341 | fn = space.__dict__[mname] |
|
341 | fn = space.__dict__[mname] | |
342 | except KeyError: |
|
342 | except KeyError: | |
343 | pass |
|
343 | pass | |
344 | else: |
|
344 | else: | |
345 | break |
|
345 | break | |
346 | if mode == 'brief': |
|
346 | if mode == 'brief': | |
347 | # only first line |
|
347 | # only first line | |
348 | if fn.__doc__: |
|
348 | if fn.__doc__: | |
349 | fndoc = fn.__doc__.split('\n',1)[0] |
|
349 | fndoc = fn.__doc__.split('\n',1)[0] | |
350 | else: |
|
350 | else: | |
351 | fndoc = 'No documentation' |
|
351 | fndoc = 'No documentation' | |
352 | else: |
|
352 | else: | |
353 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.rstrip() |
|
354 | fndoc = fn.__doc__.rstrip() | |
355 | else: |
|
355 | else: | |
356 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
357 |
|
357 | |||
358 |
|
358 | |||
359 | if mode == 'rest': |
|
359 | if mode == 'rest': | |
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
361 | fname,fndoc)) |
|
361 | fname,fndoc)) | |
362 |
|
362 | |||
363 | else: |
|
363 | else: | |
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
365 | fname,fndoc)) |
|
365 | fname,fndoc)) | |
366 |
|
366 | |||
367 | magic_docs = ''.join(magic_docs) |
|
367 | magic_docs = ''.join(magic_docs) | |
368 |
|
368 | |||
369 | if mode == 'rest': |
|
369 | if mode == 'rest': | |
370 | return "".join(rest_docs) |
|
370 | return "".join(rest_docs) | |
371 |
|
371 | |||
372 | if mode == 'latex': |
|
372 | if mode == 'latex': | |
373 | print self.format_latex(magic_docs) |
|
373 | print self.format_latex(magic_docs) | |
374 | return |
|
374 | return | |
375 | else: |
|
375 | else: | |
376 | magic_docs = format_screen(magic_docs) |
|
376 | magic_docs = format_screen(magic_docs) | |
377 | if mode == 'brief': |
|
377 | if mode == 'brief': | |
378 | return magic_docs |
|
378 | return magic_docs | |
379 |
|
379 | |||
380 | outmsg = """ |
|
380 | outmsg = """ | |
381 | IPython's 'magic' functions |
|
381 | IPython's 'magic' functions | |
382 | =========================== |
|
382 | =========================== | |
383 |
|
383 | |||
384 | The magic function system provides a series of functions which allow you to |
|
384 | The magic function system provides a series of functions which allow you to | |
385 | control the behavior of IPython itself, plus a lot of system-type |
|
385 | control the behavior of IPython itself, plus a lot of system-type | |
386 | features. All these functions are prefixed with a % character, but parameters |
|
386 | features. All these functions are prefixed with a % character, but parameters | |
387 | are given without parentheses or quotes. |
|
387 | are given without parentheses or quotes. | |
388 |
|
388 | |||
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
390 | %automagic function), you don't need to type in the % explicitly. By default, |
|
390 | %automagic function), you don't need to type in the % explicitly. By default, | |
391 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
391 | IPython ships with automagic on, so you should only rarely need the % escape. | |
392 |
|
392 | |||
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
394 | to 'mydir', if it exists. |
|
394 | to 'mydir', if it exists. | |
395 |
|
395 | |||
396 | You can define your own magic functions to extend the system. See the supplied |
|
396 | You can define your own magic functions to extend the system. See the supplied | |
397 | ipythonrc and example-magic.py files for details (in your ipython |
|
397 | ipythonrc and example-magic.py files for details (in your ipython | |
398 | configuration directory, typically $HOME/.ipython/). |
|
398 | configuration directory, typically $HOME/.ipython/). | |
399 |
|
399 | |||
400 | You can also define your own aliased names for magic functions. In your |
|
400 | You can also define your own aliased names for magic functions. In your | |
401 | ipythonrc file, placing a line like: |
|
401 | ipythonrc file, placing a line like: | |
402 |
|
402 | |||
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
404 |
|
404 | |||
405 | will define %pf as a new name for %profile. |
|
405 | will define %pf as a new name for %profile. | |
406 |
|
406 | |||
407 | You can also call magics in code using the magic() function, which IPython |
|
407 | You can also call magics in code using the magic() function, which IPython | |
408 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
408 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
409 |
|
409 | |||
410 | For a list of the available magic functions, use %lsmagic. For a description |
|
410 | For a list of the available magic functions, use %lsmagic. For a description | |
411 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
411 | of any of them, type %magic_name?, e.g. '%cd?'. | |
412 |
|
412 | |||
413 | Currently the magic system has the following functions:\n""" |
|
413 | Currently the magic system has the following functions:\n""" | |
414 |
|
414 | |||
415 | mesc = ESC_MAGIC |
|
415 | mesc = ESC_MAGIC | |
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
417 | "\n\n%s%s\n\n%s" % (outmsg, |
|
417 | "\n\n%s%s\n\n%s" % (outmsg, | |
418 | magic_docs,mesc,mesc, |
|
418 | magic_docs,mesc,mesc, | |
419 | (' '+mesc).join(self.lsmagic()), |
|
419 | (' '+mesc).join(self.lsmagic()), | |
420 | Magic.auto_status[self.shell.automagic] ) ) |
|
420 | Magic.auto_status[self.shell.automagic] ) ) | |
421 | page.page(outmsg) |
|
421 | page.page(outmsg) | |
422 |
|
422 | |||
423 | def magic_automagic(self, parameter_s = ''): |
|
423 | def magic_automagic(self, parameter_s = ''): | |
424 | """Make magic functions callable without having to type the initial %. |
|
424 | """Make magic functions callable without having to type the initial %. | |
425 |
|
425 | |||
426 | Without argumentsl toggles on/off (when off, you must call it as |
|
426 | Without argumentsl toggles on/off (when off, you must call it as | |
427 | %automagic, of course). With arguments it sets the value, and you can |
|
427 | %automagic, of course). With arguments it sets the value, and you can | |
428 | use any of (case insensitive): |
|
428 | use any of (case insensitive): | |
429 |
|
429 | |||
430 | - on,1,True: to activate |
|
430 | - on,1,True: to activate | |
431 |
|
431 | |||
432 | - off,0,False: to deactivate. |
|
432 | - off,0,False: to deactivate. | |
433 |
|
433 | |||
434 | Note that magic functions have lowest priority, so if there's a |
|
434 | Note that magic functions have lowest priority, so if there's a | |
435 | variable whose name collides with that of a magic fn, automagic won't |
|
435 | variable whose name collides with that of a magic fn, automagic won't | |
436 | work for that function (you get the variable instead). However, if you |
|
436 | work for that function (you get the variable instead). However, if you | |
437 | delete the variable (del var), the previously shadowed magic function |
|
437 | delete the variable (del var), the previously shadowed magic function | |
438 | becomes visible to automagic again.""" |
|
438 | becomes visible to automagic again.""" | |
439 |
|
439 | |||
440 | arg = parameter_s.lower() |
|
440 | arg = parameter_s.lower() | |
441 | if parameter_s in ('on','1','true'): |
|
441 | if parameter_s in ('on','1','true'): | |
442 | self.shell.automagic = True |
|
442 | self.shell.automagic = True | |
443 | elif parameter_s in ('off','0','false'): |
|
443 | elif parameter_s in ('off','0','false'): | |
444 | self.shell.automagic = False |
|
444 | self.shell.automagic = False | |
445 | else: |
|
445 | else: | |
446 | self.shell.automagic = not self.shell.automagic |
|
446 | self.shell.automagic = not self.shell.automagic | |
447 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
447 | print '\n' + Magic.auto_status[self.shell.automagic] | |
448 |
|
448 | |||
449 | @testdec.skip_doctest |
|
449 | @testdec.skip_doctest | |
450 | def magic_autocall(self, parameter_s = ''): |
|
450 | def magic_autocall(self, parameter_s = ''): | |
451 | """Make functions callable without having to type parentheses. |
|
451 | """Make functions callable without having to type parentheses. | |
452 |
|
452 | |||
453 | Usage: |
|
453 | Usage: | |
454 |
|
454 | |||
455 | %autocall [mode] |
|
455 | %autocall [mode] | |
456 |
|
456 | |||
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
458 | value is toggled on and off (remembering the previous state). |
|
458 | value is toggled on and off (remembering the previous state). | |
459 |
|
459 | |||
460 | In more detail, these values mean: |
|
460 | In more detail, these values mean: | |
461 |
|
461 | |||
462 | 0 -> fully disabled |
|
462 | 0 -> fully disabled | |
463 |
|
463 | |||
464 | 1 -> active, but do not apply if there are no arguments on the line. |
|
464 | 1 -> active, but do not apply if there are no arguments on the line. | |
465 |
|
465 | |||
466 | In this mode, you get: |
|
466 | In this mode, you get: | |
467 |
|
467 | |||
468 | In [1]: callable |
|
468 | In [1]: callable | |
469 | Out[1]: <built-in function callable> |
|
469 | Out[1]: <built-in function callable> | |
470 |
|
470 | |||
471 | In [2]: callable 'hello' |
|
471 | In [2]: callable 'hello' | |
472 | ------> callable('hello') |
|
472 | ------> callable('hello') | |
473 | Out[2]: False |
|
473 | Out[2]: False | |
474 |
|
474 | |||
475 | 2 -> Active always. Even if no arguments are present, the callable |
|
475 | 2 -> Active always. Even if no arguments are present, the callable | |
476 | object is called: |
|
476 | object is called: | |
477 |
|
477 | |||
478 | In [2]: float |
|
478 | In [2]: float | |
479 | ------> float() |
|
479 | ------> float() | |
480 | Out[2]: 0.0 |
|
480 | Out[2]: 0.0 | |
481 |
|
481 | |||
482 | Note that even with autocall off, you can still use '/' at the start of |
|
482 | Note that even with autocall off, you can still use '/' at the start of | |
483 | a line to treat the first argument on the command line as a function |
|
483 | a line to treat the first argument on the command line as a function | |
484 | and add parentheses to it: |
|
484 | and add parentheses to it: | |
485 |
|
485 | |||
486 | In [8]: /str 43 |
|
486 | In [8]: /str 43 | |
487 | ------> str(43) |
|
487 | ------> str(43) | |
488 | Out[8]: '43' |
|
488 | Out[8]: '43' | |
489 |
|
489 | |||
490 | # all-random (note for auto-testing) |
|
490 | # all-random (note for auto-testing) | |
491 | """ |
|
491 | """ | |
492 |
|
492 | |||
493 | if parameter_s: |
|
493 | if parameter_s: | |
494 | arg = int(parameter_s) |
|
494 | arg = int(parameter_s) | |
495 | else: |
|
495 | else: | |
496 | arg = 'toggle' |
|
496 | arg = 'toggle' | |
497 |
|
497 | |||
498 | if not arg in (0,1,2,'toggle'): |
|
498 | if not arg in (0,1,2,'toggle'): | |
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
500 | return |
|
500 | return | |
501 |
|
501 | |||
502 | if arg in (0,1,2): |
|
502 | if arg in (0,1,2): | |
503 | self.shell.autocall = arg |
|
503 | self.shell.autocall = arg | |
504 | else: # toggle |
|
504 | else: # toggle | |
505 | if self.shell.autocall: |
|
505 | if self.shell.autocall: | |
506 | self._magic_state.autocall_save = self.shell.autocall |
|
506 | self._magic_state.autocall_save = self.shell.autocall | |
507 | self.shell.autocall = 0 |
|
507 | self.shell.autocall = 0 | |
508 | else: |
|
508 | else: | |
509 | try: |
|
509 | try: | |
510 | self.shell.autocall = self._magic_state.autocall_save |
|
510 | self.shell.autocall = self._magic_state.autocall_save | |
511 | except AttributeError: |
|
511 | except AttributeError: | |
512 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
512 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
513 |
|
513 | |||
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
515 |
|
515 | |||
516 |
|
516 | |||
517 | def magic_page(self, parameter_s=''): |
|
517 | def magic_page(self, parameter_s=''): | |
518 | """Pretty print the object and display it through a pager. |
|
518 | """Pretty print the object and display it through a pager. | |
519 |
|
519 | |||
520 | %page [options] OBJECT |
|
520 | %page [options] OBJECT | |
521 |
|
521 | |||
522 | If no object is given, use _ (last output). |
|
522 | If no object is given, use _ (last output). | |
523 |
|
523 | |||
524 | Options: |
|
524 | Options: | |
525 |
|
525 | |||
526 | -r: page str(object), don't pretty-print it.""" |
|
526 | -r: page str(object), don't pretty-print it.""" | |
527 |
|
527 | |||
528 | # After a function contributed by Olivier Aubert, slightly modified. |
|
528 | # After a function contributed by Olivier Aubert, slightly modified. | |
529 |
|
529 | |||
530 | # Process options/args |
|
530 | # Process options/args | |
531 | opts,args = self.parse_options(parameter_s,'r') |
|
531 | opts,args = self.parse_options(parameter_s,'r') | |
532 | raw = 'r' in opts |
|
532 | raw = 'r' in opts | |
533 |
|
533 | |||
534 | oname = args and args or '_' |
|
534 | oname = args and args or '_' | |
535 | info = self._ofind(oname) |
|
535 | info = self._ofind(oname) | |
536 | if info['found']: |
|
536 | if info['found']: | |
537 | txt = (raw and str or pformat)( info['obj'] ) |
|
537 | txt = (raw and str or pformat)( info['obj'] ) | |
538 | page.page(txt) |
|
538 | page.page(txt) | |
539 | else: |
|
539 | else: | |
540 | print 'Object `%s` not found' % oname |
|
540 | print 'Object `%s` not found' % oname | |
541 |
|
541 | |||
542 | def magic_profile(self, parameter_s=''): |
|
542 | def magic_profile(self, parameter_s=''): | |
543 | """Print your currently active IPython profile.""" |
|
543 | """Print your currently active IPython profile.""" | |
544 | if self.shell.profile: |
|
544 | if self.shell.profile: | |
545 | printpl('Current IPython profile: $self.shell.profile.') |
|
545 | printpl('Current IPython profile: $self.shell.profile.') | |
546 | else: |
|
546 | else: | |
547 | print 'No profile active.' |
|
547 | print 'No profile active.' | |
548 |
|
548 | |||
549 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
549 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
550 | """Provide detailed information about an object. |
|
550 | """Provide detailed information about an object. | |
551 |
|
551 | |||
552 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
552 | '%pinfo object' is just a synonym for object? or ?object.""" | |
553 |
|
553 | |||
554 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
554 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
555 |
|
555 | |||
556 |
|
556 | |||
557 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
557 | # detail_level: 0 -> obj? , 1 -> obj?? | |
558 | detail_level = 0 |
|
558 | detail_level = 0 | |
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
560 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
560 | # happen if the user types 'pinfo foo?' at the cmd line. | |
561 | pinfo,qmark1,oname,qmark2 = \ |
|
561 | pinfo,qmark1,oname,qmark2 = \ | |
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
563 | if pinfo or qmark1 or qmark2: |
|
563 | if pinfo or qmark1 or qmark2: | |
564 | detail_level = 1 |
|
564 | detail_level = 1 | |
565 | if "*" in oname: |
|
565 | if "*" in oname: | |
566 | self.magic_psearch(oname) |
|
566 | self.magic_psearch(oname) | |
567 | else: |
|
567 | else: | |
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
569 | namespaces=namespaces) |
|
569 | namespaces=namespaces) | |
570 |
|
570 | |||
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
572 | """Provide extra detailed information about an object. |
|
572 | """Provide extra detailed information about an object. | |
573 |
|
573 | |||
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
576 | namespaces=namespaces) |
|
576 | namespaces=namespaces) | |
577 |
|
577 | |||
578 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
578 | def magic_pdef(self, parameter_s='', namespaces=None): | |
579 | """Print the definition header for any callable object. |
|
579 | """Print the definition header for any callable object. | |
580 |
|
580 | |||
581 | If the object is a class, print the constructor information.""" |
|
581 | If the object is a class, print the constructor information.""" | |
582 | self._inspect('pdef',parameter_s, namespaces) |
|
582 | self._inspect('pdef',parameter_s, namespaces) | |
583 |
|
583 | |||
584 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
584 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
585 | """Print the docstring for an object. |
|
585 | """Print the docstring for an object. | |
586 |
|
586 | |||
587 | If the given object is a class, it will print both the class and the |
|
587 | If the given object is a class, it will print both the class and the | |
588 | constructor docstrings.""" |
|
588 | constructor docstrings.""" | |
589 | self._inspect('pdoc',parameter_s, namespaces) |
|
589 | self._inspect('pdoc',parameter_s, namespaces) | |
590 |
|
590 | |||
591 | def magic_psource(self, parameter_s='', namespaces=None): |
|
591 | def magic_psource(self, parameter_s='', namespaces=None): | |
592 | """Print (or run through pager) the source code for an object.""" |
|
592 | """Print (or run through pager) the source code for an object.""" | |
593 | self._inspect('psource',parameter_s, namespaces) |
|
593 | self._inspect('psource',parameter_s, namespaces) | |
594 |
|
594 | |||
595 | def magic_pfile(self, parameter_s=''): |
|
595 | def magic_pfile(self, parameter_s=''): | |
596 | """Print (or run through pager) the file where an object is defined. |
|
596 | """Print (or run through pager) the file where an object is defined. | |
597 |
|
597 | |||
598 | The file opens at the line where the object definition begins. IPython |
|
598 | The file opens at the line where the object definition begins. IPython | |
599 | will honor the environment variable PAGER if set, and otherwise will |
|
599 | will honor the environment variable PAGER if set, and otherwise will | |
600 | do its best to print the file in a convenient form. |
|
600 | do its best to print the file in a convenient form. | |
601 |
|
601 | |||
602 | If the given argument is not an object currently defined, IPython will |
|
602 | If the given argument is not an object currently defined, IPython will | |
603 | try to interpret it as a filename (automatically adding a .py extension |
|
603 | try to interpret it as a filename (automatically adding a .py extension | |
604 | if needed). You can thus use %pfile as a syntax highlighting code |
|
604 | if needed). You can thus use %pfile as a syntax highlighting code | |
605 | viewer.""" |
|
605 | viewer.""" | |
606 |
|
606 | |||
607 | # first interpret argument as an object name |
|
607 | # first interpret argument as an object name | |
608 | out = self._inspect('pfile',parameter_s) |
|
608 | out = self._inspect('pfile',parameter_s) | |
609 | # if not, try the input as a filename |
|
609 | # if not, try the input as a filename | |
610 | if out == 'not found': |
|
610 | if out == 'not found': | |
611 | try: |
|
611 | try: | |
612 | filename = get_py_filename(parameter_s) |
|
612 | filename = get_py_filename(parameter_s) | |
613 | except IOError,msg: |
|
613 | except IOError,msg: | |
614 | print msg |
|
614 | print msg | |
615 | return |
|
615 | return | |
616 | page.page(self.shell.inspector.format(file(filename).read())) |
|
616 | page.page(self.shell.inspector.format(file(filename).read())) | |
617 |
|
617 | |||
618 | def magic_psearch(self, parameter_s=''): |
|
618 | def magic_psearch(self, parameter_s=''): | |
619 | """Search for object in namespaces by wildcard. |
|
619 | """Search for object in namespaces by wildcard. | |
620 |
|
620 | |||
621 | %psearch [options] PATTERN [OBJECT TYPE] |
|
621 | %psearch [options] PATTERN [OBJECT TYPE] | |
622 |
|
622 | |||
623 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
623 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
624 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
624 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
625 | rest of the command line must be unchanged (options come first), so |
|
625 | rest of the command line must be unchanged (options come first), so | |
626 | for example the following forms are equivalent |
|
626 | for example the following forms are equivalent | |
627 |
|
627 | |||
628 | %psearch -i a* function |
|
628 | %psearch -i a* function | |
629 | -i a* function? |
|
629 | -i a* function? | |
630 | ?-i a* function |
|
630 | ?-i a* function | |
631 |
|
631 | |||
632 | Arguments: |
|
632 | Arguments: | |
633 |
|
633 | |||
634 | PATTERN |
|
634 | PATTERN | |
635 |
|
635 | |||
636 | where PATTERN is a string containing * as a wildcard similar to its |
|
636 | where PATTERN is a string containing * as a wildcard similar to its | |
637 | use in a shell. The pattern is matched in all namespaces on the |
|
637 | use in a shell. The pattern is matched in all namespaces on the | |
638 | search path. By default objects starting with a single _ are not |
|
638 | search path. By default objects starting with a single _ are not | |
639 | matched, many IPython generated objects have a single |
|
639 | matched, many IPython generated objects have a single | |
640 | underscore. The default is case insensitive matching. Matching is |
|
640 | underscore. The default is case insensitive matching. Matching is | |
641 | also done on the attributes of objects and not only on the objects |
|
641 | also done on the attributes of objects and not only on the objects | |
642 | in a module. |
|
642 | in a module. | |
643 |
|
643 | |||
644 | [OBJECT TYPE] |
|
644 | [OBJECT TYPE] | |
645 |
|
645 | |||
646 | Is the name of a python type from the types module. The name is |
|
646 | Is the name of a python type from the types module. The name is | |
647 | given in lowercase without the ending type, ex. StringType is |
|
647 | given in lowercase without the ending type, ex. StringType is | |
648 | written string. By adding a type here only objects matching the |
|
648 | written string. By adding a type here only objects matching the | |
649 | given type are matched. Using all here makes the pattern match all |
|
649 | given type are matched. Using all here makes the pattern match all | |
650 | types (this is the default). |
|
650 | types (this is the default). | |
651 |
|
651 | |||
652 | Options: |
|
652 | Options: | |
653 |
|
653 | |||
654 | -a: makes the pattern match even objects whose names start with a |
|
654 | -a: makes the pattern match even objects whose names start with a | |
655 | single underscore. These names are normally ommitted from the |
|
655 | single underscore. These names are normally ommitted from the | |
656 | search. |
|
656 | search. | |
657 |
|
657 | |||
658 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
658 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
659 | these options is given, the default is read from your ipythonrc |
|
659 | these options is given, the default is read from your ipythonrc | |
660 | file. The option name which sets this value is |
|
660 | file. The option name which sets this value is | |
661 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
661 | 'wildcards_case_sensitive'. If this option is not specified in your | |
662 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
662 | ipythonrc file, IPython's internal default is to do a case sensitive | |
663 | search. |
|
663 | search. | |
664 |
|
664 | |||
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
666 | specifiy can be searched in any of the following namespaces: |
|
666 | specifiy can be searched in any of the following namespaces: | |
667 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
667 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
668 | 'builtin' and 'user' are the search defaults. Note that you should |
|
668 | 'builtin' and 'user' are the search defaults. Note that you should | |
669 | not use quotes when specifying namespaces. |
|
669 | not use quotes when specifying namespaces. | |
670 |
|
670 | |||
671 | 'Builtin' contains the python module builtin, 'user' contains all |
|
671 | 'Builtin' contains the python module builtin, 'user' contains all | |
672 | user data, 'alias' only contain the shell aliases and no python |
|
672 | user data, 'alias' only contain the shell aliases and no python | |
673 | objects, 'internal' contains objects used by IPython. The |
|
673 | objects, 'internal' contains objects used by IPython. The | |
674 | 'user_global' namespace is only used by embedded IPython instances, |
|
674 | 'user_global' namespace is only used by embedded IPython instances, | |
675 | and it contains module-level globals. You can add namespaces to the |
|
675 | and it contains module-level globals. You can add namespaces to the | |
676 | search with -s or exclude them with -e (these options can be given |
|
676 | search with -s or exclude them with -e (these options can be given | |
677 | more than once). |
|
677 | more than once). | |
678 |
|
678 | |||
679 | Examples: |
|
679 | Examples: | |
680 |
|
680 | |||
681 | %psearch a* -> objects beginning with an a |
|
681 | %psearch a* -> objects beginning with an a | |
682 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
682 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
683 | %psearch a* function -> all functions beginning with an a |
|
683 | %psearch a* function -> all functions beginning with an a | |
684 | %psearch re.e* -> objects beginning with an e in module re |
|
684 | %psearch re.e* -> objects beginning with an e in module re | |
685 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
685 | %psearch r*.e* -> objects that start with e in modules starting in r | |
686 | %psearch r*.* string -> all strings in modules beginning with r |
|
686 | %psearch r*.* string -> all strings in modules beginning with r | |
687 |
|
687 | |||
688 | Case sensitve search: |
|
688 | Case sensitve search: | |
689 |
|
689 | |||
690 | %psearch -c a* list all object beginning with lower case a |
|
690 | %psearch -c a* list all object beginning with lower case a | |
691 |
|
691 | |||
692 | Show objects beginning with a single _: |
|
692 | Show objects beginning with a single _: | |
693 |
|
693 | |||
694 | %psearch -a _* list objects beginning with a single underscore""" |
|
694 | %psearch -a _* list objects beginning with a single underscore""" | |
695 | try: |
|
695 | try: | |
696 | parameter_s = parameter_s.encode('ascii') |
|
696 | parameter_s = parameter_s.encode('ascii') | |
697 | except UnicodeEncodeError: |
|
697 | except UnicodeEncodeError: | |
698 | print 'Python identifiers can only contain ascii characters.' |
|
698 | print 'Python identifiers can only contain ascii characters.' | |
699 | return |
|
699 | return | |
700 |
|
700 | |||
701 | # default namespaces to be searched |
|
701 | # default namespaces to be searched | |
702 | def_search = ['user','builtin'] |
|
702 | def_search = ['user','builtin'] | |
703 |
|
703 | |||
704 | # Process options/args |
|
704 | # Process options/args | |
705 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
705 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
706 | opt = opts.get |
|
706 | opt = opts.get | |
707 | shell = self.shell |
|
707 | shell = self.shell | |
708 | psearch = shell.inspector.psearch |
|
708 | psearch = shell.inspector.psearch | |
709 |
|
709 | |||
710 | # select case options |
|
710 | # select case options | |
711 | if opts.has_key('i'): |
|
711 | if opts.has_key('i'): | |
712 | ignore_case = True |
|
712 | ignore_case = True | |
713 | elif opts.has_key('c'): |
|
713 | elif opts.has_key('c'): | |
714 | ignore_case = False |
|
714 | ignore_case = False | |
715 | else: |
|
715 | else: | |
716 | ignore_case = not shell.wildcards_case_sensitive |
|
716 | ignore_case = not shell.wildcards_case_sensitive | |
717 |
|
717 | |||
718 | # Build list of namespaces to search from user options |
|
718 | # Build list of namespaces to search from user options | |
719 | def_search.extend(opt('s',[])) |
|
719 | def_search.extend(opt('s',[])) | |
720 | ns_exclude = ns_exclude=opt('e',[]) |
|
720 | ns_exclude = ns_exclude=opt('e',[]) | |
721 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
721 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
722 |
|
722 | |||
723 | # Call the actual search |
|
723 | # Call the actual search | |
724 | try: |
|
724 | try: | |
725 | psearch(args,shell.ns_table,ns_search, |
|
725 | psearch(args,shell.ns_table,ns_search, | |
726 | show_all=opt('a'),ignore_case=ignore_case) |
|
726 | show_all=opt('a'),ignore_case=ignore_case) | |
727 | except: |
|
727 | except: | |
728 | shell.showtraceback() |
|
728 | shell.showtraceback() | |
729 |
|
729 | |||
730 | def magic_who_ls(self, parameter_s=''): |
|
730 | def magic_who_ls(self, parameter_s=''): | |
731 | """Return a sorted list of all interactive variables. |
|
731 | """Return a sorted list of all interactive variables. | |
732 |
|
732 | |||
733 | If arguments are given, only variables of types matching these |
|
733 | If arguments are given, only variables of types matching these | |
734 | arguments are returned.""" |
|
734 | arguments are returned.""" | |
735 |
|
735 | |||
736 | user_ns = self.shell.user_ns |
|
736 | user_ns = self.shell.user_ns | |
737 | internal_ns = self.shell.internal_ns |
|
737 | internal_ns = self.shell.internal_ns | |
738 | user_ns_hidden = self.shell.user_ns_hidden |
|
738 | user_ns_hidden = self.shell.user_ns_hidden | |
739 | out = [ i for i in user_ns |
|
739 | out = [ i for i in user_ns | |
740 | if not i.startswith('_') \ |
|
740 | if not i.startswith('_') \ | |
741 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
741 | and not (i in internal_ns or i in user_ns_hidden) ] | |
742 |
|
742 | |||
743 | typelist = parameter_s.split() |
|
743 | typelist = parameter_s.split() | |
744 | if typelist: |
|
744 | if typelist: | |
745 | typeset = set(typelist) |
|
745 | typeset = set(typelist) | |
746 | out = [i for i in out if type(i).__name__ in typeset] |
|
746 | out = [i for i in out if type(i).__name__ in typeset] | |
747 |
|
747 | |||
748 | out.sort() |
|
748 | out.sort() | |
749 | return out |
|
749 | return out | |
750 |
|
750 | |||
751 | def magic_who(self, parameter_s=''): |
|
751 | def magic_who(self, parameter_s=''): | |
752 | """Print all interactive variables, with some minimal formatting. |
|
752 | """Print all interactive variables, with some minimal formatting. | |
753 |
|
753 | |||
754 | If any arguments are given, only variables whose type matches one of |
|
754 | If any arguments are given, only variables whose type matches one of | |
755 | these are printed. For example: |
|
755 | these are printed. For example: | |
756 |
|
756 | |||
757 | %who function str |
|
757 | %who function str | |
758 |
|
758 | |||
759 | will only list functions and strings, excluding all other types of |
|
759 | will only list functions and strings, excluding all other types of | |
760 | variables. To find the proper type names, simply use type(var) at a |
|
760 | variables. To find the proper type names, simply use type(var) at a | |
761 | command line to see how python prints type names. For example: |
|
761 | command line to see how python prints type names. For example: | |
762 |
|
762 | |||
763 | In [1]: type('hello')\\ |
|
763 | In [1]: type('hello')\\ | |
764 | Out[1]: <type 'str'> |
|
764 | Out[1]: <type 'str'> | |
765 |
|
765 | |||
766 | indicates that the type name for strings is 'str'. |
|
766 | indicates that the type name for strings is 'str'. | |
767 |
|
767 | |||
768 | %who always excludes executed names loaded through your configuration |
|
768 | %who always excludes executed names loaded through your configuration | |
769 | file and things which are internal to IPython. |
|
769 | file and things which are internal to IPython. | |
770 |
|
770 | |||
771 | This is deliberate, as typically you may load many modules and the |
|
771 | This is deliberate, as typically you may load many modules and the | |
772 | purpose of %who is to show you only what you've manually defined.""" |
|
772 | purpose of %who is to show you only what you've manually defined.""" | |
773 |
|
773 | |||
774 | varlist = self.magic_who_ls(parameter_s) |
|
774 | varlist = self.magic_who_ls(parameter_s) | |
775 | if not varlist: |
|
775 | if not varlist: | |
776 | if parameter_s: |
|
776 | if parameter_s: | |
777 | print 'No variables match your requested type.' |
|
777 | print 'No variables match your requested type.' | |
778 | else: |
|
778 | else: | |
779 | print 'Interactive namespace is empty.' |
|
779 | print 'Interactive namespace is empty.' | |
780 | return |
|
780 | return | |
781 |
|
781 | |||
782 | # if we have variables, move on... |
|
782 | # if we have variables, move on... | |
783 | count = 0 |
|
783 | count = 0 | |
784 | for i in varlist: |
|
784 | for i in varlist: | |
785 | print i+'\t', |
|
785 | print i+'\t', | |
786 | count += 1 |
|
786 | count += 1 | |
787 | if count > 8: |
|
787 | if count > 8: | |
788 | count = 0 |
|
788 | count = 0 | |
789 |
|
789 | |||
790 |
|
790 | |||
791 |
|
791 | |||
792 | def magic_whos(self, parameter_s=''): |
|
792 | def magic_whos(self, parameter_s=''): | |
793 | """Like %who, but gives some extra information about each variable. |
|
793 | """Like %who, but gives some extra information about each variable. | |
794 |
|
794 | |||
795 | The same type filtering of %who can be applied here. |
|
795 | The same type filtering of %who can be applied here. | |
796 |
|
796 | |||
797 | For all variables, the type is printed. Additionally it prints: |
|
797 | For all variables, the type is printed. Additionally it prints: | |
798 |
|
798 | |||
799 | - For {},[],(): their length. |
|
799 | - For {},[],(): their length. | |
800 |
|
800 | |||
801 | - For numpy and Numeric arrays, a summary with shape, number of |
|
801 | - For numpy and Numeric arrays, a summary with shape, number of | |
802 | elements, typecode and size in memory. |
|
802 | elements, typecode and size in memory. | |
803 |
|
803 | |||
804 | - Everything else: a string representation, snipping their middle if |
|
804 | - Everything else: a string representation, snipping their middle if | |
805 | too long.""" |
|
805 | too long.""" | |
806 |
|
806 | |||
807 | varnames = self.magic_who_ls(parameter_s) |
|
807 | varnames = self.magic_who_ls(parameter_s) | |
808 | if not varnames: |
|
808 | if not varnames: | |
809 | if parameter_s: |
|
809 | if parameter_s: | |
810 | print 'No variables match your requested type.' |
|
810 | print 'No variables match your requested type.' | |
811 | else: |
|
811 | else: | |
812 | print 'Interactive namespace is empty.' |
|
812 | print 'Interactive namespace is empty.' | |
813 | return |
|
813 | return | |
814 |
|
814 | |||
815 | # if we have variables, move on... |
|
815 | # if we have variables, move on... | |
816 |
|
816 | |||
817 | # for these types, show len() instead of data: |
|
817 | # for these types, show len() instead of data: | |
818 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
818 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
819 |
|
819 | |||
820 | # for numpy/Numeric arrays, display summary info |
|
820 | # for numpy/Numeric arrays, display summary info | |
821 | try: |
|
821 | try: | |
822 | import numpy |
|
822 | import numpy | |
823 | except ImportError: |
|
823 | except ImportError: | |
824 | ndarray_type = None |
|
824 | ndarray_type = None | |
825 | else: |
|
825 | else: | |
826 | ndarray_type = numpy.ndarray.__name__ |
|
826 | ndarray_type = numpy.ndarray.__name__ | |
827 | try: |
|
827 | try: | |
828 | import Numeric |
|
828 | import Numeric | |
829 | except ImportError: |
|
829 | except ImportError: | |
830 | array_type = None |
|
830 | array_type = None | |
831 | else: |
|
831 | else: | |
832 | array_type = Numeric.ArrayType.__name__ |
|
832 | array_type = Numeric.ArrayType.__name__ | |
833 |
|
833 | |||
834 | # Find all variable names and types so we can figure out column sizes |
|
834 | # Find all variable names and types so we can figure out column sizes | |
835 | def get_vars(i): |
|
835 | def get_vars(i): | |
836 | return self.shell.user_ns[i] |
|
836 | return self.shell.user_ns[i] | |
837 |
|
837 | |||
838 | # some types are well known and can be shorter |
|
838 | # some types are well known and can be shorter | |
839 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
839 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
840 | def type_name(v): |
|
840 | def type_name(v): | |
841 | tn = type(v).__name__ |
|
841 | tn = type(v).__name__ | |
842 | return abbrevs.get(tn,tn) |
|
842 | return abbrevs.get(tn,tn) | |
843 |
|
843 | |||
844 | varlist = map(get_vars,varnames) |
|
844 | varlist = map(get_vars,varnames) | |
845 |
|
845 | |||
846 | typelist = [] |
|
846 | typelist = [] | |
847 | for vv in varlist: |
|
847 | for vv in varlist: | |
848 | tt = type_name(vv) |
|
848 | tt = type_name(vv) | |
849 |
|
849 | |||
850 | if tt=='instance': |
|
850 | if tt=='instance': | |
851 | typelist.append( abbrevs.get(str(vv.__class__), |
|
851 | typelist.append( abbrevs.get(str(vv.__class__), | |
852 | str(vv.__class__))) |
|
852 | str(vv.__class__))) | |
853 | else: |
|
853 | else: | |
854 | typelist.append(tt) |
|
854 | typelist.append(tt) | |
855 |
|
855 | |||
856 | # column labels and # of spaces as separator |
|
856 | # column labels and # of spaces as separator | |
857 | varlabel = 'Variable' |
|
857 | varlabel = 'Variable' | |
858 | typelabel = 'Type' |
|
858 | typelabel = 'Type' | |
859 | datalabel = 'Data/Info' |
|
859 | datalabel = 'Data/Info' | |
860 | colsep = 3 |
|
860 | colsep = 3 | |
861 | # variable format strings |
|
861 | # variable format strings | |
862 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
862 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
863 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
863 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
864 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
864 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
865 | # find the size of the columns to format the output nicely |
|
865 | # find the size of the columns to format the output nicely | |
866 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
866 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
867 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
867 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
868 | # table header |
|
868 | # table header | |
869 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
869 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
870 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
870 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
871 | # and the table itself |
|
871 | # and the table itself | |
872 | kb = 1024 |
|
872 | kb = 1024 | |
873 | Mb = 1048576 # kb**2 |
|
873 | Mb = 1048576 # kb**2 | |
874 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
874 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
875 | print itpl(vformat), |
|
875 | print itpl(vformat), | |
876 | if vtype in seq_types: |
|
876 | if vtype in seq_types: | |
877 | print len(var) |
|
877 | print len(var) | |
878 | elif vtype in [array_type,ndarray_type]: |
|
878 | elif vtype in [array_type,ndarray_type]: | |
879 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
879 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
880 | if vtype==ndarray_type: |
|
880 | if vtype==ndarray_type: | |
881 | # numpy |
|
881 | # numpy | |
882 | vsize = var.size |
|
882 | vsize = var.size | |
883 | vbytes = vsize*var.itemsize |
|
883 | vbytes = vsize*var.itemsize | |
884 | vdtype = var.dtype |
|
884 | vdtype = var.dtype | |
885 | else: |
|
885 | else: | |
886 | # Numeric |
|
886 | # Numeric | |
887 | vsize = Numeric.size(var) |
|
887 | vsize = Numeric.size(var) | |
888 | vbytes = vsize*var.itemsize() |
|
888 | vbytes = vsize*var.itemsize() | |
889 | vdtype = var.typecode() |
|
889 | vdtype = var.typecode() | |
890 |
|
890 | |||
891 | if vbytes < 100000: |
|
891 | if vbytes < 100000: | |
892 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
892 | print aformat % (vshape,vsize,vdtype,vbytes) | |
893 | else: |
|
893 | else: | |
894 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
894 | print aformat % (vshape,vsize,vdtype,vbytes), | |
895 | if vbytes < Mb: |
|
895 | if vbytes < Mb: | |
896 | print '(%s kb)' % (vbytes/kb,) |
|
896 | print '(%s kb)' % (vbytes/kb,) | |
897 | else: |
|
897 | else: | |
898 | print '(%s Mb)' % (vbytes/Mb,) |
|
898 | print '(%s Mb)' % (vbytes/Mb,) | |
899 | else: |
|
899 | else: | |
900 | try: |
|
900 | try: | |
901 | vstr = str(var) |
|
901 | vstr = str(var) | |
902 | except UnicodeEncodeError: |
|
902 | except UnicodeEncodeError: | |
903 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
903 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
904 | 'backslashreplace') |
|
904 | 'backslashreplace') | |
905 | vstr = vstr.replace('\n','\\n') |
|
905 | vstr = vstr.replace('\n','\\n') | |
906 | if len(vstr) < 50: |
|
906 | if len(vstr) < 50: | |
907 | print vstr |
|
907 | print vstr | |
908 | else: |
|
908 | else: | |
909 | printpl(vfmt_short) |
|
909 | printpl(vfmt_short) | |
910 |
|
910 | |||
911 | def magic_reset(self, parameter_s=''): |
|
911 | def magic_reset(self, parameter_s=''): | |
912 | """Resets the namespace by removing all names defined by the user. |
|
912 | """Resets the namespace by removing all names defined by the user. | |
913 |
|
913 | |||
914 | Input/Output history are left around in case you need them. |
|
914 | Input/Output history are left around in case you need them. | |
915 |
|
915 | |||
916 | Parameters |
|
916 | Parameters | |
917 | ---------- |
|
917 | ---------- | |
918 | -y : force reset without asking for confirmation. |
|
918 | -y : force reset without asking for confirmation. | |
919 |
|
919 | |||
920 | Examples |
|
920 | Examples | |
921 | -------- |
|
921 | -------- | |
922 | In [6]: a = 1 |
|
922 | In [6]: a = 1 | |
923 |
|
923 | |||
924 | In [7]: a |
|
924 | In [7]: a | |
925 | Out[7]: 1 |
|
925 | Out[7]: 1 | |
926 |
|
926 | |||
927 | In [8]: 'a' in _ip.user_ns |
|
927 | In [8]: 'a' in _ip.user_ns | |
928 | Out[8]: True |
|
928 | Out[8]: True | |
929 |
|
929 | |||
930 | In [9]: %reset -f |
|
930 | In [9]: %reset -f | |
931 |
|
931 | |||
932 | In [10]: 'a' in _ip.user_ns |
|
932 | In [10]: 'a' in _ip.user_ns | |
933 | Out[10]: False |
|
933 | Out[10]: False | |
934 | """ |
|
934 | """ | |
935 |
|
935 | |||
936 | if parameter_s == '-f': |
|
936 | if parameter_s == '-f': | |
937 | ans = True |
|
937 | ans = True | |
938 | else: |
|
938 | else: | |
939 | ans = self.shell.ask_yes_no( |
|
939 | ans = self.shell.ask_yes_no( | |
940 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
940 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
941 | if not ans: |
|
941 | if not ans: | |
942 | print 'Nothing done.' |
|
942 | print 'Nothing done.' | |
943 | return |
|
943 | return | |
944 | user_ns = self.shell.user_ns |
|
944 | user_ns = self.shell.user_ns | |
945 | for i in self.magic_who_ls(): |
|
945 | for i in self.magic_who_ls(): | |
946 | del(user_ns[i]) |
|
946 | del(user_ns[i]) | |
947 |
|
947 | |||
948 | # Also flush the private list of module references kept for script |
|
948 | # Also flush the private list of module references kept for script | |
949 | # execution protection |
|
949 | # execution protection | |
950 | self.shell.clear_main_mod_cache() |
|
950 | self.shell.clear_main_mod_cache() | |
951 |
|
951 | |||
952 | def magic_reset_selective(self, parameter_s=''): |
|
952 | def magic_reset_selective(self, parameter_s=''): | |
953 | """Resets the namespace by removing names defined by the user. |
|
953 | """Resets the namespace by removing names defined by the user. | |
954 |
|
954 | |||
955 | Input/Output history are left around in case you need them. |
|
955 | Input/Output history are left around in case you need them. | |
956 |
|
956 | |||
957 | %reset_selective [-f] regex |
|
957 | %reset_selective [-f] regex | |
958 |
|
958 | |||
959 | No action is taken if regex is not included |
|
959 | No action is taken if regex is not included | |
960 |
|
960 | |||
961 | Options |
|
961 | Options | |
962 | -f : force reset without asking for confirmation. |
|
962 | -f : force reset without asking for confirmation. | |
963 |
|
963 | |||
964 | Examples |
|
964 | Examples | |
965 | -------- |
|
965 | -------- | |
966 |
|
966 | |||
967 | We first fully reset the namespace so your output looks identical to |
|
967 | We first fully reset the namespace so your output looks identical to | |
968 | this example for pedagogical reasons; in practice you do not need a |
|
968 | this example for pedagogical reasons; in practice you do not need a | |
969 | full reset. |
|
969 | full reset. | |
970 |
|
970 | |||
971 | In [1]: %reset -f |
|
971 | In [1]: %reset -f | |
972 |
|
972 | |||
973 | Now, with a clean namespace we can make a few variables and use |
|
973 | Now, with a clean namespace we can make a few variables and use | |
974 | %reset_selective to only delete names that match our regexp: |
|
974 | %reset_selective to only delete names that match our regexp: | |
975 |
|
975 | |||
976 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
976 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
977 |
|
977 | |||
978 | In [3]: who_ls |
|
978 | In [3]: who_ls | |
979 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
979 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
980 |
|
980 | |||
981 | In [4]: %reset_selective -f b[2-3]m |
|
981 | In [4]: %reset_selective -f b[2-3]m | |
982 |
|
982 | |||
983 | In [5]: who_ls |
|
983 | In [5]: who_ls | |
984 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
984 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
985 |
|
985 | |||
986 | In [6]: %reset_selective -f d |
|
986 | In [6]: %reset_selective -f d | |
987 |
|
987 | |||
988 | In [7]: who_ls |
|
988 | In [7]: who_ls | |
989 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
989 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
990 |
|
990 | |||
991 | In [8]: %reset_selective -f c |
|
991 | In [8]: %reset_selective -f c | |
992 |
|
992 | |||
993 | In [9]: who_ls |
|
993 | In [9]: who_ls | |
994 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
994 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
995 |
|
995 | |||
996 | In [10]: %reset_selective -f b |
|
996 | In [10]: %reset_selective -f b | |
997 |
|
997 | |||
998 | In [11]: who_ls |
|
998 | In [11]: who_ls | |
999 | Out[11]: ['a'] |
|
999 | Out[11]: ['a'] | |
1000 | """ |
|
1000 | """ | |
1001 |
|
1001 | |||
1002 | opts, regex = self.parse_options(parameter_s,'f') |
|
1002 | opts, regex = self.parse_options(parameter_s,'f') | |
1003 |
|
1003 | |||
1004 | if opts.has_key('f'): |
|
1004 | if opts.has_key('f'): | |
1005 | ans = True |
|
1005 | ans = True | |
1006 | else: |
|
1006 | else: | |
1007 | ans = self.shell.ask_yes_no( |
|
1007 | ans = self.shell.ask_yes_no( | |
1008 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1008 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1009 | if not ans: |
|
1009 | if not ans: | |
1010 | print 'Nothing done.' |
|
1010 | print 'Nothing done.' | |
1011 | return |
|
1011 | return | |
1012 | user_ns = self.shell.user_ns |
|
1012 | user_ns = self.shell.user_ns | |
1013 | if not regex: |
|
1013 | if not regex: | |
1014 | print 'No regex pattern specified. Nothing done.' |
|
1014 | print 'No regex pattern specified. Nothing done.' | |
1015 | return |
|
1015 | return | |
1016 | else: |
|
1016 | else: | |
1017 | try: |
|
1017 | try: | |
1018 | m = re.compile(regex) |
|
1018 | m = re.compile(regex) | |
1019 | except TypeError: |
|
1019 | except TypeError: | |
1020 | raise TypeError('regex must be a string or compiled pattern') |
|
1020 | raise TypeError('regex must be a string or compiled pattern') | |
1021 | for i in self.magic_who_ls(): |
|
1021 | for i in self.magic_who_ls(): | |
1022 | if m.search(i): |
|
1022 | if m.search(i): | |
1023 | del(user_ns[i]) |
|
1023 | del(user_ns[i]) | |
1024 |
|
1024 | |||
1025 | def magic_logstart(self,parameter_s=''): |
|
1025 | def magic_logstart(self,parameter_s=''): | |
1026 | """Start logging anywhere in a session. |
|
1026 | """Start logging anywhere in a session. | |
1027 |
|
1027 | |||
1028 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1028 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1029 |
|
1029 | |||
1030 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1030 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1031 | current directory, in 'rotate' mode (see below). |
|
1031 | current directory, in 'rotate' mode (see below). | |
1032 |
|
1032 | |||
1033 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1033 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1034 | history up to that point and then continues logging. |
|
1034 | history up to that point and then continues logging. | |
1035 |
|
1035 | |||
1036 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1036 | %logstart takes a second optional parameter: logging mode. This can be one | |
1037 | of (note that the modes are given unquoted):\\ |
|
1037 | of (note that the modes are given unquoted):\\ | |
1038 | append: well, that says it.\\ |
|
1038 | append: well, that says it.\\ | |
1039 | backup: rename (if exists) to name~ and start name.\\ |
|
1039 | backup: rename (if exists) to name~ and start name.\\ | |
1040 | global: single logfile in your home dir, appended to.\\ |
|
1040 | global: single logfile in your home dir, appended to.\\ | |
1041 | over : overwrite existing log.\\ |
|
1041 | over : overwrite existing log.\\ | |
1042 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1042 | rotate: create rotating logs name.1~, name.2~, etc. | |
1043 |
|
1043 | |||
1044 | Options: |
|
1044 | Options: | |
1045 |
|
1045 | |||
1046 | -o: log also IPython's output. In this mode, all commands which |
|
1046 | -o: log also IPython's output. In this mode, all commands which | |
1047 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1047 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1048 | their corresponding input line. The output lines are always |
|
1048 | their corresponding input line. The output lines are always | |
1049 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1049 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1050 | Python code. |
|
1050 | Python code. | |
1051 |
|
1051 | |||
1052 | Since this marker is always the same, filtering only the output from |
|
1052 | Since this marker is always the same, filtering only the output from | |
1053 | a log is very easy, using for example a simple awk call: |
|
1053 | a log is very easy, using for example a simple awk call: | |
1054 |
|
1054 | |||
1055 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1055 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1056 |
|
1056 | |||
1057 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1057 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1058 | input, so that user lines are logged in their final form, converted |
|
1058 | input, so that user lines are logged in their final form, converted | |
1059 | into valid Python. For example, %Exit is logged as |
|
1059 | into valid Python. For example, %Exit is logged as | |
1060 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1060 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1061 | exactly as typed, with no transformations applied. |
|
1061 | exactly as typed, with no transformations applied. | |
1062 |
|
1062 | |||
1063 | -t: put timestamps before each input line logged (these are put in |
|
1063 | -t: put timestamps before each input line logged (these are put in | |
1064 | comments).""" |
|
1064 | comments).""" | |
1065 |
|
1065 | |||
1066 | opts,par = self.parse_options(parameter_s,'ort') |
|
1066 | opts,par = self.parse_options(parameter_s,'ort') | |
1067 | log_output = 'o' in opts |
|
1067 | log_output = 'o' in opts | |
1068 | log_raw_input = 'r' in opts |
|
1068 | log_raw_input = 'r' in opts | |
1069 | timestamp = 't' in opts |
|
1069 | timestamp = 't' in opts | |
1070 |
|
1070 | |||
1071 | logger = self.shell.logger |
|
1071 | logger = self.shell.logger | |
1072 |
|
1072 | |||
1073 | # if no args are given, the defaults set in the logger constructor by |
|
1073 | # if no args are given, the defaults set in the logger constructor by | |
1074 | # ipytohn remain valid |
|
1074 | # ipytohn remain valid | |
1075 | if par: |
|
1075 | if par: | |
1076 | try: |
|
1076 | try: | |
1077 | logfname,logmode = par.split() |
|
1077 | logfname,logmode = par.split() | |
1078 | except: |
|
1078 | except: | |
1079 | logfname = par |
|
1079 | logfname = par | |
1080 | logmode = 'backup' |
|
1080 | logmode = 'backup' | |
1081 | else: |
|
1081 | else: | |
1082 | logfname = logger.logfname |
|
1082 | logfname = logger.logfname | |
1083 | logmode = logger.logmode |
|
1083 | logmode = logger.logmode | |
1084 | # put logfname into rc struct as if it had been called on the command |
|
1084 | # put logfname into rc struct as if it had been called on the command | |
1085 | # line, so it ends up saved in the log header Save it in case we need |
|
1085 | # line, so it ends up saved in the log header Save it in case we need | |
1086 | # to restore it... |
|
1086 | # to restore it... | |
1087 | old_logfile = self.shell.logfile |
|
1087 | old_logfile = self.shell.logfile | |
1088 | if logfname: |
|
1088 | if logfname: | |
1089 | logfname = os.path.expanduser(logfname) |
|
1089 | logfname = os.path.expanduser(logfname) | |
1090 | self.shell.logfile = logfname |
|
1090 | self.shell.logfile = logfname | |
1091 |
|
1091 | |||
1092 | loghead = '# IPython log file\n\n' |
|
1092 | loghead = '# IPython log file\n\n' | |
1093 | try: |
|
1093 | try: | |
1094 | started = logger.logstart(logfname,loghead,logmode, |
|
1094 | started = logger.logstart(logfname,loghead,logmode, | |
1095 | log_output,timestamp,log_raw_input) |
|
1095 | log_output,timestamp,log_raw_input) | |
1096 | except: |
|
1096 | except: | |
1097 | self.shell.logfile = old_logfile |
|
1097 | self.shell.logfile = old_logfile | |
1098 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1098 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1099 | else: |
|
1099 | else: | |
1100 | # log input history up to this point, optionally interleaving |
|
1100 | # log input history up to this point, optionally interleaving | |
1101 | # output if requested |
|
1101 | # output if requested | |
1102 |
|
1102 | |||
1103 | if timestamp: |
|
1103 | if timestamp: | |
1104 | # disable timestamping for the previous history, since we've |
|
1104 | # disable timestamping for the previous history, since we've | |
1105 | # lost those already (no time machine here). |
|
1105 | # lost those already (no time machine here). | |
1106 | logger.timestamp = False |
|
1106 | logger.timestamp = False | |
1107 |
|
1107 | |||
1108 | if log_raw_input: |
|
1108 | if log_raw_input: | |
1109 | input_hist = self.shell.history_manager.input_hist_raw |
|
1109 | input_hist = self.shell.history_manager.input_hist_raw | |
1110 | else: |
|
1110 | else: | |
1111 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1111 | input_hist = self.shell.history_manager.input_hist_parsed | |
1112 |
|
1112 | |||
1113 | if log_output: |
|
1113 | if log_output: | |
1114 | log_write = logger.log_write |
|
1114 | log_write = logger.log_write | |
1115 | output_hist = self.shell.history_manager.output_hist |
|
1115 | output_hist = self.shell.history_manager.output_hist | |
1116 | for n in range(1,len(input_hist)-1): |
|
1116 | for n in range(1,len(input_hist)-1): | |
1117 | log_write(input_hist[n].rstrip()) |
|
1117 | log_write(input_hist[n].rstrip()) | |
1118 | if n in output_hist: |
|
1118 | if n in output_hist: | |
1119 | log_write(repr(output_hist[n]),'output') |
|
1119 | log_write(repr(output_hist[n]),'output') | |
1120 | else: |
|
1120 | else: | |
1121 | logger.log_write(''.join(input_hist[1:])) |
|
1121 | logger.log_write(''.join(input_hist[1:])) | |
1122 | if timestamp: |
|
1122 | if timestamp: | |
1123 | # re-enable timestamping |
|
1123 | # re-enable timestamping | |
1124 | logger.timestamp = True |
|
1124 | logger.timestamp = True | |
1125 |
|
1125 | |||
1126 | print ('Activating auto-logging. ' |
|
1126 | print ('Activating auto-logging. ' | |
1127 | 'Current session state plus future input saved.') |
|
1127 | 'Current session state plus future input saved.') | |
1128 | logger.logstate() |
|
1128 | logger.logstate() | |
1129 |
|
1129 | |||
1130 | def magic_logstop(self,parameter_s=''): |
|
1130 | def magic_logstop(self,parameter_s=''): | |
1131 | """Fully stop logging and close log file. |
|
1131 | """Fully stop logging and close log file. | |
1132 |
|
1132 | |||
1133 | In order to start logging again, a new %logstart call needs to be made, |
|
1133 | In order to start logging again, a new %logstart call needs to be made, | |
1134 | possibly (though not necessarily) with a new filename, mode and other |
|
1134 | possibly (though not necessarily) with a new filename, mode and other | |
1135 | options.""" |
|
1135 | options.""" | |
1136 | self.logger.logstop() |
|
1136 | self.logger.logstop() | |
1137 |
|
1137 | |||
1138 | def magic_logoff(self,parameter_s=''): |
|
1138 | def magic_logoff(self,parameter_s=''): | |
1139 | """Temporarily stop logging. |
|
1139 | """Temporarily stop logging. | |
1140 |
|
1140 | |||
1141 | You must have previously started logging.""" |
|
1141 | You must have previously started logging.""" | |
1142 | self.shell.logger.switch_log(0) |
|
1142 | self.shell.logger.switch_log(0) | |
1143 |
|
1143 | |||
1144 | def magic_logon(self,parameter_s=''): |
|
1144 | def magic_logon(self,parameter_s=''): | |
1145 | """Restart logging. |
|
1145 | """Restart logging. | |
1146 |
|
1146 | |||
1147 | This function is for restarting logging which you've temporarily |
|
1147 | This function is for restarting logging which you've temporarily | |
1148 | stopped with %logoff. For starting logging for the first time, you |
|
1148 | stopped with %logoff. For starting logging for the first time, you | |
1149 | must use the %logstart function, which allows you to specify an |
|
1149 | must use the %logstart function, which allows you to specify an | |
1150 | optional log filename.""" |
|
1150 | optional log filename.""" | |
1151 |
|
1151 | |||
1152 | self.shell.logger.switch_log(1) |
|
1152 | self.shell.logger.switch_log(1) | |
1153 |
|
1153 | |||
1154 | def magic_logstate(self,parameter_s=''): |
|
1154 | def magic_logstate(self,parameter_s=''): | |
1155 | """Print the status of the logging system.""" |
|
1155 | """Print the status of the logging system.""" | |
1156 |
|
1156 | |||
1157 | self.shell.logger.logstate() |
|
1157 | self.shell.logger.logstate() | |
1158 |
|
1158 | |||
1159 | def magic_pdb(self, parameter_s=''): |
|
1159 | def magic_pdb(self, parameter_s=''): | |
1160 | """Control the automatic calling of the pdb interactive debugger. |
|
1160 | """Control the automatic calling of the pdb interactive debugger. | |
1161 |
|
1161 | |||
1162 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1162 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1163 | argument it works as a toggle. |
|
1163 | argument it works as a toggle. | |
1164 |
|
1164 | |||
1165 | When an exception is triggered, IPython can optionally call the |
|
1165 | When an exception is triggered, IPython can optionally call the | |
1166 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1166 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1167 | this feature on and off. |
|
1167 | this feature on and off. | |
1168 |
|
1168 | |||
1169 | The initial state of this feature is set in your ipythonrc |
|
1169 | The initial state of this feature is set in your ipythonrc | |
1170 | configuration file (the variable is called 'pdb'). |
|
1170 | configuration file (the variable is called 'pdb'). | |
1171 |
|
1171 | |||
1172 | If you want to just activate the debugger AFTER an exception has fired, |
|
1172 | If you want to just activate the debugger AFTER an exception has fired, | |
1173 | without having to type '%pdb on' and rerunning your code, you can use |
|
1173 | without having to type '%pdb on' and rerunning your code, you can use | |
1174 | the %debug magic.""" |
|
1174 | the %debug magic.""" | |
1175 |
|
1175 | |||
1176 | par = parameter_s.strip().lower() |
|
1176 | par = parameter_s.strip().lower() | |
1177 |
|
1177 | |||
1178 | if par: |
|
1178 | if par: | |
1179 | try: |
|
1179 | try: | |
1180 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1180 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1181 | except KeyError: |
|
1181 | except KeyError: | |
1182 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1182 | print ('Incorrect argument. Use on/1, off/0, ' | |
1183 | 'or nothing for a toggle.') |
|
1183 | 'or nothing for a toggle.') | |
1184 | return |
|
1184 | return | |
1185 | else: |
|
1185 | else: | |
1186 | # toggle |
|
1186 | # toggle | |
1187 | new_pdb = not self.shell.call_pdb |
|
1187 | new_pdb = not self.shell.call_pdb | |
1188 |
|
1188 | |||
1189 | # set on the shell |
|
1189 | # set on the shell | |
1190 | self.shell.call_pdb = new_pdb |
|
1190 | self.shell.call_pdb = new_pdb | |
1191 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1191 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1192 |
|
1192 | |||
1193 | def magic_debug(self, parameter_s=''): |
|
1193 | def magic_debug(self, parameter_s=''): | |
1194 | """Activate the interactive debugger in post-mortem mode. |
|
1194 | """Activate the interactive debugger in post-mortem mode. | |
1195 |
|
1195 | |||
1196 | If an exception has just occurred, this lets you inspect its stack |
|
1196 | If an exception has just occurred, this lets you inspect its stack | |
1197 | frames interactively. Note that this will always work only on the last |
|
1197 | frames interactively. Note that this will always work only on the last | |
1198 | traceback that occurred, so you must call this quickly after an |
|
1198 | traceback that occurred, so you must call this quickly after an | |
1199 | exception that you wish to inspect has fired, because if another one |
|
1199 | exception that you wish to inspect has fired, because if another one | |
1200 | occurs, it clobbers the previous one. |
|
1200 | occurs, it clobbers the previous one. | |
1201 |
|
1201 | |||
1202 | If you want IPython to automatically do this on every exception, see |
|
1202 | If you want IPython to automatically do this on every exception, see | |
1203 | the %pdb magic for more details. |
|
1203 | the %pdb magic for more details. | |
1204 | """ |
|
1204 | """ | |
1205 | self.shell.debugger(force=True) |
|
1205 | self.shell.debugger(force=True) | |
1206 |
|
1206 | |||
1207 | @testdec.skip_doctest |
|
1207 | @testdec.skip_doctest | |
1208 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1208 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1209 | opts=None,arg_lst=None,prog_ns=None): |
|
1209 | opts=None,arg_lst=None,prog_ns=None): | |
1210 |
|
1210 | |||
1211 | """Run a statement through the python code profiler. |
|
1211 | """Run a statement through the python code profiler. | |
1212 |
|
1212 | |||
1213 | Usage: |
|
1213 | Usage: | |
1214 | %prun [options] statement |
|
1214 | %prun [options] statement | |
1215 |
|
1215 | |||
1216 | The given statement (which doesn't require quote marks) is run via the |
|
1216 | The given statement (which doesn't require quote marks) is run via the | |
1217 | python profiler in a manner similar to the profile.run() function. |
|
1217 | python profiler in a manner similar to the profile.run() function. | |
1218 | Namespaces are internally managed to work correctly; profile.run |
|
1218 | Namespaces are internally managed to work correctly; profile.run | |
1219 | cannot be used in IPython because it makes certain assumptions about |
|
1219 | cannot be used in IPython because it makes certain assumptions about | |
1220 | namespaces which do not hold under IPython. |
|
1220 | namespaces which do not hold under IPython. | |
1221 |
|
1221 | |||
1222 | Options: |
|
1222 | Options: | |
1223 |
|
1223 | |||
1224 | -l <limit>: you can place restrictions on what or how much of the |
|
1224 | -l <limit>: you can place restrictions on what or how much of the | |
1225 | profile gets printed. The limit value can be: |
|
1225 | profile gets printed. The limit value can be: | |
1226 |
|
1226 | |||
1227 | * A string: only information for function names containing this string |
|
1227 | * A string: only information for function names containing this string | |
1228 | is printed. |
|
1228 | is printed. | |
1229 |
|
1229 | |||
1230 | * An integer: only these many lines are printed. |
|
1230 | * An integer: only these many lines are printed. | |
1231 |
|
1231 | |||
1232 | * A float (between 0 and 1): this fraction of the report is printed |
|
1232 | * A float (between 0 and 1): this fraction of the report is printed | |
1233 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1233 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1234 |
|
1234 | |||
1235 | You can combine several limits with repeated use of the option. For |
|
1235 | You can combine several limits with repeated use of the option. For | |
1236 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1236 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1237 | information about class constructors. |
|
1237 | information about class constructors. | |
1238 |
|
1238 | |||
1239 | -r: return the pstats.Stats object generated by the profiling. This |
|
1239 | -r: return the pstats.Stats object generated by the profiling. This | |
1240 | object has all the information about the profile in it, and you can |
|
1240 | object has all the information about the profile in it, and you can | |
1241 | later use it for further analysis or in other functions. |
|
1241 | later use it for further analysis or in other functions. | |
1242 |
|
1242 | |||
1243 | -s <key>: sort profile by given key. You can provide more than one key |
|
1243 | -s <key>: sort profile by given key. You can provide more than one key | |
1244 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1244 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1245 | default sorting key is 'time'. |
|
1245 | default sorting key is 'time'. | |
1246 |
|
1246 | |||
1247 | The following is copied verbatim from the profile documentation |
|
1247 | The following is copied verbatim from the profile documentation | |
1248 | referenced below: |
|
1248 | referenced below: | |
1249 |
|
1249 | |||
1250 | When more than one key is provided, additional keys are used as |
|
1250 | When more than one key is provided, additional keys are used as | |
1251 | secondary criteria when the there is equality in all keys selected |
|
1251 | secondary criteria when the there is equality in all keys selected | |
1252 | before them. |
|
1252 | before them. | |
1253 |
|
1253 | |||
1254 | Abbreviations can be used for any key names, as long as the |
|
1254 | Abbreviations can be used for any key names, as long as the | |
1255 | abbreviation is unambiguous. The following are the keys currently |
|
1255 | abbreviation is unambiguous. The following are the keys currently | |
1256 | defined: |
|
1256 | defined: | |
1257 |
|
1257 | |||
1258 | Valid Arg Meaning |
|
1258 | Valid Arg Meaning | |
1259 | "calls" call count |
|
1259 | "calls" call count | |
1260 | "cumulative" cumulative time |
|
1260 | "cumulative" cumulative time | |
1261 | "file" file name |
|
1261 | "file" file name | |
1262 | "module" file name |
|
1262 | "module" file name | |
1263 | "pcalls" primitive call count |
|
1263 | "pcalls" primitive call count | |
1264 | "line" line number |
|
1264 | "line" line number | |
1265 | "name" function name |
|
1265 | "name" function name | |
1266 | "nfl" name/file/line |
|
1266 | "nfl" name/file/line | |
1267 | "stdname" standard name |
|
1267 | "stdname" standard name | |
1268 | "time" internal time |
|
1268 | "time" internal time | |
1269 |
|
1269 | |||
1270 | Note that all sorts on statistics are in descending order (placing |
|
1270 | Note that all sorts on statistics are in descending order (placing | |
1271 | most time consuming items first), where as name, file, and line number |
|
1271 | most time consuming items first), where as name, file, and line number | |
1272 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1272 | searches are in ascending order (i.e., alphabetical). The subtle | |
1273 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1273 | distinction between "nfl" and "stdname" is that the standard name is a | |
1274 | sort of the name as printed, which means that the embedded line |
|
1274 | sort of the name as printed, which means that the embedded line | |
1275 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1275 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1276 | would (if the file names were the same) appear in the string order |
|
1276 | would (if the file names were the same) appear in the string order | |
1277 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1277 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1278 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1278 | line numbers. In fact, sort_stats("nfl") is the same as | |
1279 | sort_stats("name", "file", "line"). |
|
1279 | sort_stats("name", "file", "line"). | |
1280 |
|
1280 | |||
1281 | -T <filename>: save profile results as shown on screen to a text |
|
1281 | -T <filename>: save profile results as shown on screen to a text | |
1282 | file. The profile is still shown on screen. |
|
1282 | file. The profile is still shown on screen. | |
1283 |
|
1283 | |||
1284 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1284 | -D <filename>: save (via dump_stats) profile statistics to given | |
1285 | filename. This data is in a format understod by the pstats module, and |
|
1285 | filename. This data is in a format understod by the pstats module, and | |
1286 | is generated by a call to the dump_stats() method of profile |
|
1286 | is generated by a call to the dump_stats() method of profile | |
1287 | objects. The profile is still shown on screen. |
|
1287 | objects. The profile is still shown on screen. | |
1288 |
|
1288 | |||
1289 | If you want to run complete programs under the profiler's control, use |
|
1289 | If you want to run complete programs under the profiler's control, use | |
1290 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1290 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1291 | contains profiler specific options as described here. |
|
1291 | contains profiler specific options as described here. | |
1292 |
|
1292 | |||
1293 | You can read the complete documentation for the profile module with:: |
|
1293 | You can read the complete documentation for the profile module with:: | |
1294 |
|
1294 | |||
1295 | In [1]: import profile; profile.help() |
|
1295 | In [1]: import profile; profile.help() | |
1296 | """ |
|
1296 | """ | |
1297 |
|
1297 | |||
1298 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1298 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1299 | # protect user quote marks |
|
1299 | # protect user quote marks | |
1300 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1300 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1301 |
|
1301 | |||
1302 | if user_mode: # regular user call |
|
1302 | if user_mode: # regular user call | |
1303 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1303 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1304 | list_all=1) |
|
1304 | list_all=1) | |
1305 | namespace = self.shell.user_ns |
|
1305 | namespace = self.shell.user_ns | |
1306 | else: # called to run a program by %run -p |
|
1306 | else: # called to run a program by %run -p | |
1307 | try: |
|
1307 | try: | |
1308 | filename = get_py_filename(arg_lst[0]) |
|
1308 | filename = get_py_filename(arg_lst[0]) | |
1309 | except IOError,msg: |
|
1309 | except IOError,msg: | |
1310 | error(msg) |
|
1310 | error(msg) | |
1311 | return |
|
1311 | return | |
1312 |
|
1312 | |||
1313 | arg_str = 'execfile(filename,prog_ns)' |
|
1313 | arg_str = 'execfile(filename,prog_ns)' | |
1314 | namespace = locals() |
|
1314 | namespace = locals() | |
1315 |
|
1315 | |||
1316 | opts.merge(opts_def) |
|
1316 | opts.merge(opts_def) | |
1317 |
|
1317 | |||
1318 | prof = profile.Profile() |
|
1318 | prof = profile.Profile() | |
1319 | try: |
|
1319 | try: | |
1320 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1320 | prof = prof.runctx(arg_str,namespace,namespace) | |
1321 | sys_exit = '' |
|
1321 | sys_exit = '' | |
1322 | except SystemExit: |
|
1322 | except SystemExit: | |
1323 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1323 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1324 |
|
1324 | |||
1325 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1325 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1326 |
|
1326 | |||
1327 | lims = opts.l |
|
1327 | lims = opts.l | |
1328 | if lims: |
|
1328 | if lims: | |
1329 | lims = [] # rebuild lims with ints/floats/strings |
|
1329 | lims = [] # rebuild lims with ints/floats/strings | |
1330 | for lim in opts.l: |
|
1330 | for lim in opts.l: | |
1331 | try: |
|
1331 | try: | |
1332 | lims.append(int(lim)) |
|
1332 | lims.append(int(lim)) | |
1333 | except ValueError: |
|
1333 | except ValueError: | |
1334 | try: |
|
1334 | try: | |
1335 | lims.append(float(lim)) |
|
1335 | lims.append(float(lim)) | |
1336 | except ValueError: |
|
1336 | except ValueError: | |
1337 | lims.append(lim) |
|
1337 | lims.append(lim) | |
1338 |
|
1338 | |||
1339 | # Trap output. |
|
1339 | # Trap output. | |
1340 | stdout_trap = StringIO() |
|
1340 | stdout_trap = StringIO() | |
1341 |
|
1341 | |||
1342 | if hasattr(stats,'stream'): |
|
1342 | if hasattr(stats,'stream'): | |
1343 | # In newer versions of python, the stats object has a 'stream' |
|
1343 | # In newer versions of python, the stats object has a 'stream' | |
1344 | # attribute to write into. |
|
1344 | # attribute to write into. | |
1345 | stats.stream = stdout_trap |
|
1345 | stats.stream = stdout_trap | |
1346 | stats.print_stats(*lims) |
|
1346 | stats.print_stats(*lims) | |
1347 | else: |
|
1347 | else: | |
1348 | # For older versions, we manually redirect stdout during printing |
|
1348 | # For older versions, we manually redirect stdout during printing | |
1349 | sys_stdout = sys.stdout |
|
1349 | sys_stdout = sys.stdout | |
1350 | try: |
|
1350 | try: | |
1351 | sys.stdout = stdout_trap |
|
1351 | sys.stdout = stdout_trap | |
1352 | stats.print_stats(*lims) |
|
1352 | stats.print_stats(*lims) | |
1353 | finally: |
|
1353 | finally: | |
1354 | sys.stdout = sys_stdout |
|
1354 | sys.stdout = sys_stdout | |
1355 |
|
1355 | |||
1356 | output = stdout_trap.getvalue() |
|
1356 | output = stdout_trap.getvalue() | |
1357 | output = output.rstrip() |
|
1357 | output = output.rstrip() | |
1358 |
|
1358 | |||
1359 | page.page(output) |
|
1359 | page.page(output) | |
1360 | print sys_exit, |
|
1360 | print sys_exit, | |
1361 |
|
1361 | |||
1362 | dump_file = opts.D[0] |
|
1362 | dump_file = opts.D[0] | |
1363 | text_file = opts.T[0] |
|
1363 | text_file = opts.T[0] | |
1364 | if dump_file: |
|
1364 | if dump_file: | |
1365 | prof.dump_stats(dump_file) |
|
1365 | prof.dump_stats(dump_file) | |
1366 | print '\n*** Profile stats marshalled to file',\ |
|
1366 | print '\n*** Profile stats marshalled to file',\ | |
1367 | `dump_file`+'.',sys_exit |
|
1367 | `dump_file`+'.',sys_exit | |
1368 | if text_file: |
|
1368 | if text_file: | |
1369 | pfile = file(text_file,'w') |
|
1369 | pfile = file(text_file,'w') | |
1370 | pfile.write(output) |
|
1370 | pfile.write(output) | |
1371 | pfile.close() |
|
1371 | pfile.close() | |
1372 | print '\n*** Profile printout saved to text file',\ |
|
1372 | print '\n*** Profile printout saved to text file',\ | |
1373 | `text_file`+'.',sys_exit |
|
1373 | `text_file`+'.',sys_exit | |
1374 |
|
1374 | |||
1375 | if opts.has_key('r'): |
|
1375 | if opts.has_key('r'): | |
1376 | return stats |
|
1376 | return stats | |
1377 | else: |
|
1377 | else: | |
1378 | return None |
|
1378 | return None | |
1379 |
|
1379 | |||
1380 | @testdec.skip_doctest |
|
1380 | @testdec.skip_doctest | |
1381 | def magic_run(self, parameter_s ='',runner=None, |
|
1381 | def magic_run(self, parameter_s ='',runner=None, | |
1382 | file_finder=get_py_filename): |
|
1382 | file_finder=get_py_filename): | |
1383 | """Run the named file inside IPython as a program. |
|
1383 | """Run the named file inside IPython as a program. | |
1384 |
|
1384 | |||
1385 | Usage:\\ |
|
1385 | Usage:\\ | |
1386 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1386 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1387 |
|
1387 | |||
1388 | Parameters after the filename are passed as command-line arguments to |
|
1388 | Parameters after the filename are passed as command-line arguments to | |
1389 | the program (put in sys.argv). Then, control returns to IPython's |
|
1389 | the program (put in sys.argv). Then, control returns to IPython's | |
1390 | prompt. |
|
1390 | prompt. | |
1391 |
|
1391 | |||
1392 | This is similar to running at a system prompt:\\ |
|
1392 | This is similar to running at a system prompt:\\ | |
1393 | $ python file args\\ |
|
1393 | $ python file args\\ | |
1394 | but with the advantage of giving you IPython's tracebacks, and of |
|
1394 | but with the advantage of giving you IPython's tracebacks, and of | |
1395 | loading all variables into your interactive namespace for further use |
|
1395 | loading all variables into your interactive namespace for further use | |
1396 | (unless -p is used, see below). |
|
1396 | (unless -p is used, see below). | |
1397 |
|
1397 | |||
1398 | The file is executed in a namespace initially consisting only of |
|
1398 | The file is executed in a namespace initially consisting only of | |
1399 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1399 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1400 | sees its environment as if it were being run as a stand-alone program |
|
1400 | sees its environment as if it were being run as a stand-alone program | |
1401 | (except for sharing global objects such as previously imported |
|
1401 | (except for sharing global objects such as previously imported | |
1402 | modules). But after execution, the IPython interactive namespace gets |
|
1402 | modules). But after execution, the IPython interactive namespace gets | |
1403 | updated with all variables defined in the program (except for __name__ |
|
1403 | updated with all variables defined in the program (except for __name__ | |
1404 | and sys.argv). This allows for very convenient loading of code for |
|
1404 | and sys.argv). This allows for very convenient loading of code for | |
1405 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1405 | interactive work, while giving each program a 'clean sheet' to run in. | |
1406 |
|
1406 | |||
1407 | Options: |
|
1407 | Options: | |
1408 |
|
1408 | |||
1409 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1409 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1410 | without extension (as python does under import). This allows running |
|
1410 | without extension (as python does under import). This allows running | |
1411 | scripts and reloading the definitions in them without calling code |
|
1411 | scripts and reloading the definitions in them without calling code | |
1412 | protected by an ' if __name__ == "__main__" ' clause. |
|
1412 | protected by an ' if __name__ == "__main__" ' clause. | |
1413 |
|
1413 | |||
1414 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1414 | -i: run the file in IPython's namespace instead of an empty one. This | |
1415 | is useful if you are experimenting with code written in a text editor |
|
1415 | is useful if you are experimenting with code written in a text editor | |
1416 | which depends on variables defined interactively. |
|
1416 | which depends on variables defined interactively. | |
1417 |
|
1417 | |||
1418 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1418 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1419 | being run. This is particularly useful if IPython is being used to |
|
1419 | being run. This is particularly useful if IPython is being used to | |
1420 | run unittests, which always exit with a sys.exit() call. In such |
|
1420 | run unittests, which always exit with a sys.exit() call. In such | |
1421 | cases you are interested in the output of the test results, not in |
|
1421 | cases you are interested in the output of the test results, not in | |
1422 | seeing a traceback of the unittest module. |
|
1422 | seeing a traceback of the unittest module. | |
1423 |
|
1423 | |||
1424 | -t: print timing information at the end of the run. IPython will give |
|
1424 | -t: print timing information at the end of the run. IPython will give | |
1425 | you an estimated CPU time consumption for your script, which under |
|
1425 | you an estimated CPU time consumption for your script, which under | |
1426 | Unix uses the resource module to avoid the wraparound problems of |
|
1426 | Unix uses the resource module to avoid the wraparound problems of | |
1427 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1427 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1428 | is also given (for Windows platforms this is reported as 0.0). |
|
1428 | is also given (for Windows platforms this is reported as 0.0). | |
1429 |
|
1429 | |||
1430 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1430 | If -t is given, an additional -N<N> option can be given, where <N> | |
1431 | must be an integer indicating how many times you want the script to |
|
1431 | must be an integer indicating how many times you want the script to | |
1432 | run. The final timing report will include total and per run results. |
|
1432 | run. The final timing report will include total and per run results. | |
1433 |
|
1433 | |||
1434 | For example (testing the script uniq_stable.py): |
|
1434 | For example (testing the script uniq_stable.py): | |
1435 |
|
1435 | |||
1436 | In [1]: run -t uniq_stable |
|
1436 | In [1]: run -t uniq_stable | |
1437 |
|
1437 | |||
1438 | IPython CPU timings (estimated):\\ |
|
1438 | IPython CPU timings (estimated):\\ | |
1439 | User : 0.19597 s.\\ |
|
1439 | User : 0.19597 s.\\ | |
1440 | System: 0.0 s.\\ |
|
1440 | System: 0.0 s.\\ | |
1441 |
|
1441 | |||
1442 | In [2]: run -t -N5 uniq_stable |
|
1442 | In [2]: run -t -N5 uniq_stable | |
1443 |
|
1443 | |||
1444 | IPython CPU timings (estimated):\\ |
|
1444 | IPython CPU timings (estimated):\\ | |
1445 | Total runs performed: 5\\ |
|
1445 | Total runs performed: 5\\ | |
1446 | Times : Total Per run\\ |
|
1446 | Times : Total Per run\\ | |
1447 | User : 0.910862 s, 0.1821724 s.\\ |
|
1447 | User : 0.910862 s, 0.1821724 s.\\ | |
1448 | System: 0.0 s, 0.0 s. |
|
1448 | System: 0.0 s, 0.0 s. | |
1449 |
|
1449 | |||
1450 | -d: run your program under the control of pdb, the Python debugger. |
|
1450 | -d: run your program under the control of pdb, the Python debugger. | |
1451 | This allows you to execute your program step by step, watch variables, |
|
1451 | This allows you to execute your program step by step, watch variables, | |
1452 | etc. Internally, what IPython does is similar to calling: |
|
1452 | etc. Internally, what IPython does is similar to calling: | |
1453 |
|
1453 | |||
1454 | pdb.run('execfile("YOURFILENAME")') |
|
1454 | pdb.run('execfile("YOURFILENAME")') | |
1455 |
|
1455 | |||
1456 | with a breakpoint set on line 1 of your file. You can change the line |
|
1456 | with a breakpoint set on line 1 of your file. You can change the line | |
1457 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1457 | number for this automatic breakpoint to be <N> by using the -bN option | |
1458 | (where N must be an integer). For example: |
|
1458 | (where N must be an integer). For example: | |
1459 |
|
1459 | |||
1460 | %run -d -b40 myscript |
|
1460 | %run -d -b40 myscript | |
1461 |
|
1461 | |||
1462 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1462 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1463 | the first breakpoint must be set on a line which actually does |
|
1463 | the first breakpoint must be set on a line which actually does | |
1464 | something (not a comment or docstring) for it to stop execution. |
|
1464 | something (not a comment or docstring) for it to stop execution. | |
1465 |
|
1465 | |||
1466 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1466 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1467 | first enter 'c' (without qoutes) to start execution up to the first |
|
1467 | first enter 'c' (without qoutes) to start execution up to the first | |
1468 | breakpoint. |
|
1468 | breakpoint. | |
1469 |
|
1469 | |||
1470 | Entering 'help' gives information about the use of the debugger. You |
|
1470 | Entering 'help' gives information about the use of the debugger. You | |
1471 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1471 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1472 | at a prompt. |
|
1472 | at a prompt. | |
1473 |
|
1473 | |||
1474 | -p: run program under the control of the Python profiler module (which |
|
1474 | -p: run program under the control of the Python profiler module (which | |
1475 | prints a detailed report of execution times, function calls, etc). |
|
1475 | prints a detailed report of execution times, function calls, etc). | |
1476 |
|
1476 | |||
1477 | You can pass other options after -p which affect the behavior of the |
|
1477 | You can pass other options after -p which affect the behavior of the | |
1478 | profiler itself. See the docs for %prun for details. |
|
1478 | profiler itself. See the docs for %prun for details. | |
1479 |
|
1479 | |||
1480 | In this mode, the program's variables do NOT propagate back to the |
|
1480 | In this mode, the program's variables do NOT propagate back to the | |
1481 | IPython interactive namespace (because they remain in the namespace |
|
1481 | IPython interactive namespace (because they remain in the namespace | |
1482 | where the profiler executes them). |
|
1482 | where the profiler executes them). | |
1483 |
|
1483 | |||
1484 | Internally this triggers a call to %prun, see its documentation for |
|
1484 | Internally this triggers a call to %prun, see its documentation for | |
1485 | details on the options available specifically for profiling. |
|
1485 | details on the options available specifically for profiling. | |
1486 |
|
1486 | |||
1487 | There is one special usage for which the text above doesn't apply: |
|
1487 | There is one special usage for which the text above doesn't apply: | |
1488 | if the filename ends with .ipy, the file is run as ipython script, |
|
1488 | if the filename ends with .ipy, the file is run as ipython script, | |
1489 | just as if the commands were written on IPython prompt. |
|
1489 | just as if the commands were written on IPython prompt. | |
1490 | """ |
|
1490 | """ | |
1491 |
|
1491 | |||
1492 | # get arguments and set sys.argv for program to be run. |
|
1492 | # get arguments and set sys.argv for program to be run. | |
1493 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1493 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1494 | mode='list',list_all=1) |
|
1494 | mode='list',list_all=1) | |
1495 |
|
1495 | |||
1496 | try: |
|
1496 | try: | |
1497 | filename = file_finder(arg_lst[0]) |
|
1497 | filename = file_finder(arg_lst[0]) | |
1498 | except IndexError: |
|
1498 | except IndexError: | |
1499 | warn('you must provide at least a filename.') |
|
1499 | warn('you must provide at least a filename.') | |
1500 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1500 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1501 | return |
|
1501 | return | |
1502 | except IOError,msg: |
|
1502 | except IOError,msg: | |
1503 | error(msg) |
|
1503 | error(msg) | |
1504 | return |
|
1504 | return | |
1505 |
|
1505 | |||
1506 | if filename.lower().endswith('.ipy'): |
|
1506 | if filename.lower().endswith('.ipy'): | |
1507 | self.shell.safe_execfile_ipy(filename) |
|
1507 | self.shell.safe_execfile_ipy(filename) | |
1508 | return |
|
1508 | return | |
1509 |
|
1509 | |||
1510 | # Control the response to exit() calls made by the script being run |
|
1510 | # Control the response to exit() calls made by the script being run | |
1511 | exit_ignore = opts.has_key('e') |
|
1511 | exit_ignore = opts.has_key('e') | |
1512 |
|
1512 | |||
1513 | # Make sure that the running script gets a proper sys.argv as if it |
|
1513 | # Make sure that the running script gets a proper sys.argv as if it | |
1514 | # were run from a system shell. |
|
1514 | # were run from a system shell. | |
1515 | save_argv = sys.argv # save it for later restoring |
|
1515 | save_argv = sys.argv # save it for later restoring | |
1516 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1516 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1517 |
|
1517 | |||
1518 | if opts.has_key('i'): |
|
1518 | if opts.has_key('i'): | |
1519 | # Run in user's interactive namespace |
|
1519 | # Run in user's interactive namespace | |
1520 | prog_ns = self.shell.user_ns |
|
1520 | prog_ns = self.shell.user_ns | |
1521 | __name__save = self.shell.user_ns['__name__'] |
|
1521 | __name__save = self.shell.user_ns['__name__'] | |
1522 | prog_ns['__name__'] = '__main__' |
|
1522 | prog_ns['__name__'] = '__main__' | |
1523 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1523 | main_mod = self.shell.new_main_mod(prog_ns) | |
1524 | else: |
|
1524 | else: | |
1525 | # Run in a fresh, empty namespace |
|
1525 | # Run in a fresh, empty namespace | |
1526 | if opts.has_key('n'): |
|
1526 | if opts.has_key('n'): | |
1527 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1527 | name = os.path.splitext(os.path.basename(filename))[0] | |
1528 | else: |
|
1528 | else: | |
1529 | name = '__main__' |
|
1529 | name = '__main__' | |
1530 |
|
1530 | |||
1531 | main_mod = self.shell.new_main_mod() |
|
1531 | main_mod = self.shell.new_main_mod() | |
1532 | prog_ns = main_mod.__dict__ |
|
1532 | prog_ns = main_mod.__dict__ | |
1533 | prog_ns['__name__'] = name |
|
1533 | prog_ns['__name__'] = name | |
1534 |
|
1534 | |||
1535 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1535 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1536 | # set the __file__ global in the script's namespace |
|
1536 | # set the __file__ global in the script's namespace | |
1537 | prog_ns['__file__'] = filename |
|
1537 | prog_ns['__file__'] = filename | |
1538 |
|
1538 | |||
1539 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1539 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1540 | # that, if we overwrite __main__, we replace it at the end |
|
1540 | # that, if we overwrite __main__, we replace it at the end | |
1541 | main_mod_name = prog_ns['__name__'] |
|
1541 | main_mod_name = prog_ns['__name__'] | |
1542 |
|
1542 | |||
1543 | if main_mod_name == '__main__': |
|
1543 | if main_mod_name == '__main__': | |
1544 | restore_main = sys.modules['__main__'] |
|
1544 | restore_main = sys.modules['__main__'] | |
1545 | else: |
|
1545 | else: | |
1546 | restore_main = False |
|
1546 | restore_main = False | |
1547 |
|
1547 | |||
1548 | # This needs to be undone at the end to prevent holding references to |
|
1548 | # This needs to be undone at the end to prevent holding references to | |
1549 | # every single object ever created. |
|
1549 | # every single object ever created. | |
1550 | sys.modules[main_mod_name] = main_mod |
|
1550 | sys.modules[main_mod_name] = main_mod | |
1551 |
|
1551 | |||
1552 | stats = None |
|
1552 | stats = None | |
1553 | try: |
|
1553 | try: | |
1554 | self.shell.save_history() |
|
1554 | self.shell.save_history() | |
1555 |
|
1555 | |||
1556 | if opts.has_key('p'): |
|
1556 | if opts.has_key('p'): | |
1557 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1557 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1558 | else: |
|
1558 | else: | |
1559 | if opts.has_key('d'): |
|
1559 | if opts.has_key('d'): | |
1560 | deb = debugger.Pdb(self.shell.colors) |
|
1560 | deb = debugger.Pdb(self.shell.colors) | |
1561 | # reset Breakpoint state, which is moronically kept |
|
1561 | # reset Breakpoint state, which is moronically kept | |
1562 | # in a class |
|
1562 | # in a class | |
1563 | bdb.Breakpoint.next = 1 |
|
1563 | bdb.Breakpoint.next = 1 | |
1564 | bdb.Breakpoint.bplist = {} |
|
1564 | bdb.Breakpoint.bplist = {} | |
1565 | bdb.Breakpoint.bpbynumber = [None] |
|
1565 | bdb.Breakpoint.bpbynumber = [None] | |
1566 | # Set an initial breakpoint to stop execution |
|
1566 | # Set an initial breakpoint to stop execution | |
1567 | maxtries = 10 |
|
1567 | maxtries = 10 | |
1568 | bp = int(opts.get('b',[1])[0]) |
|
1568 | bp = int(opts.get('b',[1])[0]) | |
1569 | checkline = deb.checkline(filename,bp) |
|
1569 | checkline = deb.checkline(filename,bp) | |
1570 | if not checkline: |
|
1570 | if not checkline: | |
1571 | for bp in range(bp+1,bp+maxtries+1): |
|
1571 | for bp in range(bp+1,bp+maxtries+1): | |
1572 | if deb.checkline(filename,bp): |
|
1572 | if deb.checkline(filename,bp): | |
1573 | break |
|
1573 | break | |
1574 | else: |
|
1574 | else: | |
1575 | msg = ("\nI failed to find a valid line to set " |
|
1575 | msg = ("\nI failed to find a valid line to set " | |
1576 | "a breakpoint\n" |
|
1576 | "a breakpoint\n" | |
1577 | "after trying up to line: %s.\n" |
|
1577 | "after trying up to line: %s.\n" | |
1578 | "Please set a valid breakpoint manually " |
|
1578 | "Please set a valid breakpoint manually " | |
1579 | "with the -b option." % bp) |
|
1579 | "with the -b option." % bp) | |
1580 | error(msg) |
|
1580 | error(msg) | |
1581 | return |
|
1581 | return | |
1582 | # if we find a good linenumber, set the breakpoint |
|
1582 | # if we find a good linenumber, set the breakpoint | |
1583 | deb.do_break('%s:%s' % (filename,bp)) |
|
1583 | deb.do_break('%s:%s' % (filename,bp)) | |
1584 | # Start file run |
|
1584 | # Start file run | |
1585 | print "NOTE: Enter 'c' at the", |
|
1585 | print "NOTE: Enter 'c' at the", | |
1586 | print "%s prompt to start your script." % deb.prompt |
|
1586 | print "%s prompt to start your script." % deb.prompt | |
1587 | try: |
|
1587 | try: | |
1588 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1588 | deb.run('execfile("%s")' % filename,prog_ns) | |
1589 |
|
1589 | |||
1590 | except: |
|
1590 | except: | |
1591 | etype, value, tb = sys.exc_info() |
|
1591 | etype, value, tb = sys.exc_info() | |
1592 | # Skip three frames in the traceback: the %run one, |
|
1592 | # Skip three frames in the traceback: the %run one, | |
1593 | # one inside bdb.py, and the command-line typed by the |
|
1593 | # one inside bdb.py, and the command-line typed by the | |
1594 | # user (run by exec in pdb itself). |
|
1594 | # user (run by exec in pdb itself). | |
1595 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1595 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1596 | else: |
|
1596 | else: | |
1597 | if runner is None: |
|
1597 | if runner is None: | |
1598 | runner = self.shell.safe_execfile |
|
1598 | runner = self.shell.safe_execfile | |
1599 | if opts.has_key('t'): |
|
1599 | if opts.has_key('t'): | |
1600 | # timed execution |
|
1600 | # timed execution | |
1601 | try: |
|
1601 | try: | |
1602 | nruns = int(opts['N'][0]) |
|
1602 | nruns = int(opts['N'][0]) | |
1603 | if nruns < 1: |
|
1603 | if nruns < 1: | |
1604 | error('Number of runs must be >=1') |
|
1604 | error('Number of runs must be >=1') | |
1605 | return |
|
1605 | return | |
1606 | except (KeyError): |
|
1606 | except (KeyError): | |
1607 | nruns = 1 |
|
1607 | nruns = 1 | |
1608 | if nruns == 1: |
|
1608 | if nruns == 1: | |
1609 | t0 = clock2() |
|
1609 | t0 = clock2() | |
1610 | runner(filename,prog_ns,prog_ns, |
|
1610 | runner(filename,prog_ns,prog_ns, | |
1611 | exit_ignore=exit_ignore) |
|
1611 | exit_ignore=exit_ignore) | |
1612 | t1 = clock2() |
|
1612 | t1 = clock2() | |
1613 | t_usr = t1[0]-t0[0] |
|
1613 | t_usr = t1[0]-t0[0] | |
1614 | t_sys = t1[1]-t0[1] |
|
1614 | t_sys = t1[1]-t0[1] | |
1615 | print "\nIPython CPU timings (estimated):" |
|
1615 | print "\nIPython CPU timings (estimated):" | |
1616 | print " User : %10s s." % t_usr |
|
1616 | print " User : %10s s." % t_usr | |
1617 | print " System: %10s s." % t_sys |
|
1617 | print " System: %10s s." % t_sys | |
1618 | else: |
|
1618 | else: | |
1619 | runs = range(nruns) |
|
1619 | runs = range(nruns) | |
1620 | t0 = clock2() |
|
1620 | t0 = clock2() | |
1621 | for nr in runs: |
|
1621 | for nr in runs: | |
1622 | runner(filename,prog_ns,prog_ns, |
|
1622 | runner(filename,prog_ns,prog_ns, | |
1623 | exit_ignore=exit_ignore) |
|
1623 | exit_ignore=exit_ignore) | |
1624 | t1 = clock2() |
|
1624 | t1 = clock2() | |
1625 | t_usr = t1[0]-t0[0] |
|
1625 | t_usr = t1[0]-t0[0] | |
1626 | t_sys = t1[1]-t0[1] |
|
1626 | t_sys = t1[1]-t0[1] | |
1627 | print "\nIPython CPU timings (estimated):" |
|
1627 | print "\nIPython CPU timings (estimated):" | |
1628 | print "Total runs performed:",nruns |
|
1628 | print "Total runs performed:",nruns | |
1629 | print " Times : %10s %10s" % ('Total','Per run') |
|
1629 | print " Times : %10s %10s" % ('Total','Per run') | |
1630 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1630 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1631 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1631 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1632 |
|
1632 | |||
1633 | else: |
|
1633 | else: | |
1634 | # regular execution |
|
1634 | # regular execution | |
1635 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1635 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1636 |
|
1636 | |||
1637 | if opts.has_key('i'): |
|
1637 | if opts.has_key('i'): | |
1638 | self.shell.user_ns['__name__'] = __name__save |
|
1638 | self.shell.user_ns['__name__'] = __name__save | |
1639 | else: |
|
1639 | else: | |
1640 | # The shell MUST hold a reference to prog_ns so after %run |
|
1640 | # The shell MUST hold a reference to prog_ns so after %run | |
1641 | # exits, the python deletion mechanism doesn't zero it out |
|
1641 | # exits, the python deletion mechanism doesn't zero it out | |
1642 | # (leaving dangling references). |
|
1642 | # (leaving dangling references). | |
1643 | self.shell.cache_main_mod(prog_ns,filename) |
|
1643 | self.shell.cache_main_mod(prog_ns,filename) | |
1644 | # update IPython interactive namespace |
|
1644 | # update IPython interactive namespace | |
1645 |
|
1645 | |||
1646 | # Some forms of read errors on the file may mean the |
|
1646 | # Some forms of read errors on the file may mean the | |
1647 | # __name__ key was never set; using pop we don't have to |
|
1647 | # __name__ key was never set; using pop we don't have to | |
1648 | # worry about a possible KeyError. |
|
1648 | # worry about a possible KeyError. | |
1649 | prog_ns.pop('__name__', None) |
|
1649 | prog_ns.pop('__name__', None) | |
1650 |
|
1650 | |||
1651 | self.shell.user_ns.update(prog_ns) |
|
1651 | self.shell.user_ns.update(prog_ns) | |
1652 | finally: |
|
1652 | finally: | |
1653 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1653 | # It's a bit of a mystery why, but __builtins__ can change from | |
1654 | # being a module to becoming a dict missing some key data after |
|
1654 | # being a module to becoming a dict missing some key data after | |
1655 | # %run. As best I can see, this is NOT something IPython is doing |
|
1655 | # %run. As best I can see, this is NOT something IPython is doing | |
1656 | # at all, and similar problems have been reported before: |
|
1656 | # at all, and similar problems have been reported before: | |
1657 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1657 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1658 | # Since this seems to be done by the interpreter itself, the best |
|
1658 | # Since this seems to be done by the interpreter itself, the best | |
1659 | # we can do is to at least restore __builtins__ for the user on |
|
1659 | # we can do is to at least restore __builtins__ for the user on | |
1660 | # exit. |
|
1660 | # exit. | |
1661 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1661 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1662 |
|
1662 | |||
1663 | # Ensure key global structures are restored |
|
1663 | # Ensure key global structures are restored | |
1664 | sys.argv = save_argv |
|
1664 | sys.argv = save_argv | |
1665 | if restore_main: |
|
1665 | if restore_main: | |
1666 | sys.modules['__main__'] = restore_main |
|
1666 | sys.modules['__main__'] = restore_main | |
1667 | else: |
|
1667 | else: | |
1668 | # Remove from sys.modules the reference to main_mod we'd |
|
1668 | # Remove from sys.modules the reference to main_mod we'd | |
1669 | # added. Otherwise it will trap references to objects |
|
1669 | # added. Otherwise it will trap references to objects | |
1670 | # contained therein. |
|
1670 | # contained therein. | |
1671 | del sys.modules[main_mod_name] |
|
1671 | del sys.modules[main_mod_name] | |
1672 |
|
1672 | |||
1673 | self.shell.reload_history() |
|
1673 | self.shell.reload_history() | |
1674 |
|
1674 | |||
1675 | return stats |
|
1675 | return stats | |
1676 |
|
1676 | |||
1677 | @testdec.skip_doctest |
|
1677 | @testdec.skip_doctest | |
1678 | def magic_timeit(self, parameter_s =''): |
|
1678 | def magic_timeit(self, parameter_s =''): | |
1679 | """Time execution of a Python statement or expression |
|
1679 | """Time execution of a Python statement or expression | |
1680 |
|
1680 | |||
1681 | Usage:\\ |
|
1681 | Usage:\\ | |
1682 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1682 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1683 |
|
1683 | |||
1684 | Time execution of a Python statement or expression using the timeit |
|
1684 | Time execution of a Python statement or expression using the timeit | |
1685 | module. |
|
1685 | module. | |
1686 |
|
1686 | |||
1687 | Options: |
|
1687 | Options: | |
1688 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1688 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1689 | is not given, a fitting value is chosen. |
|
1689 | is not given, a fitting value is chosen. | |
1690 |
|
1690 | |||
1691 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1691 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1692 | Default: 3 |
|
1692 | Default: 3 | |
1693 |
|
1693 | |||
1694 | -t: use time.time to measure the time, which is the default on Unix. |
|
1694 | -t: use time.time to measure the time, which is the default on Unix. | |
1695 | This function measures wall time. |
|
1695 | This function measures wall time. | |
1696 |
|
1696 | |||
1697 | -c: use time.clock to measure the time, which is the default on |
|
1697 | -c: use time.clock to measure the time, which is the default on | |
1698 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1698 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1699 | instead and returns the CPU user time. |
|
1699 | instead and returns the CPU user time. | |
1700 |
|
1700 | |||
1701 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1701 | -p<P>: use a precision of <P> digits to display the timing result. | |
1702 | Default: 3 |
|
1702 | Default: 3 | |
1703 |
|
1703 | |||
1704 |
|
1704 | |||
1705 | Examples: |
|
1705 | Examples: | |
1706 |
|
1706 | |||
1707 | In [1]: %timeit pass |
|
1707 | In [1]: %timeit pass | |
1708 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1708 | 10000000 loops, best of 3: 53.3 ns per loop | |
1709 |
|
1709 | |||
1710 | In [2]: u = None |
|
1710 | In [2]: u = None | |
1711 |
|
1711 | |||
1712 | In [3]: %timeit u is None |
|
1712 | In [3]: %timeit u is None | |
1713 | 10000000 loops, best of 3: 184 ns per loop |
|
1713 | 10000000 loops, best of 3: 184 ns per loop | |
1714 |
|
1714 | |||
1715 | In [4]: %timeit -r 4 u == None |
|
1715 | In [4]: %timeit -r 4 u == None | |
1716 | 1000000 loops, best of 4: 242 ns per loop |
|
1716 | 1000000 loops, best of 4: 242 ns per loop | |
1717 |
|
1717 | |||
1718 | In [5]: import time |
|
1718 | In [5]: import time | |
1719 |
|
1719 | |||
1720 | In [6]: %timeit -n1 time.sleep(2) |
|
1720 | In [6]: %timeit -n1 time.sleep(2) | |
1721 | 1 loops, best of 3: 2 s per loop |
|
1721 | 1 loops, best of 3: 2 s per loop | |
1722 |
|
1722 | |||
1723 |
|
1723 | |||
1724 | The times reported by %timeit will be slightly higher than those |
|
1724 | The times reported by %timeit will be slightly higher than those | |
1725 | reported by the timeit.py script when variables are accessed. This is |
|
1725 | reported by the timeit.py script when variables are accessed. This is | |
1726 | due to the fact that %timeit executes the statement in the namespace |
|
1726 | due to the fact that %timeit executes the statement in the namespace | |
1727 | of the shell, compared with timeit.py, which uses a single setup |
|
1727 | of the shell, compared with timeit.py, which uses a single setup | |
1728 | statement to import function or create variables. Generally, the bias |
|
1728 | statement to import function or create variables. Generally, the bias | |
1729 | does not matter as long as results from timeit.py are not mixed with |
|
1729 | does not matter as long as results from timeit.py are not mixed with | |
1730 | those from %timeit.""" |
|
1730 | those from %timeit.""" | |
1731 |
|
1731 | |||
1732 | import timeit |
|
1732 | import timeit | |
1733 | import math |
|
1733 | import math | |
1734 |
|
1734 | |||
1735 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1735 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1736 | # certain terminals. Until we figure out a robust way of |
|
1736 | # certain terminals. Until we figure out a robust way of | |
1737 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1737 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1738 | # microseconds. I am really NOT happy about disabling the proper |
|
1738 | # microseconds. I am really NOT happy about disabling the proper | |
1739 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1739 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1740 | # right solution for this is, I'm all ears... |
|
1740 | # right solution for this is, I'm all ears... | |
1741 | # |
|
1741 | # | |
1742 | # Note: using |
|
1742 | # Note: using | |
1743 | # |
|
1743 | # | |
1744 | # s = u'\xb5' |
|
1744 | # s = u'\xb5' | |
1745 | # s.encode(sys.getdefaultencoding()) |
|
1745 | # s.encode(sys.getdefaultencoding()) | |
1746 | # |
|
1746 | # | |
1747 | # is not sufficient, as I've seen terminals where that fails but |
|
1747 | # is not sufficient, as I've seen terminals where that fails but | |
1748 | # print s |
|
1748 | # print s | |
1749 | # |
|
1749 | # | |
1750 | # succeeds |
|
1750 | # succeeds | |
1751 | # |
|
1751 | # | |
1752 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1752 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1753 |
|
1753 | |||
1754 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1754 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1755 | units = [u"s", u"ms",u'us',"ns"] |
|
1755 | units = [u"s", u"ms",u'us',"ns"] | |
1756 |
|
1756 | |||
1757 | scaling = [1, 1e3, 1e6, 1e9] |
|
1757 | scaling = [1, 1e3, 1e6, 1e9] | |
1758 |
|
1758 | |||
1759 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1759 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1760 | posix=False) |
|
1760 | posix=False) | |
1761 | if stmt == "": |
|
1761 | if stmt == "": | |
1762 | return |
|
1762 | return | |
1763 | timefunc = timeit.default_timer |
|
1763 | timefunc = timeit.default_timer | |
1764 | number = int(getattr(opts, "n", 0)) |
|
1764 | number = int(getattr(opts, "n", 0)) | |
1765 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1765 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1766 | precision = int(getattr(opts, "p", 3)) |
|
1766 | precision = int(getattr(opts, "p", 3)) | |
1767 | if hasattr(opts, "t"): |
|
1767 | if hasattr(opts, "t"): | |
1768 | timefunc = time.time |
|
1768 | timefunc = time.time | |
1769 | if hasattr(opts, "c"): |
|
1769 | if hasattr(opts, "c"): | |
1770 | timefunc = clock |
|
1770 | timefunc = clock | |
1771 |
|
1771 | |||
1772 | timer = timeit.Timer(timer=timefunc) |
|
1772 | timer = timeit.Timer(timer=timefunc) | |
1773 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1773 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1774 | # but is there a better way to achieve that the code stmt has access |
|
1774 | # but is there a better way to achieve that the code stmt has access | |
1775 | # to the shell namespace? |
|
1775 | # to the shell namespace? | |
1776 |
|
1776 | |||
1777 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1777 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1778 | 'setup': "pass"} |
|
1778 | 'setup': "pass"} | |
1779 | # Track compilation time so it can be reported if too long |
|
1779 | # Track compilation time so it can be reported if too long | |
1780 | # Minimum time above which compilation time will be reported |
|
1780 | # Minimum time above which compilation time will be reported | |
1781 | tc_min = 0.1 |
|
1781 | tc_min = 0.1 | |
1782 |
|
1782 | |||
1783 | t0 = clock() |
|
1783 | t0 = clock() | |
1784 | code = compile(src, "<magic-timeit>", "exec") |
|
1784 | code = compile(src, "<magic-timeit>", "exec") | |
1785 | tc = clock()-t0 |
|
1785 | tc = clock()-t0 | |
1786 |
|
1786 | |||
1787 | ns = {} |
|
1787 | ns = {} | |
1788 | exec code in self.shell.user_ns, ns |
|
1788 | exec code in self.shell.user_ns, ns | |
1789 | timer.inner = ns["inner"] |
|
1789 | timer.inner = ns["inner"] | |
1790 |
|
1790 | |||
1791 | if number == 0: |
|
1791 | if number == 0: | |
1792 | # determine number so that 0.2 <= total time < 2.0 |
|
1792 | # determine number so that 0.2 <= total time < 2.0 | |
1793 | number = 1 |
|
1793 | number = 1 | |
1794 | for i in range(1, 10): |
|
1794 | for i in range(1, 10): | |
1795 | if timer.timeit(number) >= 0.2: |
|
1795 | if timer.timeit(number) >= 0.2: | |
1796 | break |
|
1796 | break | |
1797 | number *= 10 |
|
1797 | number *= 10 | |
1798 |
|
1798 | |||
1799 | best = min(timer.repeat(repeat, number)) / number |
|
1799 | best = min(timer.repeat(repeat, number)) / number | |
1800 |
|
1800 | |||
1801 | if best > 0.0 and best < 1000.0: |
|
1801 | if best > 0.0 and best < 1000.0: | |
1802 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1802 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1803 | elif best >= 1000.0: |
|
1803 | elif best >= 1000.0: | |
1804 | order = 0 |
|
1804 | order = 0 | |
1805 | else: |
|
1805 | else: | |
1806 | order = 3 |
|
1806 | order = 3 | |
1807 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1807 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1808 | precision, |
|
1808 | precision, | |
1809 | best * scaling[order], |
|
1809 | best * scaling[order], | |
1810 | units[order]) |
|
1810 | units[order]) | |
1811 | if tc > tc_min: |
|
1811 | if tc > tc_min: | |
1812 | print "Compiler time: %.2f s" % tc |
|
1812 | print "Compiler time: %.2f s" % tc | |
1813 |
|
1813 | |||
1814 | @testdec.skip_doctest |
|
1814 | @testdec.skip_doctest | |
1815 | def magic_time(self,parameter_s = ''): |
|
1815 | def magic_time(self,parameter_s = ''): | |
1816 | """Time execution of a Python statement or expression. |
|
1816 | """Time execution of a Python statement or expression. | |
1817 |
|
1817 | |||
1818 | The CPU and wall clock times are printed, and the value of the |
|
1818 | The CPU and wall clock times are printed, and the value of the | |
1819 | expression (if any) is returned. Note that under Win32, system time |
|
1819 | expression (if any) is returned. Note that under Win32, system time | |
1820 | is always reported as 0, since it can not be measured. |
|
1820 | is always reported as 0, since it can not be measured. | |
1821 |
|
1821 | |||
1822 | This function provides very basic timing functionality. In Python |
|
1822 | This function provides very basic timing functionality. In Python | |
1823 | 2.3, the timeit module offers more control and sophistication, so this |
|
1823 | 2.3, the timeit module offers more control and sophistication, so this | |
1824 | could be rewritten to use it (patches welcome). |
|
1824 | could be rewritten to use it (patches welcome). | |
1825 |
|
1825 | |||
1826 | Some examples: |
|
1826 | Some examples: | |
1827 |
|
1827 | |||
1828 | In [1]: time 2**128 |
|
1828 | In [1]: time 2**128 | |
1829 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1829 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1830 | Wall time: 0.00 |
|
1830 | Wall time: 0.00 | |
1831 | Out[1]: 340282366920938463463374607431768211456L |
|
1831 | Out[1]: 340282366920938463463374607431768211456L | |
1832 |
|
1832 | |||
1833 | In [2]: n = 1000000 |
|
1833 | In [2]: n = 1000000 | |
1834 |
|
1834 | |||
1835 | In [3]: time sum(range(n)) |
|
1835 | In [3]: time sum(range(n)) | |
1836 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1836 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1837 | Wall time: 1.37 |
|
1837 | Wall time: 1.37 | |
1838 | Out[3]: 499999500000L |
|
1838 | Out[3]: 499999500000L | |
1839 |
|
1839 | |||
1840 | In [4]: time print 'hello world' |
|
1840 | In [4]: time print 'hello world' | |
1841 | hello world |
|
1841 | hello world | |
1842 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1842 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1843 | Wall time: 0.00 |
|
1843 | Wall time: 0.00 | |
1844 |
|
1844 | |||
1845 | Note that the time needed by Python to compile the given expression |
|
1845 | Note that the time needed by Python to compile the given expression | |
1846 | will be reported if it is more than 0.1s. In this example, the |
|
1846 | will be reported if it is more than 0.1s. In this example, the | |
1847 | actual exponentiation is done by Python at compilation time, so while |
|
1847 | actual exponentiation is done by Python at compilation time, so while | |
1848 | the expression can take a noticeable amount of time to compute, that |
|
1848 | the expression can take a noticeable amount of time to compute, that | |
1849 | time is purely due to the compilation: |
|
1849 | time is purely due to the compilation: | |
1850 |
|
1850 | |||
1851 | In [5]: time 3**9999; |
|
1851 | In [5]: time 3**9999; | |
1852 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1852 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1853 | Wall time: 0.00 s |
|
1853 | Wall time: 0.00 s | |
1854 |
|
1854 | |||
1855 | In [6]: time 3**999999; |
|
1855 | In [6]: time 3**999999; | |
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1857 | Wall time: 0.00 s |
|
1857 | Wall time: 0.00 s | |
1858 | Compiler : 0.78 s |
|
1858 | Compiler : 0.78 s | |
1859 | """ |
|
1859 | """ | |
1860 |
|
1860 | |||
1861 | # fail immediately if the given expression can't be compiled |
|
1861 | # fail immediately if the given expression can't be compiled | |
1862 |
|
1862 | |||
1863 | expr = self.shell.prefilter(parameter_s,False) |
|
1863 | expr = self.shell.prefilter(parameter_s,False) | |
1864 |
|
1864 | |||
1865 | # Minimum time above which compilation time will be reported |
|
1865 | # Minimum time above which compilation time will be reported | |
1866 | tc_min = 0.1 |
|
1866 | tc_min = 0.1 | |
1867 |
|
1867 | |||
1868 | try: |
|
1868 | try: | |
1869 | mode = 'eval' |
|
1869 | mode = 'eval' | |
1870 | t0 = clock() |
|
1870 | t0 = clock() | |
1871 | code = compile(expr,'<timed eval>',mode) |
|
1871 | code = compile(expr,'<timed eval>',mode) | |
1872 | tc = clock()-t0 |
|
1872 | tc = clock()-t0 | |
1873 | except SyntaxError: |
|
1873 | except SyntaxError: | |
1874 | mode = 'exec' |
|
1874 | mode = 'exec' | |
1875 | t0 = clock() |
|
1875 | t0 = clock() | |
1876 | code = compile(expr,'<timed exec>',mode) |
|
1876 | code = compile(expr,'<timed exec>',mode) | |
1877 | tc = clock()-t0 |
|
1877 | tc = clock()-t0 | |
1878 | # skew measurement as little as possible |
|
1878 | # skew measurement as little as possible | |
1879 | glob = self.shell.user_ns |
|
1879 | glob = self.shell.user_ns | |
1880 | clk = clock2 |
|
1880 | clk = clock2 | |
1881 | wtime = time.time |
|
1881 | wtime = time.time | |
1882 | # time execution |
|
1882 | # time execution | |
1883 | wall_st = wtime() |
|
1883 | wall_st = wtime() | |
1884 | if mode=='eval': |
|
1884 | if mode=='eval': | |
1885 | st = clk() |
|
1885 | st = clk() | |
1886 | out = eval(code,glob) |
|
1886 | out = eval(code,glob) | |
1887 | end = clk() |
|
1887 | end = clk() | |
1888 | else: |
|
1888 | else: | |
1889 | st = clk() |
|
1889 | st = clk() | |
1890 | exec code in glob |
|
1890 | exec code in glob | |
1891 | end = clk() |
|
1891 | end = clk() | |
1892 | out = None |
|
1892 | out = None | |
1893 | wall_end = wtime() |
|
1893 | wall_end = wtime() | |
1894 | # Compute actual times and report |
|
1894 | # Compute actual times and report | |
1895 | wall_time = wall_end-wall_st |
|
1895 | wall_time = wall_end-wall_st | |
1896 | cpu_user = end[0]-st[0] |
|
1896 | cpu_user = end[0]-st[0] | |
1897 | cpu_sys = end[1]-st[1] |
|
1897 | cpu_sys = end[1]-st[1] | |
1898 | cpu_tot = cpu_user+cpu_sys |
|
1898 | cpu_tot = cpu_user+cpu_sys | |
1899 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1899 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1900 | (cpu_user,cpu_sys,cpu_tot) |
|
1900 | (cpu_user,cpu_sys,cpu_tot) | |
1901 | print "Wall time: %.2f s" % wall_time |
|
1901 | print "Wall time: %.2f s" % wall_time | |
1902 | if tc > tc_min: |
|
1902 | if tc > tc_min: | |
1903 | print "Compiler : %.2f s" % tc |
|
1903 | print "Compiler : %.2f s" % tc | |
1904 | return out |
|
1904 | return out | |
1905 |
|
1905 | |||
1906 | @testdec.skip_doctest |
|
1906 | @testdec.skip_doctest | |
1907 | def magic_macro(self,parameter_s = ''): |
|
1907 | def magic_macro(self,parameter_s = ''): | |
1908 | """Define a set of input lines as a macro for future re-execution. |
|
1908 | """Define a set of input lines as a macro for future re-execution. | |
1909 |
|
1909 | |||
1910 | Usage:\\ |
|
1910 | Usage:\\ | |
1911 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1911 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1912 |
|
1912 | |||
1913 | Options: |
|
1913 | Options: | |
1914 |
|
1914 | |||
1915 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1915 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1916 | so that magics are loaded in their transformed version to valid |
|
1916 | so that magics are loaded in their transformed version to valid | |
1917 | Python. If this option is given, the raw input as typed as the |
|
1917 | Python. If this option is given, the raw input as typed as the | |
1918 | command line is used instead. |
|
1918 | command line is used instead. | |
1919 |
|
1919 | |||
1920 | This will define a global variable called `name` which is a string |
|
1920 | This will define a global variable called `name` which is a string | |
1921 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1921 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1922 | above) from your input history into a single string. This variable |
|
1922 | above) from your input history into a single string. This variable | |
1923 | acts like an automatic function which re-executes those lines as if |
|
1923 | acts like an automatic function which re-executes those lines as if | |
1924 | you had typed them. You just type 'name' at the prompt and the code |
|
1924 | you had typed them. You just type 'name' at the prompt and the code | |
1925 | executes. |
|
1925 | executes. | |
1926 |
|
1926 | |||
1927 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1927 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1928 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1928 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1929 | using the lines numbered 5,6 and 7. |
|
1929 | using the lines numbered 5,6 and 7. | |
1930 |
|
1930 | |||
1931 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1931 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1932 | notation, where N:M means numbers N through M-1. |
|
1932 | notation, where N:M means numbers N through M-1. | |
1933 |
|
1933 | |||
1934 | For example, if your history contains (%hist prints it): |
|
1934 | For example, if your history contains (%hist prints it): | |
1935 |
|
1935 | |||
1936 | 44: x=1 |
|
1936 | 44: x=1 | |
1937 | 45: y=3 |
|
1937 | 45: y=3 | |
1938 | 46: z=x+y |
|
1938 | 46: z=x+y | |
1939 | 47: print x |
|
1939 | 47: print x | |
1940 | 48: a=5 |
|
1940 | 48: a=5 | |
1941 | 49: print 'x',x,'y',y |
|
1941 | 49: print 'x',x,'y',y | |
1942 |
|
1942 | |||
1943 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1943 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1944 | called my_macro with: |
|
1944 | called my_macro with: | |
1945 |
|
1945 | |||
1946 | In [55]: %macro my_macro 44-47 49 |
|
1946 | In [55]: %macro my_macro 44-47 49 | |
1947 |
|
1947 | |||
1948 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1948 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1949 | in one pass. |
|
1949 | in one pass. | |
1950 |
|
1950 | |||
1951 | You don't need to give the line-numbers in order, and any given line |
|
1951 | You don't need to give the line-numbers in order, and any given line | |
1952 | number can appear multiple times. You can assemble macros with any |
|
1952 | number can appear multiple times. You can assemble macros with any | |
1953 | lines from your input history in any order. |
|
1953 | lines from your input history in any order. | |
1954 |
|
1954 | |||
1955 | The macro is a simple object which holds its value in an attribute, |
|
1955 | The macro is a simple object which holds its value in an attribute, | |
1956 | but IPython's display system checks for macros and executes them as |
|
1956 | but IPython's display system checks for macros and executes them as | |
1957 | code instead of printing them when you type their name. |
|
1957 | code instead of printing them when you type their name. | |
1958 |
|
1958 | |||
1959 | You can view a macro's contents by explicitly printing it with: |
|
1959 | You can view a macro's contents by explicitly printing it with: | |
1960 |
|
1960 | |||
1961 | 'print macro_name'. |
|
1961 | 'print macro_name'. | |
1962 |
|
1962 | |||
1963 | For one-off cases which DON'T contain magic function calls in them you |
|
1963 | For one-off cases which DON'T contain magic function calls in them you | |
1964 | can obtain similar results by explicitly executing slices from your |
|
1964 | can obtain similar results by explicitly executing slices from your | |
1965 | input history with: |
|
1965 | input history with: | |
1966 |
|
1966 | |||
1967 | In [60]: exec In[44:48]+In[49]""" |
|
1967 | In [60]: exec In[44:48]+In[49]""" | |
1968 |
|
1968 | |||
1969 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1969 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1970 | if not args: |
|
1970 | if not args: | |
1971 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1971 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1972 | macs.sort() |
|
1972 | macs.sort() | |
1973 | return macs |
|
1973 | return macs | |
1974 | if len(args) == 1: |
|
1974 | if len(args) == 1: | |
1975 | raise UsageError( |
|
1975 | raise UsageError( | |
1976 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1976 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1977 | name,ranges = args[0], args[1:] |
|
1977 | name,ranges = args[0], args[1:] | |
1978 |
|
1978 | |||
1979 | #print 'rng',ranges # dbg |
|
1979 | #print 'rng',ranges # dbg | |
1980 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1980 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1981 | macro = Macro(lines) |
|
1981 | macro = Macro(lines) | |
1982 | self.shell.define_macro(name, macro) |
|
1982 | self.shell.define_macro(name, macro) | |
1983 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1983 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1984 | print 'Macro contents:' |
|
1984 | print 'Macro contents:' | |
1985 | print macro, |
|
1985 | print macro, | |
1986 |
|
1986 | |||
1987 | def magic_save(self,parameter_s = ''): |
|
1987 | def magic_save(self,parameter_s = ''): | |
1988 | """Save a set of lines to a given filename. |
|
1988 | """Save a set of lines to a given filename. | |
1989 |
|
1989 | |||
1990 | Usage:\\ |
|
1990 | Usage:\\ | |
1991 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1991 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1992 |
|
1992 | |||
1993 | Options: |
|
1993 | Options: | |
1994 |
|
1994 | |||
1995 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1995 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1996 | so that magics are loaded in their transformed version to valid |
|
1996 | so that magics are loaded in their transformed version to valid | |
1997 | Python. If this option is given, the raw input as typed as the |
|
1997 | Python. If this option is given, the raw input as typed as the | |
1998 | command line is used instead. |
|
1998 | command line is used instead. | |
1999 |
|
1999 | |||
2000 | This function uses the same syntax as %macro for line extraction, but |
|
2000 | This function uses the same syntax as %macro for line extraction, but | |
2001 | instead of creating a macro it saves the resulting string to the |
|
2001 | instead of creating a macro it saves the resulting string to the | |
2002 | filename you specify. |
|
2002 | filename you specify. | |
2003 |
|
2003 | |||
2004 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2004 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2005 | it asks for confirmation before overwriting existing files.""" |
|
2005 | it asks for confirmation before overwriting existing files.""" | |
2006 |
|
2006 | |||
2007 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2007 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2008 | fname,ranges = args[0], args[1:] |
|
2008 | fname,ranges = args[0], args[1:] | |
2009 | if not fname.endswith('.py'): |
|
2009 | if not fname.endswith('.py'): | |
2010 | fname += '.py' |
|
2010 | fname += '.py' | |
2011 | if os.path.isfile(fname): |
|
2011 | if os.path.isfile(fname): | |
2012 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2012 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2013 | if ans.lower() not in ['y','yes']: |
|
2013 | if ans.lower() not in ['y','yes']: | |
2014 | print 'Operation cancelled.' |
|
2014 | print 'Operation cancelled.' | |
2015 | return |
|
2015 | return | |
2016 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2016 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2017 | f = file(fname,'w') |
|
2017 | f = file(fname,'w') | |
2018 | f.write(cmds) |
|
2018 | f.write(cmds) | |
2019 | f.close() |
|
2019 | f.close() | |
2020 | print 'The following commands were written to file `%s`:' % fname |
|
2020 | print 'The following commands were written to file `%s`:' % fname | |
2021 | print cmds |
|
2021 | print cmds | |
2022 |
|
2022 | |||
2023 | def _edit_macro(self,mname,macro): |
|
2023 | def _edit_macro(self,mname,macro): | |
2024 | """open an editor with the macro data in a file""" |
|
2024 | """open an editor with the macro data in a file""" | |
2025 | filename = self.shell.mktempfile(macro.value) |
|
2025 | filename = self.shell.mktempfile(macro.value) | |
2026 | self.shell.hooks.editor(filename) |
|
2026 | self.shell.hooks.editor(filename) | |
2027 |
|
2027 | |||
2028 | # and make a new macro object, to replace the old one |
|
2028 | # and make a new macro object, to replace the old one | |
2029 | mfile = open(filename) |
|
2029 | mfile = open(filename) | |
2030 | mvalue = mfile.read() |
|
2030 | mvalue = mfile.read() | |
2031 | mfile.close() |
|
2031 | mfile.close() | |
2032 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2032 | self.shell.user_ns[mname] = Macro(mvalue) | |
2033 |
|
2033 | |||
2034 | def magic_ed(self,parameter_s=''): |
|
2034 | def magic_ed(self,parameter_s=''): | |
2035 | """Alias to %edit.""" |
|
2035 | """Alias to %edit.""" | |
2036 | return self.magic_edit(parameter_s) |
|
2036 | return self.magic_edit(parameter_s) | |
2037 |
|
2037 | |||
2038 | @testdec.skip_doctest |
|
2038 | @testdec.skip_doctest | |
2039 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2039 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2040 | """Bring up an editor and execute the resulting code. |
|
2040 | """Bring up an editor and execute the resulting code. | |
2041 |
|
2041 | |||
2042 | Usage: |
|
2042 | Usage: | |
2043 | %edit [options] [args] |
|
2043 | %edit [options] [args] | |
2044 |
|
2044 | |||
2045 | %edit runs IPython's editor hook. The default version of this hook is |
|
2045 | %edit runs IPython's editor hook. The default version of this hook is | |
2046 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2046 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2047 | environment variable $EDITOR. If this isn't found, it will default to |
|
2047 | environment variable $EDITOR. If this isn't found, it will default to | |
2048 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2048 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2049 | docstring for how to change the editor hook. |
|
2049 | docstring for how to change the editor hook. | |
2050 |
|
2050 | |||
2051 | You can also set the value of this editor via the command line option |
|
2051 | You can also set the value of this editor via the command line option | |
2052 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2052 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2053 | specifically for IPython an editor different from your typical default |
|
2053 | specifically for IPython an editor different from your typical default | |
2054 | (and for Windows users who typically don't set environment variables). |
|
2054 | (and for Windows users who typically don't set environment variables). | |
2055 |
|
2055 | |||
2056 | This command allows you to conveniently edit multi-line code right in |
|
2056 | This command allows you to conveniently edit multi-line code right in | |
2057 | your IPython session. |
|
2057 | your IPython session. | |
2058 |
|
2058 | |||
2059 | If called without arguments, %edit opens up an empty editor with a |
|
2059 | If called without arguments, %edit opens up an empty editor with a | |
2060 | temporary file and will execute the contents of this file when you |
|
2060 | temporary file and will execute the contents of this file when you | |
2061 | close it (don't forget to save it!). |
|
2061 | close it (don't forget to save it!). | |
2062 |
|
2062 | |||
2063 |
|
2063 | |||
2064 | Options: |
|
2064 | Options: | |
2065 |
|
2065 | |||
2066 | -n <number>: open the editor at a specified line number. By default, |
|
2066 | -n <number>: open the editor at a specified line number. By default, | |
2067 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2067 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2068 | you can configure this by providing your own modified hook if your |
|
2068 | you can configure this by providing your own modified hook if your | |
2069 | favorite editor supports line-number specifications with a different |
|
2069 | favorite editor supports line-number specifications with a different | |
2070 | syntax. |
|
2070 | syntax. | |
2071 |
|
2071 | |||
2072 | -p: this will call the editor with the same data as the previous time |
|
2072 | -p: this will call the editor with the same data as the previous time | |
2073 | it was used, regardless of how long ago (in your current session) it |
|
2073 | it was used, regardless of how long ago (in your current session) it | |
2074 | was. |
|
2074 | was. | |
2075 |
|
2075 | |||
2076 | -r: use 'raw' input. This option only applies to input taken from the |
|
2076 | -r: use 'raw' input. This option only applies to input taken from the | |
2077 | user's history. By default, the 'processed' history is used, so that |
|
2077 | user's history. By default, the 'processed' history is used, so that | |
2078 | magics are loaded in their transformed version to valid Python. If |
|
2078 | magics are loaded in their transformed version to valid Python. If | |
2079 | this option is given, the raw input as typed as the command line is |
|
2079 | this option is given, the raw input as typed as the command line is | |
2080 | used instead. When you exit the editor, it will be executed by |
|
2080 | used instead. When you exit the editor, it will be executed by | |
2081 | IPython's own processor. |
|
2081 | IPython's own processor. | |
2082 |
|
2082 | |||
2083 | -x: do not execute the edited code immediately upon exit. This is |
|
2083 | -x: do not execute the edited code immediately upon exit. This is | |
2084 | mainly useful if you are editing programs which need to be called with |
|
2084 | mainly useful if you are editing programs which need to be called with | |
2085 | command line arguments, which you can then do using %run. |
|
2085 | command line arguments, which you can then do using %run. | |
2086 |
|
2086 | |||
2087 |
|
2087 | |||
2088 | Arguments: |
|
2088 | Arguments: | |
2089 |
|
2089 | |||
2090 | If arguments are given, the following possibilites exist: |
|
2090 | If arguments are given, the following possibilites exist: | |
2091 |
|
2091 | |||
2092 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2092 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2093 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2093 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2094 | loaded into the editor. The syntax is the same of the %macro command. |
|
2094 | loaded into the editor. The syntax is the same of the %macro command. | |
2095 |
|
2095 | |||
2096 | - If the argument doesn't start with a number, it is evaluated as a |
|
2096 | - If the argument doesn't start with a number, it is evaluated as a | |
2097 | variable and its contents loaded into the editor. You can thus edit |
|
2097 | variable and its contents loaded into the editor. You can thus edit | |
2098 | any string which contains python code (including the result of |
|
2098 | any string which contains python code (including the result of | |
2099 | previous edits). |
|
2099 | previous edits). | |
2100 |
|
2100 | |||
2101 | - If the argument is the name of an object (other than a string), |
|
2101 | - If the argument is the name of an object (other than a string), | |
2102 | IPython will try to locate the file where it was defined and open the |
|
2102 | IPython will try to locate the file where it was defined and open the | |
2103 | editor at the point where it is defined. You can use `%edit function` |
|
2103 | editor at the point where it is defined. You can use `%edit function` | |
2104 | to load an editor exactly at the point where 'function' is defined, |
|
2104 | to load an editor exactly at the point where 'function' is defined, | |
2105 | edit it and have the file be executed automatically. |
|
2105 | edit it and have the file be executed automatically. | |
2106 |
|
2106 | |||
2107 | If the object is a macro (see %macro for details), this opens up your |
|
2107 | If the object is a macro (see %macro for details), this opens up your | |
2108 | specified editor with a temporary file containing the macro's data. |
|
2108 | specified editor with a temporary file containing the macro's data. | |
2109 | Upon exit, the macro is reloaded with the contents of the file. |
|
2109 | Upon exit, the macro is reloaded with the contents of the file. | |
2110 |
|
2110 | |||
2111 | Note: opening at an exact line is only supported under Unix, and some |
|
2111 | Note: opening at an exact line is only supported under Unix, and some | |
2112 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2112 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2113 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2113 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2114 | (X)Emacs, vi, jed, pico and joe all do. |
|
2114 | (X)Emacs, vi, jed, pico and joe all do. | |
2115 |
|
2115 | |||
2116 | - If the argument is not found as a variable, IPython will look for a |
|
2116 | - If the argument is not found as a variable, IPython will look for a | |
2117 | file with that name (adding .py if necessary) and load it into the |
|
2117 | file with that name (adding .py if necessary) and load it into the | |
2118 | editor. It will execute its contents with execfile() when you exit, |
|
2118 | editor. It will execute its contents with execfile() when you exit, | |
2119 | loading any code in the file into your interactive namespace. |
|
2119 | loading any code in the file into your interactive namespace. | |
2120 |
|
2120 | |||
2121 | After executing your code, %edit will return as output the code you |
|
2121 | After executing your code, %edit will return as output the code you | |
2122 | typed in the editor (except when it was an existing file). This way |
|
2122 | typed in the editor (except when it was an existing file). This way | |
2123 | you can reload the code in further invocations of %edit as a variable, |
|
2123 | you can reload the code in further invocations of %edit as a variable, | |
2124 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2124 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2125 | the output. |
|
2125 | the output. | |
2126 |
|
2126 | |||
2127 | Note that %edit is also available through the alias %ed. |
|
2127 | Note that %edit is also available through the alias %ed. | |
2128 |
|
2128 | |||
2129 | This is an example of creating a simple function inside the editor and |
|
2129 | This is an example of creating a simple function inside the editor and | |
2130 | then modifying it. First, start up the editor: |
|
2130 | then modifying it. First, start up the editor: | |
2131 |
|
2131 | |||
2132 | In [1]: ed |
|
2132 | In [1]: ed | |
2133 | Editing... done. Executing edited code... |
|
2133 | Editing... done. Executing edited code... | |
2134 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2134 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2135 |
|
2135 | |||
2136 | We can then call the function foo(): |
|
2136 | We can then call the function foo(): | |
2137 |
|
2137 | |||
2138 | In [2]: foo() |
|
2138 | In [2]: foo() | |
2139 | foo() was defined in an editing session |
|
2139 | foo() was defined in an editing session | |
2140 |
|
2140 | |||
2141 | Now we edit foo. IPython automatically loads the editor with the |
|
2141 | Now we edit foo. IPython automatically loads the editor with the | |
2142 | (temporary) file where foo() was previously defined: |
|
2142 | (temporary) file where foo() was previously defined: | |
2143 |
|
2143 | |||
2144 | In [3]: ed foo |
|
2144 | In [3]: ed foo | |
2145 | Editing... done. Executing edited code... |
|
2145 | Editing... done. Executing edited code... | |
2146 |
|
2146 | |||
2147 | And if we call foo() again we get the modified version: |
|
2147 | And if we call foo() again we get the modified version: | |
2148 |
|
2148 | |||
2149 | In [4]: foo() |
|
2149 | In [4]: foo() | |
2150 | foo() has now been changed! |
|
2150 | foo() has now been changed! | |
2151 |
|
2151 | |||
2152 | Here is an example of how to edit a code snippet successive |
|
2152 | Here is an example of how to edit a code snippet successive | |
2153 | times. First we call the editor: |
|
2153 | times. First we call the editor: | |
2154 |
|
2154 | |||
2155 | In [5]: ed |
|
2155 | In [5]: ed | |
2156 | Editing... done. Executing edited code... |
|
2156 | Editing... done. Executing edited code... | |
2157 | hello |
|
2157 | hello | |
2158 | Out[5]: "print 'hello'n" |
|
2158 | Out[5]: "print 'hello'n" | |
2159 |
|
2159 | |||
2160 | Now we call it again with the previous output (stored in _): |
|
2160 | Now we call it again with the previous output (stored in _): | |
2161 |
|
2161 | |||
2162 | In [6]: ed _ |
|
2162 | In [6]: ed _ | |
2163 | Editing... done. Executing edited code... |
|
2163 | Editing... done. Executing edited code... | |
2164 | hello world |
|
2164 | hello world | |
2165 | Out[6]: "print 'hello world'n" |
|
2165 | Out[6]: "print 'hello world'n" | |
2166 |
|
2166 | |||
2167 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2167 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2168 |
|
2168 | |||
2169 | In [7]: ed _8 |
|
2169 | In [7]: ed _8 | |
2170 | Editing... done. Executing edited code... |
|
2170 | Editing... done. Executing edited code... | |
2171 | hello again |
|
2171 | hello again | |
2172 | Out[7]: "print 'hello again'n" |
|
2172 | Out[7]: "print 'hello again'n" | |
2173 |
|
2173 | |||
2174 |
|
2174 | |||
2175 | Changing the default editor hook: |
|
2175 | Changing the default editor hook: | |
2176 |
|
2176 | |||
2177 | If you wish to write your own editor hook, you can put it in a |
|
2177 | If you wish to write your own editor hook, you can put it in a | |
2178 | configuration file which you load at startup time. The default hook |
|
2178 | configuration file which you load at startup time. The default hook | |
2179 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2179 | is defined in the IPython.core.hooks module, and you can use that as a | |
2180 | starting example for further modifications. That file also has |
|
2180 | starting example for further modifications. That file also has | |
2181 | general instructions on how to set a new hook for use once you've |
|
2181 | general instructions on how to set a new hook for use once you've | |
2182 | defined it.""" |
|
2182 | defined it.""" | |
2183 |
|
2183 | |||
2184 | # FIXME: This function has become a convoluted mess. It needs a |
|
2184 | # FIXME: This function has become a convoluted mess. It needs a | |
2185 | # ground-up rewrite with clean, simple logic. |
|
2185 | # ground-up rewrite with clean, simple logic. | |
2186 |
|
2186 | |||
2187 | def make_filename(arg): |
|
2187 | def make_filename(arg): | |
2188 | "Make a filename from the given args" |
|
2188 | "Make a filename from the given args" | |
2189 | try: |
|
2189 | try: | |
2190 | filename = get_py_filename(arg) |
|
2190 | filename = get_py_filename(arg) | |
2191 | except IOError: |
|
2191 | except IOError: | |
2192 | if args.endswith('.py'): |
|
2192 | if args.endswith('.py'): | |
2193 | filename = arg |
|
2193 | filename = arg | |
2194 | else: |
|
2194 | else: | |
2195 | filename = None |
|
2195 | filename = None | |
2196 | return filename |
|
2196 | return filename | |
2197 |
|
2197 | |||
2198 | # custom exceptions |
|
2198 | # custom exceptions | |
2199 | class DataIsObject(Exception): pass |
|
2199 | class DataIsObject(Exception): pass | |
2200 |
|
2200 | |||
2201 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2201 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2202 | # Set a few locals from the options for convenience: |
|
2202 | # Set a few locals from the options for convenience: | |
2203 | opts_p = opts.has_key('p') |
|
2203 | opts_p = opts.has_key('p') | |
2204 | opts_r = opts.has_key('r') |
|
2204 | opts_r = opts.has_key('r') | |
2205 |
|
2205 | |||
2206 | # Default line number value |
|
2206 | # Default line number value | |
2207 | lineno = opts.get('n',None) |
|
2207 | lineno = opts.get('n',None) | |
2208 |
|
2208 | |||
2209 | if opts_p: |
|
2209 | if opts_p: | |
2210 | args = '_%s' % last_call[0] |
|
2210 | args = '_%s' % last_call[0] | |
2211 | if not self.shell.user_ns.has_key(args): |
|
2211 | if not self.shell.user_ns.has_key(args): | |
2212 | args = last_call[1] |
|
2212 | args = last_call[1] | |
2213 |
|
2213 | |||
2214 | # use last_call to remember the state of the previous call, but don't |
|
2214 | # use last_call to remember the state of the previous call, but don't | |
2215 | # let it be clobbered by successive '-p' calls. |
|
2215 | # let it be clobbered by successive '-p' calls. | |
2216 | try: |
|
2216 | try: | |
2217 | last_call[0] = self.shell.displayhook.prompt_count |
|
2217 | last_call[0] = self.shell.displayhook.prompt_count | |
2218 | if not opts_p: |
|
2218 | if not opts_p: | |
2219 | last_call[1] = parameter_s |
|
2219 | last_call[1] = parameter_s | |
2220 | except: |
|
2220 | except: | |
2221 | pass |
|
2221 | pass | |
2222 |
|
2222 | |||
2223 | # by default this is done with temp files, except when the given |
|
2223 | # by default this is done with temp files, except when the given | |
2224 | # arg is a filename |
|
2224 | # arg is a filename | |
2225 | use_temp = 1 |
|
2225 | use_temp = 1 | |
2226 |
|
2226 | |||
2227 | if re.match(r'\d',args): |
|
2227 | if re.match(r'\d',args): | |
2228 | # Mode where user specifies ranges of lines, like in %macro. |
|
2228 | # Mode where user specifies ranges of lines, like in %macro. | |
2229 | # This means that you can't edit files whose names begin with |
|
2229 | # This means that you can't edit files whose names begin with | |
2230 | # numbers this way. Tough. |
|
2230 | # numbers this way. Tough. | |
2231 | ranges = args.split() |
|
2231 | ranges = args.split() | |
2232 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2232 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2233 | elif args.endswith('.py'): |
|
2233 | elif args.endswith('.py'): | |
2234 | filename = make_filename(args) |
|
2234 | filename = make_filename(args) | |
2235 | data = '' |
|
2235 | data = '' | |
2236 | use_temp = 0 |
|
2236 | use_temp = 0 | |
2237 | elif args: |
|
2237 | elif args: | |
2238 | try: |
|
2238 | try: | |
2239 | # Load the parameter given as a variable. If not a string, |
|
2239 | # Load the parameter given as a variable. If not a string, | |
2240 | # process it as an object instead (below) |
|
2240 | # process it as an object instead (below) | |
2241 |
|
2241 | |||
2242 | #print '*** args',args,'type',type(args) # dbg |
|
2242 | #print '*** args',args,'type',type(args) # dbg | |
2243 | data = eval(args,self.shell.user_ns) |
|
2243 | data = eval(args,self.shell.user_ns) | |
2244 | if not type(data) in StringTypes: |
|
2244 | if not type(data) in StringTypes: | |
2245 | raise DataIsObject |
|
2245 | raise DataIsObject | |
2246 |
|
2246 | |||
2247 | except (NameError,SyntaxError): |
|
2247 | except (NameError,SyntaxError): | |
2248 | # given argument is not a variable, try as a filename |
|
2248 | # given argument is not a variable, try as a filename | |
2249 | filename = make_filename(args) |
|
2249 | filename = make_filename(args) | |
2250 | if filename is None: |
|
2250 | if filename is None: | |
2251 | warn("Argument given (%s) can't be found as a variable " |
|
2251 | warn("Argument given (%s) can't be found as a variable " | |
2252 | "or as a filename." % args) |
|
2252 | "or as a filename." % args) | |
2253 | return |
|
2253 | return | |
2254 |
|
2254 | |||
2255 | data = '' |
|
2255 | data = '' | |
2256 | use_temp = 0 |
|
2256 | use_temp = 0 | |
2257 | except DataIsObject: |
|
2257 | except DataIsObject: | |
2258 |
|
2258 | |||
2259 | # macros have a special edit function |
|
2259 | # macros have a special edit function | |
2260 | if isinstance(data,Macro): |
|
2260 | if isinstance(data,Macro): | |
2261 | self._edit_macro(args,data) |
|
2261 | self._edit_macro(args,data) | |
2262 | return |
|
2262 | return | |
2263 |
|
2263 | |||
2264 | # For objects, try to edit the file where they are defined |
|
2264 | # For objects, try to edit the file where they are defined | |
2265 | try: |
|
2265 | try: | |
2266 | filename = inspect.getabsfile(data) |
|
2266 | filename = inspect.getabsfile(data) | |
2267 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2267 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2268 | # class created by %edit? Try to find source |
|
2268 | # class created by %edit? Try to find source | |
2269 | # by looking for method definitions instead, the |
|
2269 | # by looking for method definitions instead, the | |
2270 | # __module__ in those classes is FakeModule. |
|
2270 | # __module__ in those classes is FakeModule. | |
2271 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2271 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2272 | for attr in attrs: |
|
2272 | for attr in attrs: | |
2273 | if not inspect.ismethod(attr): |
|
2273 | if not inspect.ismethod(attr): | |
2274 | continue |
|
2274 | continue | |
2275 | filename = inspect.getabsfile(attr) |
|
2275 | filename = inspect.getabsfile(attr) | |
2276 | if filename and 'fakemodule' not in filename.lower(): |
|
2276 | if filename and 'fakemodule' not in filename.lower(): | |
2277 | # change the attribute to be the edit target instead |
|
2277 | # change the attribute to be the edit target instead | |
2278 | data = attr |
|
2278 | data = attr | |
2279 | break |
|
2279 | break | |
2280 |
|
2280 | |||
2281 | datafile = 1 |
|
2281 | datafile = 1 | |
2282 | except TypeError: |
|
2282 | except TypeError: | |
2283 | filename = make_filename(args) |
|
2283 | filename = make_filename(args) | |
2284 | datafile = 1 |
|
2284 | datafile = 1 | |
2285 | warn('Could not find file where `%s` is defined.\n' |
|
2285 | warn('Could not find file where `%s` is defined.\n' | |
2286 | 'Opening a file named `%s`' % (args,filename)) |
|
2286 | 'Opening a file named `%s`' % (args,filename)) | |
2287 | # Now, make sure we can actually read the source (if it was in |
|
2287 | # Now, make sure we can actually read the source (if it was in | |
2288 | # a temp file it's gone by now). |
|
2288 | # a temp file it's gone by now). | |
2289 | if datafile: |
|
2289 | if datafile: | |
2290 | try: |
|
2290 | try: | |
2291 | if lineno is None: |
|
2291 | if lineno is None: | |
2292 | lineno = inspect.getsourcelines(data)[1] |
|
2292 | lineno = inspect.getsourcelines(data)[1] | |
2293 | except IOError: |
|
2293 | except IOError: | |
2294 | filename = make_filename(args) |
|
2294 | filename = make_filename(args) | |
2295 | if filename is None: |
|
2295 | if filename is None: | |
2296 | warn('The file `%s` where `%s` was defined cannot ' |
|
2296 | warn('The file `%s` where `%s` was defined cannot ' | |
2297 | 'be read.' % (filename,data)) |
|
2297 | 'be read.' % (filename,data)) | |
2298 | return |
|
2298 | return | |
2299 | use_temp = 0 |
|
2299 | use_temp = 0 | |
2300 | else: |
|
2300 | else: | |
2301 | data = '' |
|
2301 | data = '' | |
2302 |
|
2302 | |||
2303 | if use_temp: |
|
2303 | if use_temp: | |
2304 | filename = self.shell.mktempfile(data) |
|
2304 | filename = self.shell.mktempfile(data) | |
2305 | print 'IPython will make a temporary file named:',filename |
|
2305 | print 'IPython will make a temporary file named:',filename | |
2306 |
|
2306 | |||
2307 | # do actual editing here |
|
2307 | # do actual editing here | |
2308 | print 'Editing...', |
|
2308 | print 'Editing...', | |
2309 | sys.stdout.flush() |
|
2309 | sys.stdout.flush() | |
2310 | try: |
|
2310 | try: | |
2311 | # Quote filenames that may have spaces in them |
|
2311 | # Quote filenames that may have spaces in them | |
2312 | if ' ' in filename: |
|
2312 | if ' ' in filename: | |
2313 | filename = "%s" % filename |
|
2313 | filename = "%s" % filename | |
2314 | self.shell.hooks.editor(filename,lineno) |
|
2314 | self.shell.hooks.editor(filename,lineno) | |
2315 | except TryNext: |
|
2315 | except TryNext: | |
2316 | warn('Could not open editor') |
|
2316 | warn('Could not open editor') | |
2317 | return |
|
2317 | return | |
2318 |
|
2318 | |||
2319 | # XXX TODO: should this be generalized for all string vars? |
|
2319 | # XXX TODO: should this be generalized for all string vars? | |
2320 | # For now, this is special-cased to blocks created by cpaste |
|
2320 | # For now, this is special-cased to blocks created by cpaste | |
2321 | if args.strip() == 'pasted_block': |
|
2321 | if args.strip() == 'pasted_block': | |
2322 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2322 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2323 |
|
2323 | |||
2324 | if opts.has_key('x'): # -x prevents actual execution |
|
2324 | if opts.has_key('x'): # -x prevents actual execution | |
2325 |
|
2325 | |||
2326 | else: |
|
2326 | else: | |
2327 | print 'done. Executing edited code...' |
|
2327 | print 'done. Executing edited code...' | |
2328 | if opts_r: |
|
2328 | if opts_r: | |
2329 | self.shell.run_cell(file_read(filename)) |
|
2329 | self.shell.run_cell(file_read(filename)) | |
2330 | else: |
|
2330 | else: | |
2331 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2331 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2332 | self.shell.user_ns) |
|
2332 | self.shell.user_ns) | |
2333 |
|
2333 | |||
2334 |
|
2334 | |||
2335 | if use_temp: |
|
2335 | if use_temp: | |
2336 | try: |
|
2336 | try: | |
2337 | return open(filename).read() |
|
2337 | return open(filename).read() | |
2338 | except IOError,msg: |
|
2338 | except IOError,msg: | |
2339 | if msg.filename == filename: |
|
2339 | if msg.filename == filename: | |
2340 | warn('File not found. Did you forget to save?') |
|
2340 | warn('File not found. Did you forget to save?') | |
2341 | return |
|
2341 | return | |
2342 | else: |
|
2342 | else: | |
2343 | self.shell.showtraceback() |
|
2343 | self.shell.showtraceback() | |
2344 |
|
2344 | |||
2345 | def magic_xmode(self,parameter_s = ''): |
|
2345 | def magic_xmode(self,parameter_s = ''): | |
2346 | """Switch modes for the exception handlers. |
|
2346 | """Switch modes for the exception handlers. | |
2347 |
|
2347 | |||
2348 | Valid modes: Plain, Context and Verbose. |
|
2348 | Valid modes: Plain, Context and Verbose. | |
2349 |
|
2349 | |||
2350 | If called without arguments, acts as a toggle.""" |
|
2350 | If called without arguments, acts as a toggle.""" | |
2351 |
|
2351 | |||
2352 | def xmode_switch_err(name): |
|
2352 | def xmode_switch_err(name): | |
2353 | warn('Error changing %s exception modes.\n%s' % |
|
2353 | warn('Error changing %s exception modes.\n%s' % | |
2354 | (name,sys.exc_info()[1])) |
|
2354 | (name,sys.exc_info()[1])) | |
2355 |
|
2355 | |||
2356 | shell = self.shell |
|
2356 | shell = self.shell | |
2357 | new_mode = parameter_s.strip().capitalize() |
|
2357 | new_mode = parameter_s.strip().capitalize() | |
2358 | try: |
|
2358 | try: | |
2359 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2359 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2360 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2360 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2361 | except: |
|
2361 | except: | |
2362 | xmode_switch_err('user') |
|
2362 | xmode_switch_err('user') | |
2363 |
|
2363 | |||
2364 | def magic_colors(self,parameter_s = ''): |
|
2364 | def magic_colors(self,parameter_s = ''): | |
2365 | """Switch color scheme for prompts, info system and exception handlers. |
|
2365 | """Switch color scheme for prompts, info system and exception handlers. | |
2366 |
|
2366 | |||
2367 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2367 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2368 |
|
2368 | |||
2369 | Color scheme names are not case-sensitive.""" |
|
2369 | Color scheme names are not case-sensitive.""" | |
2370 |
|
2370 | |||
2371 | def color_switch_err(name): |
|
2371 | def color_switch_err(name): | |
2372 | warn('Error changing %s color schemes.\n%s' % |
|
2372 | warn('Error changing %s color schemes.\n%s' % | |
2373 | (name,sys.exc_info()[1])) |
|
2373 | (name,sys.exc_info()[1])) | |
2374 |
|
2374 | |||
2375 |
|
2375 | |||
2376 | new_scheme = parameter_s.strip() |
|
2376 | new_scheme = parameter_s.strip() | |
2377 | if not new_scheme: |
|
2377 | if not new_scheme: | |
2378 | raise UsageError( |
|
2378 | raise UsageError( | |
2379 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2379 | "%colors: you must specify a color scheme. See '%colors?'") | |
2380 | return |
|
2380 | return | |
2381 | # local shortcut |
|
2381 | # local shortcut | |
2382 | shell = self.shell |
|
2382 | shell = self.shell | |
2383 |
|
2383 | |||
2384 | import IPython.utils.rlineimpl as readline |
|
2384 | import IPython.utils.rlineimpl as readline | |
2385 |
|
2385 | |||
2386 | if not readline.have_readline and sys.platform == "win32": |
|
2386 | if not readline.have_readline and sys.platform == "win32": | |
2387 | msg = """\ |
|
2387 | msg = """\ | |
2388 | Proper color support under MS Windows requires the pyreadline library. |
|
2388 | Proper color support under MS Windows requires the pyreadline library. | |
2389 | You can find it at: |
|
2389 | You can find it at: | |
2390 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2390 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2391 | Gary's readline needs the ctypes module, from: |
|
2391 | Gary's readline needs the ctypes module, from: | |
2392 | http://starship.python.net/crew/theller/ctypes |
|
2392 | http://starship.python.net/crew/theller/ctypes | |
2393 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2393 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2394 |
|
2394 | |||
2395 | Defaulting color scheme to 'NoColor'""" |
|
2395 | Defaulting color scheme to 'NoColor'""" | |
2396 | new_scheme = 'NoColor' |
|
2396 | new_scheme = 'NoColor' | |
2397 | warn(msg) |
|
2397 | warn(msg) | |
2398 |
|
2398 | |||
2399 | # readline option is 0 |
|
2399 | # readline option is 0 | |
2400 | if not shell.has_readline: |
|
2400 | if not shell.has_readline: | |
2401 | new_scheme = 'NoColor' |
|
2401 | new_scheme = 'NoColor' | |
2402 |
|
2402 | |||
2403 | # Set prompt colors |
|
2403 | # Set prompt colors | |
2404 | try: |
|
2404 | try: | |
2405 | shell.displayhook.set_colors(new_scheme) |
|
2405 | shell.displayhook.set_colors(new_scheme) | |
2406 | except: |
|
2406 | except: | |
2407 | color_switch_err('prompt') |
|
2407 | color_switch_err('prompt') | |
2408 | else: |
|
2408 | else: | |
2409 | shell.colors = \ |
|
2409 | shell.colors = \ | |
2410 | shell.displayhook.color_table.active_scheme_name |
|
2410 | shell.displayhook.color_table.active_scheme_name | |
2411 | # Set exception colors |
|
2411 | # Set exception colors | |
2412 | try: |
|
2412 | try: | |
2413 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2413 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2414 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2414 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2415 | except: |
|
2415 | except: | |
2416 | color_switch_err('exception') |
|
2416 | color_switch_err('exception') | |
2417 |
|
2417 | |||
2418 | # Set info (for 'object?') colors |
|
2418 | # Set info (for 'object?') colors | |
2419 | if shell.color_info: |
|
2419 | if shell.color_info: | |
2420 | try: |
|
2420 | try: | |
2421 | shell.inspector.set_active_scheme(new_scheme) |
|
2421 | shell.inspector.set_active_scheme(new_scheme) | |
2422 | except: |
|
2422 | except: | |
2423 | color_switch_err('object inspector') |
|
2423 | color_switch_err('object inspector') | |
2424 | else: |
|
2424 | else: | |
2425 | shell.inspector.set_active_scheme('NoColor') |
|
2425 | shell.inspector.set_active_scheme('NoColor') | |
2426 |
|
2426 | |||
2427 |
def magic_ |
|
2427 | def magic_pprint(self, parameter_s=''): | |
2428 | """Toggle pretty printing on/off.""" |
|
2428 | """Toggle pretty printing on/off.""" | |
2429 |
|
2429 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | ||
2430 | self.shell.pprint = 1 - self.shell.pprint |
|
2430 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2431 | print 'Pretty printing has been turned', \ |
|
2431 | print 'Pretty printing has been turned', \ | |
2432 |
['OFF','ON'][ |
|
2432 | ['OFF','ON'][ptformatter.pprint] | |
2433 |
|
2433 | |||
2434 | def magic_Exit(self, parameter_s=''): |
|
2434 | def magic_Exit(self, parameter_s=''): | |
2435 | """Exit IPython.""" |
|
2435 | """Exit IPython.""" | |
2436 |
|
2436 | |||
2437 | self.shell.ask_exit() |
|
2437 | self.shell.ask_exit() | |
2438 |
|
2438 | |||
2439 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2439 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2440 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2440 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2441 |
|
2441 | |||
2442 | #...................................................................... |
|
2442 | #...................................................................... | |
2443 | # Functions to implement unix shell-type things |
|
2443 | # Functions to implement unix shell-type things | |
2444 |
|
2444 | |||
2445 | @testdec.skip_doctest |
|
2445 | @testdec.skip_doctest | |
2446 | def magic_alias(self, parameter_s = ''): |
|
2446 | def magic_alias(self, parameter_s = ''): | |
2447 | """Define an alias for a system command. |
|
2447 | """Define an alias for a system command. | |
2448 |
|
2448 | |||
2449 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2449 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2450 |
|
2450 | |||
2451 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2451 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2452 | params' (from your underlying operating system). |
|
2452 | params' (from your underlying operating system). | |
2453 |
|
2453 | |||
2454 | Aliases have lower precedence than magic functions and Python normal |
|
2454 | Aliases have lower precedence than magic functions and Python normal | |
2455 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2455 | variables, so if 'foo' is both a Python variable and an alias, the | |
2456 | alias can not be executed until 'del foo' removes the Python variable. |
|
2456 | alias can not be executed until 'del foo' removes the Python variable. | |
2457 |
|
2457 | |||
2458 | You can use the %l specifier in an alias definition to represent the |
|
2458 | You can use the %l specifier in an alias definition to represent the | |
2459 | whole line when the alias is called. For example: |
|
2459 | whole line when the alias is called. For example: | |
2460 |
|
2460 | |||
2461 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2461 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2462 | In [3]: bracket hello world |
|
2462 | In [3]: bracket hello world | |
2463 | Input in brackets: <hello world> |
|
2463 | Input in brackets: <hello world> | |
2464 |
|
2464 | |||
2465 | You can also define aliases with parameters using %s specifiers (one |
|
2465 | You can also define aliases with parameters using %s specifiers (one | |
2466 | per parameter): |
|
2466 | per parameter): | |
2467 |
|
2467 | |||
2468 | In [1]: alias parts echo first %s second %s |
|
2468 | In [1]: alias parts echo first %s second %s | |
2469 | In [2]: %parts A B |
|
2469 | In [2]: %parts A B | |
2470 | first A second B |
|
2470 | first A second B | |
2471 | In [3]: %parts A |
|
2471 | In [3]: %parts A | |
2472 | Incorrect number of arguments: 2 expected. |
|
2472 | Incorrect number of arguments: 2 expected. | |
2473 | parts is an alias to: 'echo first %s second %s' |
|
2473 | parts is an alias to: 'echo first %s second %s' | |
2474 |
|
2474 | |||
2475 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2475 | Note that %l and %s are mutually exclusive. You can only use one or | |
2476 | the other in your aliases. |
|
2476 | the other in your aliases. | |
2477 |
|
2477 | |||
2478 | Aliases expand Python variables just like system calls using ! or !! |
|
2478 | Aliases expand Python variables just like system calls using ! or !! | |
2479 | do: all expressions prefixed with '$' get expanded. For details of |
|
2479 | do: all expressions prefixed with '$' get expanded. For details of | |
2480 | the semantic rules, see PEP-215: |
|
2480 | the semantic rules, see PEP-215: | |
2481 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2481 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2482 | IPython for variable expansion. If you want to access a true shell |
|
2482 | IPython for variable expansion. If you want to access a true shell | |
2483 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2483 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2484 |
|
2484 | |||
2485 | In [6]: alias show echo |
|
2485 | In [6]: alias show echo | |
2486 | In [7]: PATH='A Python string' |
|
2486 | In [7]: PATH='A Python string' | |
2487 | In [8]: show $PATH |
|
2487 | In [8]: show $PATH | |
2488 | A Python string |
|
2488 | A Python string | |
2489 | In [9]: show $$PATH |
|
2489 | In [9]: show $$PATH | |
2490 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2490 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2491 |
|
2491 | |||
2492 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2492 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2493 | and %rehashx functions, which automatically create aliases for the |
|
2493 | and %rehashx functions, which automatically create aliases for the | |
2494 | contents of your $PATH. |
|
2494 | contents of your $PATH. | |
2495 |
|
2495 | |||
2496 | If called with no parameters, %alias prints the current alias table.""" |
|
2496 | If called with no parameters, %alias prints the current alias table.""" | |
2497 |
|
2497 | |||
2498 | par = parameter_s.strip() |
|
2498 | par = parameter_s.strip() | |
2499 | if not par: |
|
2499 | if not par: | |
2500 | stored = self.db.get('stored_aliases', {} ) |
|
2500 | stored = self.db.get('stored_aliases', {} ) | |
2501 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2501 | aliases = sorted(self.shell.alias_manager.aliases) | |
2502 | # for k, v in stored: |
|
2502 | # for k, v in stored: | |
2503 | # atab.append(k, v[0]) |
|
2503 | # atab.append(k, v[0]) | |
2504 |
|
2504 | |||
2505 | print "Total number of aliases:", len(aliases) |
|
2505 | print "Total number of aliases:", len(aliases) | |
2506 | sys.stdout.flush() |
|
2506 | sys.stdout.flush() | |
2507 | return aliases |
|
2507 | return aliases | |
2508 |
|
2508 | |||
2509 | # Now try to define a new one |
|
2509 | # Now try to define a new one | |
2510 | try: |
|
2510 | try: | |
2511 | alias,cmd = par.split(None, 1) |
|
2511 | alias,cmd = par.split(None, 1) | |
2512 | except: |
|
2512 | except: | |
2513 | print oinspect.getdoc(self.magic_alias) |
|
2513 | print oinspect.getdoc(self.magic_alias) | |
2514 | else: |
|
2514 | else: | |
2515 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2515 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2516 | # end magic_alias |
|
2516 | # end magic_alias | |
2517 |
|
2517 | |||
2518 | def magic_unalias(self, parameter_s = ''): |
|
2518 | def magic_unalias(self, parameter_s = ''): | |
2519 | """Remove an alias""" |
|
2519 | """Remove an alias""" | |
2520 |
|
2520 | |||
2521 | aname = parameter_s.strip() |
|
2521 | aname = parameter_s.strip() | |
2522 | self.shell.alias_manager.undefine_alias(aname) |
|
2522 | self.shell.alias_manager.undefine_alias(aname) | |
2523 | stored = self.db.get('stored_aliases', {} ) |
|
2523 | stored = self.db.get('stored_aliases', {} ) | |
2524 | if aname in stored: |
|
2524 | if aname in stored: | |
2525 | print "Removing %stored alias",aname |
|
2525 | print "Removing %stored alias",aname | |
2526 | del stored[aname] |
|
2526 | del stored[aname] | |
2527 | self.db['stored_aliases'] = stored |
|
2527 | self.db['stored_aliases'] = stored | |
2528 |
|
2528 | |||
2529 | def magic_rehashx(self, parameter_s = ''): |
|
2529 | def magic_rehashx(self, parameter_s = ''): | |
2530 | """Update the alias table with all executable files in $PATH. |
|
2530 | """Update the alias table with all executable files in $PATH. | |
2531 |
|
2531 | |||
2532 | This version explicitly checks that every entry in $PATH is a file |
|
2532 | This version explicitly checks that every entry in $PATH is a file | |
2533 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2533 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2534 |
|
2534 | |||
2535 | Under Windows, it checks executability as a match agains a |
|
2535 | Under Windows, it checks executability as a match agains a | |
2536 | '|'-separated string of extensions, stored in the IPython config |
|
2536 | '|'-separated string of extensions, stored in the IPython config | |
2537 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2537 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2538 |
|
2538 | |||
2539 | This function also resets the root module cache of module completer, |
|
2539 | This function also resets the root module cache of module completer, | |
2540 | used on slow filesystems. |
|
2540 | used on slow filesystems. | |
2541 | """ |
|
2541 | """ | |
2542 | from IPython.core.alias import InvalidAliasError |
|
2542 | from IPython.core.alias import InvalidAliasError | |
2543 |
|
2543 | |||
2544 | # for the benefit of module completer in ipy_completers.py |
|
2544 | # for the benefit of module completer in ipy_completers.py | |
2545 | del self.db['rootmodules'] |
|
2545 | del self.db['rootmodules'] | |
2546 |
|
2546 | |||
2547 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2547 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2548 | os.environ.get('PATH','').split(os.pathsep)] |
|
2548 | os.environ.get('PATH','').split(os.pathsep)] | |
2549 | path = filter(os.path.isdir,path) |
|
2549 | path = filter(os.path.isdir,path) | |
2550 |
|
2550 | |||
2551 | syscmdlist = [] |
|
2551 | syscmdlist = [] | |
2552 | # Now define isexec in a cross platform manner. |
|
2552 | # Now define isexec in a cross platform manner. | |
2553 | if os.name == 'posix': |
|
2553 | if os.name == 'posix': | |
2554 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2554 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2555 | os.access(fname,os.X_OK) |
|
2555 | os.access(fname,os.X_OK) | |
2556 | else: |
|
2556 | else: | |
2557 | try: |
|
2557 | try: | |
2558 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2558 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2559 | except KeyError: |
|
2559 | except KeyError: | |
2560 | winext = 'exe|com|bat|py' |
|
2560 | winext = 'exe|com|bat|py' | |
2561 | if 'py' not in winext: |
|
2561 | if 'py' not in winext: | |
2562 | winext += '|py' |
|
2562 | winext += '|py' | |
2563 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2563 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2564 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2564 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2565 | savedir = os.getcwd() |
|
2565 | savedir = os.getcwd() | |
2566 |
|
2566 | |||
2567 | # Now walk the paths looking for executables to alias. |
|
2567 | # Now walk the paths looking for executables to alias. | |
2568 | try: |
|
2568 | try: | |
2569 | # write the whole loop for posix/Windows so we don't have an if in |
|
2569 | # write the whole loop for posix/Windows so we don't have an if in | |
2570 | # the innermost part |
|
2570 | # the innermost part | |
2571 | if os.name == 'posix': |
|
2571 | if os.name == 'posix': | |
2572 | for pdir in path: |
|
2572 | for pdir in path: | |
2573 | os.chdir(pdir) |
|
2573 | os.chdir(pdir) | |
2574 | for ff in os.listdir(pdir): |
|
2574 | for ff in os.listdir(pdir): | |
2575 | if isexec(ff): |
|
2575 | if isexec(ff): | |
2576 | try: |
|
2576 | try: | |
2577 | # Removes dots from the name since ipython |
|
2577 | # Removes dots from the name since ipython | |
2578 | # will assume names with dots to be python. |
|
2578 | # will assume names with dots to be python. | |
2579 | self.shell.alias_manager.define_alias( |
|
2579 | self.shell.alias_manager.define_alias( | |
2580 | ff.replace('.',''), ff) |
|
2580 | ff.replace('.',''), ff) | |
2581 | except InvalidAliasError: |
|
2581 | except InvalidAliasError: | |
2582 | pass |
|
2582 | pass | |
2583 | else: |
|
2583 | else: | |
2584 | syscmdlist.append(ff) |
|
2584 | syscmdlist.append(ff) | |
2585 | else: |
|
2585 | else: | |
2586 | no_alias = self.shell.alias_manager.no_alias |
|
2586 | no_alias = self.shell.alias_manager.no_alias | |
2587 | for pdir in path: |
|
2587 | for pdir in path: | |
2588 | os.chdir(pdir) |
|
2588 | os.chdir(pdir) | |
2589 | for ff in os.listdir(pdir): |
|
2589 | for ff in os.listdir(pdir): | |
2590 | base, ext = os.path.splitext(ff) |
|
2590 | base, ext = os.path.splitext(ff) | |
2591 | if isexec(ff) and base.lower() not in no_alias: |
|
2591 | if isexec(ff) and base.lower() not in no_alias: | |
2592 | if ext.lower() == '.exe': |
|
2592 | if ext.lower() == '.exe': | |
2593 | ff = base |
|
2593 | ff = base | |
2594 | try: |
|
2594 | try: | |
2595 | # Removes dots from the name since ipython |
|
2595 | # Removes dots from the name since ipython | |
2596 | # will assume names with dots to be python. |
|
2596 | # will assume names with dots to be python. | |
2597 | self.shell.alias_manager.define_alias( |
|
2597 | self.shell.alias_manager.define_alias( | |
2598 | base.lower().replace('.',''), ff) |
|
2598 | base.lower().replace('.',''), ff) | |
2599 | except InvalidAliasError: |
|
2599 | except InvalidAliasError: | |
2600 | pass |
|
2600 | pass | |
2601 | syscmdlist.append(ff) |
|
2601 | syscmdlist.append(ff) | |
2602 | db = self.db |
|
2602 | db = self.db | |
2603 | db['syscmdlist'] = syscmdlist |
|
2603 | db['syscmdlist'] = syscmdlist | |
2604 | finally: |
|
2604 | finally: | |
2605 | os.chdir(savedir) |
|
2605 | os.chdir(savedir) | |
2606 |
|
2606 | |||
2607 | def magic_pwd(self, parameter_s = ''): |
|
2607 | def magic_pwd(self, parameter_s = ''): | |
2608 | """Return the current working directory path.""" |
|
2608 | """Return the current working directory path.""" | |
2609 | return os.getcwd() |
|
2609 | return os.getcwd() | |
2610 |
|
2610 | |||
2611 | def magic_cd(self, parameter_s=''): |
|
2611 | def magic_cd(self, parameter_s=''): | |
2612 | """Change the current working directory. |
|
2612 | """Change the current working directory. | |
2613 |
|
2613 | |||
2614 | This command automatically maintains an internal list of directories |
|
2614 | This command automatically maintains an internal list of directories | |
2615 | you visit during your IPython session, in the variable _dh. The |
|
2615 | you visit during your IPython session, in the variable _dh. The | |
2616 | command %dhist shows this history nicely formatted. You can also |
|
2616 | command %dhist shows this history nicely formatted. You can also | |
2617 | do 'cd -<tab>' to see directory history conveniently. |
|
2617 | do 'cd -<tab>' to see directory history conveniently. | |
2618 |
|
2618 | |||
2619 | Usage: |
|
2619 | Usage: | |
2620 |
|
2620 | |||
2621 | cd 'dir': changes to directory 'dir'. |
|
2621 | cd 'dir': changes to directory 'dir'. | |
2622 |
|
2622 | |||
2623 | cd -: changes to the last visited directory. |
|
2623 | cd -: changes to the last visited directory. | |
2624 |
|
2624 | |||
2625 | cd -<n>: changes to the n-th directory in the directory history. |
|
2625 | cd -<n>: changes to the n-th directory in the directory history. | |
2626 |
|
2626 | |||
2627 | cd --foo: change to directory that matches 'foo' in history |
|
2627 | cd --foo: change to directory that matches 'foo' in history | |
2628 |
|
2628 | |||
2629 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2629 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2630 | (note: cd <bookmark_name> is enough if there is no |
|
2630 | (note: cd <bookmark_name> is enough if there is no | |
2631 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2631 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2632 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2632 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2633 |
|
2633 | |||
2634 | Options: |
|
2634 | Options: | |
2635 |
|
2635 | |||
2636 | -q: quiet. Do not print the working directory after the cd command is |
|
2636 | -q: quiet. Do not print the working directory after the cd command is | |
2637 | executed. By default IPython's cd command does print this directory, |
|
2637 | executed. By default IPython's cd command does print this directory, | |
2638 | since the default prompts do not display path information. |
|
2638 | since the default prompts do not display path information. | |
2639 |
|
2639 | |||
2640 | Note that !cd doesn't work for this purpose because the shell where |
|
2640 | Note that !cd doesn't work for this purpose because the shell where | |
2641 | !command runs is immediately discarded after executing 'command'.""" |
|
2641 | !command runs is immediately discarded after executing 'command'.""" | |
2642 |
|
2642 | |||
2643 | parameter_s = parameter_s.strip() |
|
2643 | parameter_s = parameter_s.strip() | |
2644 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2644 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2645 |
|
2645 | |||
2646 | oldcwd = os.getcwd() |
|
2646 | oldcwd = os.getcwd() | |
2647 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2647 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2648 | # jump in directory history by number |
|
2648 | # jump in directory history by number | |
2649 | if numcd: |
|
2649 | if numcd: | |
2650 | nn = int(numcd.group(2)) |
|
2650 | nn = int(numcd.group(2)) | |
2651 | try: |
|
2651 | try: | |
2652 | ps = self.shell.user_ns['_dh'][nn] |
|
2652 | ps = self.shell.user_ns['_dh'][nn] | |
2653 | except IndexError: |
|
2653 | except IndexError: | |
2654 | print 'The requested directory does not exist in history.' |
|
2654 | print 'The requested directory does not exist in history.' | |
2655 | return |
|
2655 | return | |
2656 | else: |
|
2656 | else: | |
2657 | opts = {} |
|
2657 | opts = {} | |
2658 | elif parameter_s.startswith('--'): |
|
2658 | elif parameter_s.startswith('--'): | |
2659 | ps = None |
|
2659 | ps = None | |
2660 | fallback = None |
|
2660 | fallback = None | |
2661 | pat = parameter_s[2:] |
|
2661 | pat = parameter_s[2:] | |
2662 | dh = self.shell.user_ns['_dh'] |
|
2662 | dh = self.shell.user_ns['_dh'] | |
2663 | # first search only by basename (last component) |
|
2663 | # first search only by basename (last component) | |
2664 | for ent in reversed(dh): |
|
2664 | for ent in reversed(dh): | |
2665 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2665 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2666 | ps = ent |
|
2666 | ps = ent | |
2667 | break |
|
2667 | break | |
2668 |
|
2668 | |||
2669 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2669 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2670 | fallback = ent |
|
2670 | fallback = ent | |
2671 |
|
2671 | |||
2672 | # if we have no last part match, pick the first full path match |
|
2672 | # if we have no last part match, pick the first full path match | |
2673 | if ps is None: |
|
2673 | if ps is None: | |
2674 | ps = fallback |
|
2674 | ps = fallback | |
2675 |
|
2675 | |||
2676 | if ps is None: |
|
2676 | if ps is None: | |
2677 | print "No matching entry in directory history" |
|
2677 | print "No matching entry in directory history" | |
2678 | return |
|
2678 | return | |
2679 | else: |
|
2679 | else: | |
2680 | opts = {} |
|
2680 | opts = {} | |
2681 |
|
2681 | |||
2682 |
|
2682 | |||
2683 | else: |
|
2683 | else: | |
2684 | #turn all non-space-escaping backslashes to slashes, |
|
2684 | #turn all non-space-escaping backslashes to slashes, | |
2685 | # for c:\windows\directory\names\ |
|
2685 | # for c:\windows\directory\names\ | |
2686 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2686 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2687 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2687 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2688 | # jump to previous |
|
2688 | # jump to previous | |
2689 | if ps == '-': |
|
2689 | if ps == '-': | |
2690 | try: |
|
2690 | try: | |
2691 | ps = self.shell.user_ns['_dh'][-2] |
|
2691 | ps = self.shell.user_ns['_dh'][-2] | |
2692 | except IndexError: |
|
2692 | except IndexError: | |
2693 | raise UsageError('%cd -: No previous directory to change to.') |
|
2693 | raise UsageError('%cd -: No previous directory to change to.') | |
2694 | # jump to bookmark if needed |
|
2694 | # jump to bookmark if needed | |
2695 | else: |
|
2695 | else: | |
2696 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2696 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2697 | bkms = self.db.get('bookmarks', {}) |
|
2697 | bkms = self.db.get('bookmarks', {}) | |
2698 |
|
2698 | |||
2699 | if bkms.has_key(ps): |
|
2699 | if bkms.has_key(ps): | |
2700 | target = bkms[ps] |
|
2700 | target = bkms[ps] | |
2701 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2701 | print '(bookmark:%s) -> %s' % (ps,target) | |
2702 | ps = target |
|
2702 | ps = target | |
2703 | else: |
|
2703 | else: | |
2704 | if opts.has_key('b'): |
|
2704 | if opts.has_key('b'): | |
2705 | raise UsageError("Bookmark '%s' not found. " |
|
2705 | raise UsageError("Bookmark '%s' not found. " | |
2706 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2706 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2707 |
|
2707 | |||
2708 | # at this point ps should point to the target dir |
|
2708 | # at this point ps should point to the target dir | |
2709 | if ps: |
|
2709 | if ps: | |
2710 | try: |
|
2710 | try: | |
2711 | os.chdir(os.path.expanduser(ps)) |
|
2711 | os.chdir(os.path.expanduser(ps)) | |
2712 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2712 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2713 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2713 | set_term_title('IPython: ' + abbrev_cwd()) | |
2714 | except OSError: |
|
2714 | except OSError: | |
2715 | print sys.exc_info()[1] |
|
2715 | print sys.exc_info()[1] | |
2716 | else: |
|
2716 | else: | |
2717 | cwd = os.getcwd() |
|
2717 | cwd = os.getcwd() | |
2718 | dhist = self.shell.user_ns['_dh'] |
|
2718 | dhist = self.shell.user_ns['_dh'] | |
2719 | if oldcwd != cwd: |
|
2719 | if oldcwd != cwd: | |
2720 | dhist.append(cwd) |
|
2720 | dhist.append(cwd) | |
2721 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2721 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2722 |
|
2722 | |||
2723 | else: |
|
2723 | else: | |
2724 | os.chdir(self.shell.home_dir) |
|
2724 | os.chdir(self.shell.home_dir) | |
2725 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2725 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2726 | set_term_title('IPython: ' + '~') |
|
2726 | set_term_title('IPython: ' + '~') | |
2727 | cwd = os.getcwd() |
|
2727 | cwd = os.getcwd() | |
2728 | dhist = self.shell.user_ns['_dh'] |
|
2728 | dhist = self.shell.user_ns['_dh'] | |
2729 |
|
2729 | |||
2730 | if oldcwd != cwd: |
|
2730 | if oldcwd != cwd: | |
2731 | dhist.append(cwd) |
|
2731 | dhist.append(cwd) | |
2732 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2732 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2733 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2733 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2734 | print self.shell.user_ns['_dh'][-1] |
|
2734 | print self.shell.user_ns['_dh'][-1] | |
2735 |
|
2735 | |||
2736 |
|
2736 | |||
2737 | def magic_env(self, parameter_s=''): |
|
2737 | def magic_env(self, parameter_s=''): | |
2738 | """List environment variables.""" |
|
2738 | """List environment variables.""" | |
2739 |
|
2739 | |||
2740 | return os.environ.data |
|
2740 | return os.environ.data | |
2741 |
|
2741 | |||
2742 | def magic_pushd(self, parameter_s=''): |
|
2742 | def magic_pushd(self, parameter_s=''): | |
2743 | """Place the current dir on stack and change directory. |
|
2743 | """Place the current dir on stack and change directory. | |
2744 |
|
2744 | |||
2745 | Usage:\\ |
|
2745 | Usage:\\ | |
2746 | %pushd ['dirname'] |
|
2746 | %pushd ['dirname'] | |
2747 | """ |
|
2747 | """ | |
2748 |
|
2748 | |||
2749 | dir_s = self.shell.dir_stack |
|
2749 | dir_s = self.shell.dir_stack | |
2750 | tgt = os.path.expanduser(parameter_s) |
|
2750 | tgt = os.path.expanduser(parameter_s) | |
2751 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2751 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2752 | if tgt: |
|
2752 | if tgt: | |
2753 | self.magic_cd(parameter_s) |
|
2753 | self.magic_cd(parameter_s) | |
2754 | dir_s.insert(0,cwd) |
|
2754 | dir_s.insert(0,cwd) | |
2755 | return self.magic_dirs() |
|
2755 | return self.magic_dirs() | |
2756 |
|
2756 | |||
2757 | def magic_popd(self, parameter_s=''): |
|
2757 | def magic_popd(self, parameter_s=''): | |
2758 | """Change to directory popped off the top of the stack. |
|
2758 | """Change to directory popped off the top of the stack. | |
2759 | """ |
|
2759 | """ | |
2760 | if not self.shell.dir_stack: |
|
2760 | if not self.shell.dir_stack: | |
2761 | raise UsageError("%popd on empty stack") |
|
2761 | raise UsageError("%popd on empty stack") | |
2762 | top = self.shell.dir_stack.pop(0) |
|
2762 | top = self.shell.dir_stack.pop(0) | |
2763 | self.magic_cd(top) |
|
2763 | self.magic_cd(top) | |
2764 | print "popd ->",top |
|
2764 | print "popd ->",top | |
2765 |
|
2765 | |||
2766 | def magic_dirs(self, parameter_s=''): |
|
2766 | def magic_dirs(self, parameter_s=''): | |
2767 | """Return the current directory stack.""" |
|
2767 | """Return the current directory stack.""" | |
2768 |
|
2768 | |||
2769 | return self.shell.dir_stack |
|
2769 | return self.shell.dir_stack | |
2770 |
|
2770 | |||
2771 | def magic_dhist(self, parameter_s=''): |
|
2771 | def magic_dhist(self, parameter_s=''): | |
2772 | """Print your history of visited directories. |
|
2772 | """Print your history of visited directories. | |
2773 |
|
2773 | |||
2774 | %dhist -> print full history\\ |
|
2774 | %dhist -> print full history\\ | |
2775 | %dhist n -> print last n entries only\\ |
|
2775 | %dhist n -> print last n entries only\\ | |
2776 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2776 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2777 |
|
2777 | |||
2778 | This history is automatically maintained by the %cd command, and |
|
2778 | This history is automatically maintained by the %cd command, and | |
2779 | always available as the global list variable _dh. You can use %cd -<n> |
|
2779 | always available as the global list variable _dh. You can use %cd -<n> | |
2780 | to go to directory number <n>. |
|
2780 | to go to directory number <n>. | |
2781 |
|
2781 | |||
2782 | Note that most of time, you should view directory history by entering |
|
2782 | Note that most of time, you should view directory history by entering | |
2783 | cd -<TAB>. |
|
2783 | cd -<TAB>. | |
2784 |
|
2784 | |||
2785 | """ |
|
2785 | """ | |
2786 |
|
2786 | |||
2787 | dh = self.shell.user_ns['_dh'] |
|
2787 | dh = self.shell.user_ns['_dh'] | |
2788 | if parameter_s: |
|
2788 | if parameter_s: | |
2789 | try: |
|
2789 | try: | |
2790 | args = map(int,parameter_s.split()) |
|
2790 | args = map(int,parameter_s.split()) | |
2791 | except: |
|
2791 | except: | |
2792 | self.arg_err(Magic.magic_dhist) |
|
2792 | self.arg_err(Magic.magic_dhist) | |
2793 | return |
|
2793 | return | |
2794 | if len(args) == 1: |
|
2794 | if len(args) == 1: | |
2795 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2795 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2796 | elif len(args) == 2: |
|
2796 | elif len(args) == 2: | |
2797 | ini,fin = args |
|
2797 | ini,fin = args | |
2798 | else: |
|
2798 | else: | |
2799 | self.arg_err(Magic.magic_dhist) |
|
2799 | self.arg_err(Magic.magic_dhist) | |
2800 | return |
|
2800 | return | |
2801 | else: |
|
2801 | else: | |
2802 | ini,fin = 0,len(dh) |
|
2802 | ini,fin = 0,len(dh) | |
2803 | nlprint(dh, |
|
2803 | nlprint(dh, | |
2804 | header = 'Directory history (kept in _dh)', |
|
2804 | header = 'Directory history (kept in _dh)', | |
2805 | start=ini,stop=fin) |
|
2805 | start=ini,stop=fin) | |
2806 |
|
2806 | |||
2807 | @testdec.skip_doctest |
|
2807 | @testdec.skip_doctest | |
2808 | def magic_sc(self, parameter_s=''): |
|
2808 | def magic_sc(self, parameter_s=''): | |
2809 | """Shell capture - execute a shell command and capture its output. |
|
2809 | """Shell capture - execute a shell command and capture its output. | |
2810 |
|
2810 | |||
2811 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2811 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2812 |
|
2812 | |||
2813 | You should use the form 'var = !command' instead. Example: |
|
2813 | You should use the form 'var = !command' instead. Example: | |
2814 |
|
2814 | |||
2815 | "%sc -l myfiles = ls ~" should now be written as |
|
2815 | "%sc -l myfiles = ls ~" should now be written as | |
2816 |
|
2816 | |||
2817 | "myfiles = !ls ~" |
|
2817 | "myfiles = !ls ~" | |
2818 |
|
2818 | |||
2819 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2819 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2820 | below. |
|
2820 | below. | |
2821 |
|
2821 | |||
2822 | -- |
|
2822 | -- | |
2823 | %sc [options] varname=command |
|
2823 | %sc [options] varname=command | |
2824 |
|
2824 | |||
2825 | IPython will run the given command using commands.getoutput(), and |
|
2825 | IPython will run the given command using commands.getoutput(), and | |
2826 | will then update the user's interactive namespace with a variable |
|
2826 | will then update the user's interactive namespace with a variable | |
2827 | called varname, containing the value of the call. Your command can |
|
2827 | called varname, containing the value of the call. Your command can | |
2828 | contain shell wildcards, pipes, etc. |
|
2828 | contain shell wildcards, pipes, etc. | |
2829 |
|
2829 | |||
2830 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2830 | The '=' sign in the syntax is mandatory, and the variable name you | |
2831 | supply must follow Python's standard conventions for valid names. |
|
2831 | supply must follow Python's standard conventions for valid names. | |
2832 |
|
2832 | |||
2833 | (A special format without variable name exists for internal use) |
|
2833 | (A special format without variable name exists for internal use) | |
2834 |
|
2834 | |||
2835 | Options: |
|
2835 | Options: | |
2836 |
|
2836 | |||
2837 | -l: list output. Split the output on newlines into a list before |
|
2837 | -l: list output. Split the output on newlines into a list before | |
2838 | assigning it to the given variable. By default the output is stored |
|
2838 | assigning it to the given variable. By default the output is stored | |
2839 | as a single string. |
|
2839 | as a single string. | |
2840 |
|
2840 | |||
2841 | -v: verbose. Print the contents of the variable. |
|
2841 | -v: verbose. Print the contents of the variable. | |
2842 |
|
2842 | |||
2843 | In most cases you should not need to split as a list, because the |
|
2843 | In most cases you should not need to split as a list, because the | |
2844 | returned value is a special type of string which can automatically |
|
2844 | returned value is a special type of string which can automatically | |
2845 | provide its contents either as a list (split on newlines) or as a |
|
2845 | provide its contents either as a list (split on newlines) or as a | |
2846 | space-separated string. These are convenient, respectively, either |
|
2846 | space-separated string. These are convenient, respectively, either | |
2847 | for sequential processing or to be passed to a shell command. |
|
2847 | for sequential processing or to be passed to a shell command. | |
2848 |
|
2848 | |||
2849 | For example: |
|
2849 | For example: | |
2850 |
|
2850 | |||
2851 | # all-random |
|
2851 | # all-random | |
2852 |
|
2852 | |||
2853 | # Capture into variable a |
|
2853 | # Capture into variable a | |
2854 | In [1]: sc a=ls *py |
|
2854 | In [1]: sc a=ls *py | |
2855 |
|
2855 | |||
2856 | # a is a string with embedded newlines |
|
2856 | # a is a string with embedded newlines | |
2857 | In [2]: a |
|
2857 | In [2]: a | |
2858 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2858 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2859 |
|
2859 | |||
2860 | # which can be seen as a list: |
|
2860 | # which can be seen as a list: | |
2861 | In [3]: a.l |
|
2861 | In [3]: a.l | |
2862 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2862 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2863 |
|
2863 | |||
2864 | # or as a whitespace-separated string: |
|
2864 | # or as a whitespace-separated string: | |
2865 | In [4]: a.s |
|
2865 | In [4]: a.s | |
2866 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2866 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2867 |
|
2867 | |||
2868 | # a.s is useful to pass as a single command line: |
|
2868 | # a.s is useful to pass as a single command line: | |
2869 | In [5]: !wc -l $a.s |
|
2869 | In [5]: !wc -l $a.s | |
2870 | 146 setup.py |
|
2870 | 146 setup.py | |
2871 | 130 win32_manual_post_install.py |
|
2871 | 130 win32_manual_post_install.py | |
2872 | 276 total |
|
2872 | 276 total | |
2873 |
|
2873 | |||
2874 | # while the list form is useful to loop over: |
|
2874 | # while the list form is useful to loop over: | |
2875 | In [6]: for f in a.l: |
|
2875 | In [6]: for f in a.l: | |
2876 | ...: !wc -l $f |
|
2876 | ...: !wc -l $f | |
2877 | ...: |
|
2877 | ...: | |
2878 | 146 setup.py |
|
2878 | 146 setup.py | |
2879 | 130 win32_manual_post_install.py |
|
2879 | 130 win32_manual_post_install.py | |
2880 |
|
2880 | |||
2881 | Similiarly, the lists returned by the -l option are also special, in |
|
2881 | Similiarly, the lists returned by the -l option are also special, in | |
2882 | the sense that you can equally invoke the .s attribute on them to |
|
2882 | the sense that you can equally invoke the .s attribute on them to | |
2883 | automatically get a whitespace-separated string from their contents: |
|
2883 | automatically get a whitespace-separated string from their contents: | |
2884 |
|
2884 | |||
2885 | In [7]: sc -l b=ls *py |
|
2885 | In [7]: sc -l b=ls *py | |
2886 |
|
2886 | |||
2887 | In [8]: b |
|
2887 | In [8]: b | |
2888 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2888 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2889 |
|
2889 | |||
2890 | In [9]: b.s |
|
2890 | In [9]: b.s | |
2891 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2891 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2892 |
|
2892 | |||
2893 | In summary, both the lists and strings used for ouptut capture have |
|
2893 | In summary, both the lists and strings used for ouptut capture have | |
2894 | the following special attributes: |
|
2894 | the following special attributes: | |
2895 |
|
2895 | |||
2896 | .l (or .list) : value as list. |
|
2896 | .l (or .list) : value as list. | |
2897 | .n (or .nlstr): value as newline-separated string. |
|
2897 | .n (or .nlstr): value as newline-separated string. | |
2898 | .s (or .spstr): value as space-separated string. |
|
2898 | .s (or .spstr): value as space-separated string. | |
2899 | """ |
|
2899 | """ | |
2900 |
|
2900 | |||
2901 | opts,args = self.parse_options(parameter_s,'lv') |
|
2901 | opts,args = self.parse_options(parameter_s,'lv') | |
2902 | # Try to get a variable name and command to run |
|
2902 | # Try to get a variable name and command to run | |
2903 | try: |
|
2903 | try: | |
2904 | # the variable name must be obtained from the parse_options |
|
2904 | # the variable name must be obtained from the parse_options | |
2905 | # output, which uses shlex.split to strip options out. |
|
2905 | # output, which uses shlex.split to strip options out. | |
2906 | var,_ = args.split('=',1) |
|
2906 | var,_ = args.split('=',1) | |
2907 | var = var.strip() |
|
2907 | var = var.strip() | |
2908 | # But the the command has to be extracted from the original input |
|
2908 | # But the the command has to be extracted from the original input | |
2909 | # parameter_s, not on what parse_options returns, to avoid the |
|
2909 | # parameter_s, not on what parse_options returns, to avoid the | |
2910 | # quote stripping which shlex.split performs on it. |
|
2910 | # quote stripping which shlex.split performs on it. | |
2911 | _,cmd = parameter_s.split('=',1) |
|
2911 | _,cmd = parameter_s.split('=',1) | |
2912 | except ValueError: |
|
2912 | except ValueError: | |
2913 | var,cmd = '','' |
|
2913 | var,cmd = '','' | |
2914 | # If all looks ok, proceed |
|
2914 | # If all looks ok, proceed | |
2915 | split = 'l' in opts |
|
2915 | split = 'l' in opts | |
2916 | out = self.shell.getoutput(cmd, split=split) |
|
2916 | out = self.shell.getoutput(cmd, split=split) | |
2917 | if opts.has_key('v'): |
|
2917 | if opts.has_key('v'): | |
2918 | print '%s ==\n%s' % (var,pformat(out)) |
|
2918 | print '%s ==\n%s' % (var,pformat(out)) | |
2919 | if var: |
|
2919 | if var: | |
2920 | self.shell.user_ns.update({var:out}) |
|
2920 | self.shell.user_ns.update({var:out}) | |
2921 | else: |
|
2921 | else: | |
2922 | return out |
|
2922 | return out | |
2923 |
|
2923 | |||
2924 | def magic_sx(self, parameter_s=''): |
|
2924 | def magic_sx(self, parameter_s=''): | |
2925 | """Shell execute - run a shell command and capture its output. |
|
2925 | """Shell execute - run a shell command and capture its output. | |
2926 |
|
2926 | |||
2927 | %sx command |
|
2927 | %sx command | |
2928 |
|
2928 | |||
2929 | IPython will run the given command using commands.getoutput(), and |
|
2929 | IPython will run the given command using commands.getoutput(), and | |
2930 | return the result formatted as a list (split on '\\n'). Since the |
|
2930 | return the result formatted as a list (split on '\\n'). Since the | |
2931 | output is _returned_, it will be stored in ipython's regular output |
|
2931 | output is _returned_, it will be stored in ipython's regular output | |
2932 | cache Out[N] and in the '_N' automatic variables. |
|
2932 | cache Out[N] and in the '_N' automatic variables. | |
2933 |
|
2933 | |||
2934 | Notes: |
|
2934 | Notes: | |
2935 |
|
2935 | |||
2936 | 1) If an input line begins with '!!', then %sx is automatically |
|
2936 | 1) If an input line begins with '!!', then %sx is automatically | |
2937 | invoked. That is, while: |
|
2937 | invoked. That is, while: | |
2938 | !ls |
|
2938 | !ls | |
2939 | causes ipython to simply issue system('ls'), typing |
|
2939 | causes ipython to simply issue system('ls'), typing | |
2940 | !!ls |
|
2940 | !!ls | |
2941 | is a shorthand equivalent to: |
|
2941 | is a shorthand equivalent to: | |
2942 | %sx ls |
|
2942 | %sx ls | |
2943 |
|
2943 | |||
2944 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2944 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2945 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2945 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2946 | to process line-oriented shell output via further python commands. |
|
2946 | to process line-oriented shell output via further python commands. | |
2947 | %sc is meant to provide much finer control, but requires more |
|
2947 | %sc is meant to provide much finer control, but requires more | |
2948 | typing. |
|
2948 | typing. | |
2949 |
|
2949 | |||
2950 | 3) Just like %sc -l, this is a list with special attributes: |
|
2950 | 3) Just like %sc -l, this is a list with special attributes: | |
2951 |
|
2951 | |||
2952 | .l (or .list) : value as list. |
|
2952 | .l (or .list) : value as list. | |
2953 | .n (or .nlstr): value as newline-separated string. |
|
2953 | .n (or .nlstr): value as newline-separated string. | |
2954 | .s (or .spstr): value as whitespace-separated string. |
|
2954 | .s (or .spstr): value as whitespace-separated string. | |
2955 |
|
2955 | |||
2956 | This is very useful when trying to use such lists as arguments to |
|
2956 | This is very useful when trying to use such lists as arguments to | |
2957 | system commands.""" |
|
2957 | system commands.""" | |
2958 |
|
2958 | |||
2959 | if parameter_s: |
|
2959 | if parameter_s: | |
2960 | return self.shell.getoutput(parameter_s) |
|
2960 | return self.shell.getoutput(parameter_s) | |
2961 |
|
2961 | |||
2962 | def magic_r(self, parameter_s=''): |
|
2962 | def magic_r(self, parameter_s=''): | |
2963 | """Repeat previous input. |
|
2963 | """Repeat previous input. | |
2964 |
|
2964 | |||
2965 | Note: Consider using the more powerfull %rep instead! |
|
2965 | Note: Consider using the more powerfull %rep instead! | |
2966 |
|
2966 | |||
2967 | If given an argument, repeats the previous command which starts with |
|
2967 | If given an argument, repeats the previous command which starts with | |
2968 | the same string, otherwise it just repeats the previous input. |
|
2968 | the same string, otherwise it just repeats the previous input. | |
2969 |
|
2969 | |||
2970 | Shell escaped commands (with ! as first character) are not recognized |
|
2970 | Shell escaped commands (with ! as first character) are not recognized | |
2971 | by this system, only pure python code and magic commands. |
|
2971 | by this system, only pure python code and magic commands. | |
2972 | """ |
|
2972 | """ | |
2973 |
|
2973 | |||
2974 | start = parameter_s.strip() |
|
2974 | start = parameter_s.strip() | |
2975 | esc_magic = ESC_MAGIC |
|
2975 | esc_magic = ESC_MAGIC | |
2976 | # Identify magic commands even if automagic is on (which means |
|
2976 | # Identify magic commands even if automagic is on (which means | |
2977 | # the in-memory version is different from that typed by the user). |
|
2977 | # the in-memory version is different from that typed by the user). | |
2978 | if self.shell.automagic: |
|
2978 | if self.shell.automagic: | |
2979 | start_magic = esc_magic+start |
|
2979 | start_magic = esc_magic+start | |
2980 | else: |
|
2980 | else: | |
2981 | start_magic = start |
|
2981 | start_magic = start | |
2982 | # Look through the input history in reverse |
|
2982 | # Look through the input history in reverse | |
2983 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): |
|
2983 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): | |
2984 | input = self.shell.history_manager.input_hist_parsed[n] |
|
2984 | input = self.shell.history_manager.input_hist_parsed[n] | |
2985 | # skip plain 'r' lines so we don't recurse to infinity |
|
2985 | # skip plain 'r' lines so we don't recurse to infinity | |
2986 | if input != '_ip.magic("r")\n' and \ |
|
2986 | if input != '_ip.magic("r")\n' and \ | |
2987 | (input.startswith(start) or input.startswith(start_magic)): |
|
2987 | (input.startswith(start) or input.startswith(start_magic)): | |
2988 | #print 'match',`input` # dbg |
|
2988 | #print 'match',`input` # dbg | |
2989 | print 'Executing:',input, |
|
2989 | print 'Executing:',input, | |
2990 | self.shell.run_cell(input) |
|
2990 | self.shell.run_cell(input) | |
2991 | return |
|
2991 | return | |
2992 | print 'No previous input matching `%s` found.' % start |
|
2992 | print 'No previous input matching `%s` found.' % start | |
2993 |
|
2993 | |||
2994 |
|
2994 | |||
2995 | def magic_bookmark(self, parameter_s=''): |
|
2995 | def magic_bookmark(self, parameter_s=''): | |
2996 | """Manage IPython's bookmark system. |
|
2996 | """Manage IPython's bookmark system. | |
2997 |
|
2997 | |||
2998 | %bookmark <name> - set bookmark to current dir |
|
2998 | %bookmark <name> - set bookmark to current dir | |
2999 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2999 | %bookmark <name> <dir> - set bookmark to <dir> | |
3000 | %bookmark -l - list all bookmarks |
|
3000 | %bookmark -l - list all bookmarks | |
3001 | %bookmark -d <name> - remove bookmark |
|
3001 | %bookmark -d <name> - remove bookmark | |
3002 | %bookmark -r - remove all bookmarks |
|
3002 | %bookmark -r - remove all bookmarks | |
3003 |
|
3003 | |||
3004 | You can later on access a bookmarked folder with: |
|
3004 | You can later on access a bookmarked folder with: | |
3005 | %cd -b <name> |
|
3005 | %cd -b <name> | |
3006 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3006 | or simply '%cd <name>' if there is no directory called <name> AND | |
3007 | there is such a bookmark defined. |
|
3007 | there is such a bookmark defined. | |
3008 |
|
3008 | |||
3009 | Your bookmarks persist through IPython sessions, but they are |
|
3009 | Your bookmarks persist through IPython sessions, but they are | |
3010 | associated with each profile.""" |
|
3010 | associated with each profile.""" | |
3011 |
|
3011 | |||
3012 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3012 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3013 | if len(args) > 2: |
|
3013 | if len(args) > 2: | |
3014 | raise UsageError("%bookmark: too many arguments") |
|
3014 | raise UsageError("%bookmark: too many arguments") | |
3015 |
|
3015 | |||
3016 | bkms = self.db.get('bookmarks',{}) |
|
3016 | bkms = self.db.get('bookmarks',{}) | |
3017 |
|
3017 | |||
3018 | if opts.has_key('d'): |
|
3018 | if opts.has_key('d'): | |
3019 | try: |
|
3019 | try: | |
3020 | todel = args[0] |
|
3020 | todel = args[0] | |
3021 | except IndexError: |
|
3021 | except IndexError: | |
3022 | raise UsageError( |
|
3022 | raise UsageError( | |
3023 | "%bookmark -d: must provide a bookmark to delete") |
|
3023 | "%bookmark -d: must provide a bookmark to delete") | |
3024 | else: |
|
3024 | else: | |
3025 | try: |
|
3025 | try: | |
3026 | del bkms[todel] |
|
3026 | del bkms[todel] | |
3027 | except KeyError: |
|
3027 | except KeyError: | |
3028 | raise UsageError( |
|
3028 | raise UsageError( | |
3029 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3029 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3030 |
|
3030 | |||
3031 | elif opts.has_key('r'): |
|
3031 | elif opts.has_key('r'): | |
3032 | bkms = {} |
|
3032 | bkms = {} | |
3033 | elif opts.has_key('l'): |
|
3033 | elif opts.has_key('l'): | |
3034 | bks = bkms.keys() |
|
3034 | bks = bkms.keys() | |
3035 | bks.sort() |
|
3035 | bks.sort() | |
3036 | if bks: |
|
3036 | if bks: | |
3037 | size = max(map(len,bks)) |
|
3037 | size = max(map(len,bks)) | |
3038 | else: |
|
3038 | else: | |
3039 | size = 0 |
|
3039 | size = 0 | |
3040 | fmt = '%-'+str(size)+'s -> %s' |
|
3040 | fmt = '%-'+str(size)+'s -> %s' | |
3041 | print 'Current bookmarks:' |
|
3041 | print 'Current bookmarks:' | |
3042 | for bk in bks: |
|
3042 | for bk in bks: | |
3043 | print fmt % (bk,bkms[bk]) |
|
3043 | print fmt % (bk,bkms[bk]) | |
3044 | else: |
|
3044 | else: | |
3045 | if not args: |
|
3045 | if not args: | |
3046 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3046 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3047 | elif len(args)==1: |
|
3047 | elif len(args)==1: | |
3048 | bkms[args[0]] = os.getcwd() |
|
3048 | bkms[args[0]] = os.getcwd() | |
3049 | elif len(args)==2: |
|
3049 | elif len(args)==2: | |
3050 | bkms[args[0]] = args[1] |
|
3050 | bkms[args[0]] = args[1] | |
3051 | self.db['bookmarks'] = bkms |
|
3051 | self.db['bookmarks'] = bkms | |
3052 |
|
3052 | |||
3053 | def magic_pycat(self, parameter_s=''): |
|
3053 | def magic_pycat(self, parameter_s=''): | |
3054 | """Show a syntax-highlighted file through a pager. |
|
3054 | """Show a syntax-highlighted file through a pager. | |
3055 |
|
3055 | |||
3056 | This magic is similar to the cat utility, but it will assume the file |
|
3056 | This magic is similar to the cat utility, but it will assume the file | |
3057 | to be Python source and will show it with syntax highlighting. """ |
|
3057 | to be Python source and will show it with syntax highlighting. """ | |
3058 |
|
3058 | |||
3059 | try: |
|
3059 | try: | |
3060 | filename = get_py_filename(parameter_s) |
|
3060 | filename = get_py_filename(parameter_s) | |
3061 | cont = file_read(filename) |
|
3061 | cont = file_read(filename) | |
3062 | except IOError: |
|
3062 | except IOError: | |
3063 | try: |
|
3063 | try: | |
3064 | cont = eval(parameter_s,self.user_ns) |
|
3064 | cont = eval(parameter_s,self.user_ns) | |
3065 | except NameError: |
|
3065 | except NameError: | |
3066 | cont = None |
|
3066 | cont = None | |
3067 | if cont is None: |
|
3067 | if cont is None: | |
3068 | print "Error: no such file or variable" |
|
3068 | print "Error: no such file or variable" | |
3069 | return |
|
3069 | return | |
3070 |
|
3070 | |||
3071 | page.page(self.shell.pycolorize(cont)) |
|
3071 | page.page(self.shell.pycolorize(cont)) | |
3072 |
|
3072 | |||
3073 | def _rerun_pasted(self): |
|
3073 | def _rerun_pasted(self): | |
3074 | """ Rerun a previously pasted command. |
|
3074 | """ Rerun a previously pasted command. | |
3075 | """ |
|
3075 | """ | |
3076 | b = self.user_ns.get('pasted_block', None) |
|
3076 | b = self.user_ns.get('pasted_block', None) | |
3077 | if b is None: |
|
3077 | if b is None: | |
3078 | raise UsageError('No previous pasted block available') |
|
3078 | raise UsageError('No previous pasted block available') | |
3079 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3079 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3080 | exec b in self.user_ns |
|
3080 | exec b in self.user_ns | |
3081 |
|
3081 | |||
3082 | def _get_pasted_lines(self, sentinel): |
|
3082 | def _get_pasted_lines(self, sentinel): | |
3083 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3083 | """ Yield pasted lines until the user enters the given sentinel value. | |
3084 | """ |
|
3084 | """ | |
3085 | from IPython.core import interactiveshell |
|
3085 | from IPython.core import interactiveshell | |
3086 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3086 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3087 | while True: |
|
3087 | while True: | |
3088 | l = interactiveshell.raw_input_original(':') |
|
3088 | l = interactiveshell.raw_input_original(':') | |
3089 | if l == sentinel: |
|
3089 | if l == sentinel: | |
3090 | return |
|
3090 | return | |
3091 | else: |
|
3091 | else: | |
3092 | yield l |
|
3092 | yield l | |
3093 |
|
3093 | |||
3094 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3094 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3095 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3095 | """ Strip non-code parts of a sequence of lines to return a block of | |
3096 | code. |
|
3096 | code. | |
3097 | """ |
|
3097 | """ | |
3098 | # Regular expressions that declare text we strip from the input: |
|
3098 | # Regular expressions that declare text we strip from the input: | |
3099 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3099 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3100 | r'^\s*(\s?>)+', # Python input prompt |
|
3100 | r'^\s*(\s?>)+', # Python input prompt | |
3101 | r'^\s*\.{3,}', # Continuation prompts |
|
3101 | r'^\s*\.{3,}', # Continuation prompts | |
3102 | r'^\++', |
|
3102 | r'^\++', | |
3103 | ] |
|
3103 | ] | |
3104 |
|
3104 | |||
3105 | strip_from_start = map(re.compile,strip_re) |
|
3105 | strip_from_start = map(re.compile,strip_re) | |
3106 |
|
3106 | |||
3107 | lines = [] |
|
3107 | lines = [] | |
3108 | for l in raw_lines: |
|
3108 | for l in raw_lines: | |
3109 | for pat in strip_from_start: |
|
3109 | for pat in strip_from_start: | |
3110 | l = pat.sub('',l) |
|
3110 | l = pat.sub('',l) | |
3111 | lines.append(l) |
|
3111 | lines.append(l) | |
3112 |
|
3112 | |||
3113 | block = "\n".join(lines) + '\n' |
|
3113 | block = "\n".join(lines) + '\n' | |
3114 | #print "block:\n",block |
|
3114 | #print "block:\n",block | |
3115 | return block |
|
3115 | return block | |
3116 |
|
3116 | |||
3117 | def _execute_block(self, block, par): |
|
3117 | def _execute_block(self, block, par): | |
3118 | """ Execute a block, or store it in a variable, per the user's request. |
|
3118 | """ Execute a block, or store it in a variable, per the user's request. | |
3119 | """ |
|
3119 | """ | |
3120 | if not par: |
|
3120 | if not par: | |
3121 | b = textwrap.dedent(block) |
|
3121 | b = textwrap.dedent(block) | |
3122 | self.user_ns['pasted_block'] = b |
|
3122 | self.user_ns['pasted_block'] = b | |
3123 | exec b in self.user_ns |
|
3123 | exec b in self.user_ns | |
3124 | else: |
|
3124 | else: | |
3125 | self.user_ns[par] = SList(block.splitlines()) |
|
3125 | self.user_ns[par] = SList(block.splitlines()) | |
3126 | print "Block assigned to '%s'" % par |
|
3126 | print "Block assigned to '%s'" % par | |
3127 |
|
3127 | |||
3128 | def magic_quickref(self,arg): |
|
3128 | def magic_quickref(self,arg): | |
3129 | """ Show a quick reference sheet """ |
|
3129 | """ Show a quick reference sheet """ | |
3130 | import IPython.core.usage |
|
3130 | import IPython.core.usage | |
3131 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3131 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3132 |
|
3132 | |||
3133 | page.page(qr) |
|
3133 | page.page(qr) | |
3134 |
|
3134 | |||
3135 | def magic_doctest_mode(self,parameter_s=''): |
|
3135 | def magic_doctest_mode(self,parameter_s=''): | |
3136 | """Toggle doctest mode on and off. |
|
3136 | """Toggle doctest mode on and off. | |
3137 |
|
3137 | |||
3138 | This mode is intended to make IPython behave as much as possible like a |
|
3138 | This mode is intended to make IPython behave as much as possible like a | |
3139 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3139 | plain Python shell, from the perspective of how its prompts, exceptions | |
3140 | and output look. This makes it easy to copy and paste parts of a |
|
3140 | and output look. This makes it easy to copy and paste parts of a | |
3141 | session into doctests. It does so by: |
|
3141 | session into doctests. It does so by: | |
3142 |
|
3142 | |||
3143 | - Changing the prompts to the classic ``>>>`` ones. |
|
3143 | - Changing the prompts to the classic ``>>>`` ones. | |
3144 | - Changing the exception reporting mode to 'Plain'. |
|
3144 | - Changing the exception reporting mode to 'Plain'. | |
3145 | - Disabling pretty-printing of output. |
|
3145 | - Disabling pretty-printing of output. | |
3146 |
|
3146 | |||
3147 | Note that IPython also supports the pasting of code snippets that have |
|
3147 | Note that IPython also supports the pasting of code snippets that have | |
3148 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3148 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3149 | doctests from files or docstrings (even if they have leading |
|
3149 | doctests from files or docstrings (even if they have leading | |
3150 | whitespace), and the code will execute correctly. You can then use |
|
3150 | whitespace), and the code will execute correctly. You can then use | |
3151 | '%history -t' to see the translated history; this will give you the |
|
3151 | '%history -t' to see the translated history; this will give you the | |
3152 | input after removal of all the leading prompts and whitespace, which |
|
3152 | input after removal of all the leading prompts and whitespace, which | |
3153 | can be pasted back into an editor. |
|
3153 | can be pasted back into an editor. | |
3154 |
|
3154 | |||
3155 | With these features, you can switch into this mode easily whenever you |
|
3155 | With these features, you can switch into this mode easily whenever you | |
3156 | need to do testing and changes to doctests, without having to leave |
|
3156 | need to do testing and changes to doctests, without having to leave | |
3157 | your existing IPython session. |
|
3157 | your existing IPython session. | |
3158 | """ |
|
3158 | """ | |
3159 |
|
3159 | |||
3160 | from IPython.utils.ipstruct import Struct |
|
3160 | from IPython.utils.ipstruct import Struct | |
3161 |
|
3161 | |||
3162 | # Shorthands |
|
3162 | # Shorthands | |
3163 | shell = self.shell |
|
3163 | shell = self.shell | |
3164 | oc = shell.displayhook |
|
3164 | oc = shell.displayhook | |
3165 | meta = shell.meta |
|
3165 | meta = shell.meta | |
|
3166 | disp_formatter = self.shell.display_formatter | |||
|
3167 | ptformatter = disp_formatter.formatters['text/plain'] | |||
3166 | # dstore is a data store kept in the instance metadata bag to track any |
|
3168 | # dstore is a data store kept in the instance metadata bag to track any | |
3167 | # changes we make, so we can undo them later. |
|
3169 | # changes we make, so we can undo them later. | |
3168 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3170 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3169 | save_dstore = dstore.setdefault |
|
3171 | save_dstore = dstore.setdefault | |
3170 |
|
3172 | |||
3171 | # save a few values we'll need to recover later |
|
3173 | # save a few values we'll need to recover later | |
3172 | mode = save_dstore('mode',False) |
|
3174 | mode = save_dstore('mode',False) | |
3173 |
save_dstore('rc_pprint', |
|
3175 | save_dstore('rc_pprint',ptformatter.pprint) | |
3174 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3176 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3175 | save_dstore('rc_separate_out',shell.separate_out) |
|
3177 | save_dstore('rc_separate_out',shell.separate_out) | |
3176 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3178 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3177 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3179 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3178 | save_dstore('rc_separate_in',shell.separate_in) |
|
3180 | save_dstore('rc_separate_in',shell.separate_in) | |
|
3181 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |||
3179 |
|
3182 | |||
3180 | if mode == False: |
|
3183 | if mode == False: | |
3181 | # turn on |
|
3184 | # turn on | |
3182 | oc.prompt1.p_template = '>>> ' |
|
3185 | oc.prompt1.p_template = '>>> ' | |
3183 | oc.prompt2.p_template = '... ' |
|
3186 | oc.prompt2.p_template = '... ' | |
3184 | oc.prompt_out.p_template = '' |
|
3187 | oc.prompt_out.p_template = '' | |
3185 |
|
3188 | |||
3186 | # Prompt separators like plain python |
|
3189 | # Prompt separators like plain python | |
3187 | oc.input_sep = oc.prompt1.sep = '' |
|
3190 | oc.input_sep = oc.prompt1.sep = '' | |
3188 | oc.output_sep = '' |
|
3191 | oc.output_sep = '' | |
3189 | oc.output_sep2 = '' |
|
3192 | oc.output_sep2 = '' | |
3190 |
|
3193 | |||
3191 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3194 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3192 | oc.prompt_out.pad_left = False |
|
3195 | oc.prompt_out.pad_left = False | |
3193 |
|
3196 | |||
3194 |
|
|
3197 | ptformatter.pprint = False | |
|
3198 | disp_formatter.plain_text_only = True | |||
3195 |
|
3199 | |||
3196 | shell.magic_xmode('Plain') |
|
3200 | shell.magic_xmode('Plain') | |
3197 | else: |
|
3201 | else: | |
3198 | # turn off |
|
3202 | # turn off | |
3199 | oc.prompt1.p_template = shell.prompt_in1 |
|
3203 | oc.prompt1.p_template = shell.prompt_in1 | |
3200 | oc.prompt2.p_template = shell.prompt_in2 |
|
3204 | oc.prompt2.p_template = shell.prompt_in2 | |
3201 | oc.prompt_out.p_template = shell.prompt_out |
|
3205 | oc.prompt_out.p_template = shell.prompt_out | |
3202 |
|
3206 | |||
3203 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3207 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3204 |
|
3208 | |||
3205 | oc.output_sep = dstore.rc_separate_out |
|
3209 | oc.output_sep = dstore.rc_separate_out | |
3206 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3210 | oc.output_sep2 = dstore.rc_separate_out2 | |
3207 |
|
3211 | |||
3208 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3212 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3209 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3213 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3210 |
|
3214 | |||
3211 |
|
|
3215 | ptformatter.pprint = dstore.rc_pprint | |
|
3216 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |||
3212 |
|
3217 | |||
3213 | shell.magic_xmode(dstore.xmode) |
|
3218 | shell.magic_xmode(dstore.xmode) | |
3214 |
|
3219 | |||
3215 | # Store new mode and inform |
|
3220 | # Store new mode and inform | |
3216 | dstore.mode = bool(1-int(mode)) |
|
3221 | dstore.mode = bool(1-int(mode)) | |
3217 | mode_label = ['OFF','ON'][dstore.mode] |
|
3222 | mode_label = ['OFF','ON'][dstore.mode] | |
3218 | print 'Doctest mode is:', mode_label |
|
3223 | print 'Doctest mode is:', mode_label | |
3219 |
|
3224 | |||
3220 | def magic_gui(self, parameter_s=''): |
|
3225 | def magic_gui(self, parameter_s=''): | |
3221 | """Enable or disable IPython GUI event loop integration. |
|
3226 | """Enable or disable IPython GUI event loop integration. | |
3222 |
|
3227 | |||
3223 | %gui [GUINAME] |
|
3228 | %gui [GUINAME] | |
3224 |
|
3229 | |||
3225 | This magic replaces IPython's threaded shells that were activated |
|
3230 | This magic replaces IPython's threaded shells that were activated | |
3226 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3231 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3227 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3232 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3228 | interrupts should work without any problems. The following toolkits |
|
3233 | interrupts should work without any problems. The following toolkits | |
3229 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3234 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3230 |
|
3235 | |||
3231 | %gui wx # enable wxPython event loop integration |
|
3236 | %gui wx # enable wxPython event loop integration | |
3232 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3237 | %gui qt4|qt # enable PyQt4 event loop integration | |
3233 | %gui gtk # enable PyGTK event loop integration |
|
3238 | %gui gtk # enable PyGTK event loop integration | |
3234 | %gui tk # enable Tk event loop integration |
|
3239 | %gui tk # enable Tk event loop integration | |
3235 | %gui # disable all event loop integration |
|
3240 | %gui # disable all event loop integration | |
3236 |
|
3241 | |||
3237 | WARNING: after any of these has been called you can simply create |
|
3242 | WARNING: after any of these has been called you can simply create | |
3238 | an application object, but DO NOT start the event loop yourself, as |
|
3243 | an application object, but DO NOT start the event loop yourself, as | |
3239 | we have already handled that. |
|
3244 | we have already handled that. | |
3240 | """ |
|
3245 | """ | |
3241 | from IPython.lib.inputhook import enable_gui |
|
3246 | from IPython.lib.inputhook import enable_gui | |
3242 | opts, arg = self.parse_options(parameter_s, '') |
|
3247 | opts, arg = self.parse_options(parameter_s, '') | |
3243 | if arg=='': arg = None |
|
3248 | if arg=='': arg = None | |
3244 | return enable_gui(arg) |
|
3249 | return enable_gui(arg) | |
3245 |
|
3250 | |||
3246 | def magic_load_ext(self, module_str): |
|
3251 | def magic_load_ext(self, module_str): | |
3247 | """Load an IPython extension by its module name.""" |
|
3252 | """Load an IPython extension by its module name.""" | |
3248 | return self.extension_manager.load_extension(module_str) |
|
3253 | return self.extension_manager.load_extension(module_str) | |
3249 |
|
3254 | |||
3250 | def magic_unload_ext(self, module_str): |
|
3255 | def magic_unload_ext(self, module_str): | |
3251 | """Unload an IPython extension by its module name.""" |
|
3256 | """Unload an IPython extension by its module name.""" | |
3252 | self.extension_manager.unload_extension(module_str) |
|
3257 | self.extension_manager.unload_extension(module_str) | |
3253 |
|
3258 | |||
3254 | def magic_reload_ext(self, module_str): |
|
3259 | def magic_reload_ext(self, module_str): | |
3255 | """Reload an IPython extension by its module name.""" |
|
3260 | """Reload an IPython extension by its module name.""" | |
3256 | self.extension_manager.reload_extension(module_str) |
|
3261 | self.extension_manager.reload_extension(module_str) | |
3257 |
|
3262 | |||
3258 | @testdec.skip_doctest |
|
3263 | @testdec.skip_doctest | |
3259 | def magic_install_profiles(self, s): |
|
3264 | def magic_install_profiles(self, s): | |
3260 | """Install the default IPython profiles into the .ipython dir. |
|
3265 | """Install the default IPython profiles into the .ipython dir. | |
3261 |
|
3266 | |||
3262 | If the default profiles have already been installed, they will not |
|
3267 | If the default profiles have already been installed, they will not | |
3263 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3268 | be overwritten. You can force overwriting them by using the ``-o`` | |
3264 | option:: |
|
3269 | option:: | |
3265 |
|
3270 | |||
3266 | In [1]: %install_profiles -o |
|
3271 | In [1]: %install_profiles -o | |
3267 | """ |
|
3272 | """ | |
3268 | if '-o' in s: |
|
3273 | if '-o' in s: | |
3269 | overwrite = True |
|
3274 | overwrite = True | |
3270 | else: |
|
3275 | else: | |
3271 | overwrite = False |
|
3276 | overwrite = False | |
3272 | from IPython.config import profile |
|
3277 | from IPython.config import profile | |
3273 | profile_dir = os.path.split(profile.__file__)[0] |
|
3278 | profile_dir = os.path.split(profile.__file__)[0] | |
3274 | ipython_dir = self.ipython_dir |
|
3279 | ipython_dir = self.ipython_dir | |
3275 | files = os.listdir(profile_dir) |
|
3280 | files = os.listdir(profile_dir) | |
3276 |
|
3281 | |||
3277 | to_install = [] |
|
3282 | to_install = [] | |
3278 | for f in files: |
|
3283 | for f in files: | |
3279 | if f.startswith('ipython_config'): |
|
3284 | if f.startswith('ipython_config'): | |
3280 | src = os.path.join(profile_dir, f) |
|
3285 | src = os.path.join(profile_dir, f) | |
3281 | dst = os.path.join(ipython_dir, f) |
|
3286 | dst = os.path.join(ipython_dir, f) | |
3282 | if (not os.path.isfile(dst)) or overwrite: |
|
3287 | if (not os.path.isfile(dst)) or overwrite: | |
3283 | to_install.append((f, src, dst)) |
|
3288 | to_install.append((f, src, dst)) | |
3284 | if len(to_install)>0: |
|
3289 | if len(to_install)>0: | |
3285 | print "Installing profiles to: ", ipython_dir |
|
3290 | print "Installing profiles to: ", ipython_dir | |
3286 | for (f, src, dst) in to_install: |
|
3291 | for (f, src, dst) in to_install: | |
3287 | shutil.copy(src, dst) |
|
3292 | shutil.copy(src, dst) | |
3288 | print " %s" % f |
|
3293 | print " %s" % f | |
3289 |
|
3294 | |||
3290 | def magic_install_default_config(self, s): |
|
3295 | def magic_install_default_config(self, s): | |
3291 | """Install IPython's default config file into the .ipython dir. |
|
3296 | """Install IPython's default config file into the .ipython dir. | |
3292 |
|
3297 | |||
3293 | If the default config file (:file:`ipython_config.py`) is already |
|
3298 | If the default config file (:file:`ipython_config.py`) is already | |
3294 | installed, it will not be overwritten. You can force overwriting |
|
3299 | installed, it will not be overwritten. You can force overwriting | |
3295 | by using the ``-o`` option:: |
|
3300 | by using the ``-o`` option:: | |
3296 |
|
3301 | |||
3297 | In [1]: %install_default_config |
|
3302 | In [1]: %install_default_config | |
3298 | """ |
|
3303 | """ | |
3299 | if '-o' in s: |
|
3304 | if '-o' in s: | |
3300 | overwrite = True |
|
3305 | overwrite = True | |
3301 | else: |
|
3306 | else: | |
3302 | overwrite = False |
|
3307 | overwrite = False | |
3303 | from IPython.config import default |
|
3308 | from IPython.config import default | |
3304 | config_dir = os.path.split(default.__file__)[0] |
|
3309 | config_dir = os.path.split(default.__file__)[0] | |
3305 | ipython_dir = self.ipython_dir |
|
3310 | ipython_dir = self.ipython_dir | |
3306 | default_config_file_name = 'ipython_config.py' |
|
3311 | default_config_file_name = 'ipython_config.py' | |
3307 | src = os.path.join(config_dir, default_config_file_name) |
|
3312 | src = os.path.join(config_dir, default_config_file_name) | |
3308 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3313 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3309 | if (not os.path.isfile(dst)) or overwrite: |
|
3314 | if (not os.path.isfile(dst)) or overwrite: | |
3310 | shutil.copy(src, dst) |
|
3315 | shutil.copy(src, dst) | |
3311 | print "Installing default config file: %s" % dst |
|
3316 | print "Installing default config file: %s" % dst | |
3312 |
|
3317 | |||
3313 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3318 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3314 | # handling and modify slightly %run |
|
3319 | # handling and modify slightly %run | |
3315 |
|
3320 | |||
3316 | @testdec.skip_doctest |
|
3321 | @testdec.skip_doctest | |
3317 | def _pylab_magic_run(self, parameter_s=''): |
|
3322 | def _pylab_magic_run(self, parameter_s=''): | |
3318 | Magic.magic_run(self, parameter_s, |
|
3323 | Magic.magic_run(self, parameter_s, | |
3319 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3324 | runner=mpl_runner(self.shell.safe_execfile)) | |
3320 |
|
3325 | |||
3321 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3326 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3322 |
|
3327 | |||
3323 | @testdec.skip_doctest |
|
3328 | @testdec.skip_doctest | |
3324 | def magic_pylab(self, s): |
|
3329 | def magic_pylab(self, s): | |
3325 | """Load numpy and matplotlib to work interactively. |
|
3330 | """Load numpy and matplotlib to work interactively. | |
3326 |
|
3331 | |||
3327 | %pylab [GUINAME] |
|
3332 | %pylab [GUINAME] | |
3328 |
|
3333 | |||
3329 | This function lets you activate pylab (matplotlib, numpy and |
|
3334 | This function lets you activate pylab (matplotlib, numpy and | |
3330 | interactive support) at any point during an IPython session. |
|
3335 | interactive support) at any point during an IPython session. | |
3331 |
|
3336 | |||
3332 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3337 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3333 | pylab and mlab, as well as all names from numpy and pylab. |
|
3338 | pylab and mlab, as well as all names from numpy and pylab. | |
3334 |
|
3339 | |||
3335 | Parameters |
|
3340 | Parameters | |
3336 | ---------- |
|
3341 | ---------- | |
3337 | guiname : optional |
|
3342 | guiname : optional | |
3338 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3343 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3339 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3344 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3340 | otherwise matplotlib's default (which you can override in your |
|
3345 | otherwise matplotlib's default (which you can override in your | |
3341 | matplotlib config file) is used. |
|
3346 | matplotlib config file) is used. | |
3342 |
|
3347 | |||
3343 | Examples |
|
3348 | Examples | |
3344 | -------- |
|
3349 | -------- | |
3345 | In this case, where the MPL default is TkAgg: |
|
3350 | In this case, where the MPL default is TkAgg: | |
3346 | In [2]: %pylab |
|
3351 | In [2]: %pylab | |
3347 |
|
3352 | |||
3348 | Welcome to pylab, a matplotlib-based Python environment. |
|
3353 | Welcome to pylab, a matplotlib-based Python environment. | |
3349 | Backend in use: TkAgg |
|
3354 | Backend in use: TkAgg | |
3350 | For more information, type 'help(pylab)'. |
|
3355 | For more information, type 'help(pylab)'. | |
3351 |
|
3356 | |||
3352 | But you can explicitly request a different backend: |
|
3357 | But you can explicitly request a different backend: | |
3353 | In [3]: %pylab qt |
|
3358 | In [3]: %pylab qt | |
3354 |
|
3359 | |||
3355 | Welcome to pylab, a matplotlib-based Python environment. |
|
3360 | Welcome to pylab, a matplotlib-based Python environment. | |
3356 | Backend in use: Qt4Agg |
|
3361 | Backend in use: Qt4Agg | |
3357 | For more information, type 'help(pylab)'. |
|
3362 | For more information, type 'help(pylab)'. | |
3358 | """ |
|
3363 | """ | |
3359 | self.shell.enable_pylab(s) |
|
3364 | self.shell.enable_pylab(s) | |
3360 |
|
3365 | |||
3361 | def magic_tb(self, s): |
|
3366 | def magic_tb(self, s): | |
3362 | """Print the last traceback with the currently active exception mode. |
|
3367 | """Print the last traceback with the currently active exception mode. | |
3363 |
|
3368 | |||
3364 | See %xmode for changing exception reporting modes.""" |
|
3369 | See %xmode for changing exception reporting modes.""" | |
3365 | self.shell.showtraceback() |
|
3370 | self.shell.showtraceback() | |
3366 |
|
3371 | |||
3367 | # end Magic |
|
3372 | # end Magic |
@@ -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=' |
|
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=' |
|
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. |
|
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,208 +1,251 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 | def figsize(sizex, sizey): | |||
|
40 | """Set the default figure size to be [sizex, sizey]. | |||
|
41 | ||||
|
42 | This is just an easy to remember, convenience wrapper that sets:: | |||
|
43 | ||||
|
44 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] | |||
|
45 | """ | |||
|
46 | import matplotlib | |||
|
47 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] | |||
|
48 | ||||
|
49 | ||||
|
50 | def figure_to_svg(fig): | |||
|
51 | """Convert a figure to svg for inline display.""" | |||
|
52 | fc = fig.get_facecolor() | |||
|
53 | ec = fig.get_edgecolor() | |||
|
54 | fig.set_facecolor('white') | |||
|
55 | fig.set_edgecolor('white') | |||
|
56 | try: | |||
|
57 | string_io = StringIO() | |||
|
58 | fig.canvas.print_figure(string_io, format='svg') | |||
|
59 | svg = string_io.getvalue() | |||
|
60 | finally: | |||
|
61 | fig.set_facecolor(fc) | |||
|
62 | fig.set_edgecolor(ec) | |||
|
63 | return svg | |||
|
64 | ||||
|
65 | ||||
|
66 | # We need a little factory function here to create the closure where | |||
|
67 | # safe_execfile can live. | |||
|
68 | def mpl_runner(safe_execfile): | |||
|
69 | """Factory to return a matplotlib-enabled runner for %run. | |||
|
70 | ||||
|
71 | Parameters | |||
|
72 | ---------- | |||
|
73 | safe_execfile : function | |||
|
74 | This must be a function with the same interface as the | |||
|
75 | :meth:`safe_execfile` method of IPython. | |||
|
76 | ||||
|
77 | Returns | |||
|
78 | ------- | |||
|
79 | A function suitable for use as the ``runner`` argument of the %run magic | |||
|
80 | function. | |||
|
81 | """ | |||
|
82 | ||||
|
83 | def mpl_execfile(fname,*where,**kw): | |||
|
84 | """matplotlib-aware wrapper around safe_execfile. | |||
|
85 | ||||
|
86 | Its interface is identical to that of the :func:`execfile` builtin. | |||
|
87 | ||||
|
88 | This is ultimately a call to execfile(), but wrapped in safeties to | |||
|
89 | properly handle interactive rendering.""" | |||
|
90 | ||||
|
91 | import matplotlib | |||
|
92 | import matplotlib.pylab as pylab | |||
|
93 | ||||
|
94 | #print '*** Matplotlib runner ***' # dbg | |||
|
95 | # turn off rendering until end of script | |||
|
96 | is_interactive = matplotlib.rcParams['interactive'] | |||
|
97 | matplotlib.interactive(False) | |||
|
98 | safe_execfile(fname,*where,**kw) | |||
|
99 | matplotlib.interactive(is_interactive) | |||
|
100 | # make rendering call now, if the user tried to do it | |||
|
101 | if pylab.draw_if_interactive.called: | |||
|
102 | pylab.draw() | |||
|
103 | pylab.draw_if_interactive.called = False | |||
|
104 | ||||
|
105 | return mpl_execfile | |||
|
106 | ||||
|
107 | ||||
|
108 | #----------------------------------------------------------------------------- | |||
|
109 | # Code for initializing matplotlib and importing pylab | |||
35 | #----------------------------------------------------------------------------- |
|
110 | #----------------------------------------------------------------------------- | |
36 |
|
111 | |||
37 |
|
112 | |||
38 | def find_gui_and_backend(gui=None): |
|
113 | def find_gui_and_backend(gui=None): | |
39 | """Given a gui string return the gui and mpl backend. |
|
114 | """Given a gui string return the gui and mpl backend. | |
40 |
|
115 | |||
41 | Parameters |
|
116 | Parameters | |
42 | ---------- |
|
117 | ---------- | |
43 | gui : str |
|
118 | gui : str | |
44 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). |
|
119 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). | |
45 |
|
120 | |||
46 | Returns |
|
121 | Returns | |
47 | ------- |
|
122 | ------- | |
48 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', |
|
123 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', | |
49 | 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). |
|
124 | 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). | |
50 | """ |
|
125 | """ | |
51 |
|
126 | |||
52 | import matplotlib |
|
127 | import matplotlib | |
53 |
|
128 | |||
54 | if gui: |
|
129 | if gui: | |
55 | # select backend based on requested gui |
|
130 | # select backend based on requested gui | |
56 | backend = backends[gui] |
|
131 | backend = backends[gui] | |
57 | else: |
|
132 | else: | |
58 | backend = matplotlib.rcParams['backend'] |
|
133 | backend = matplotlib.rcParams['backend'] | |
59 | # In this case, we need to find what the appropriate gui selection call |
|
134 | # In this case, we need to find what the appropriate gui selection call | |
60 | # should be for IPython, so we can activate inputhook accordingly |
|
135 | # should be for IPython, so we can activate inputhook accordingly | |
61 | g2b = backends # maps gui names to mpl backend names |
|
136 | g2b = backends # maps gui names to mpl backend names | |
62 | b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict |
|
137 | b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict | |
63 | gui = b2g.get(backend, None) |
|
138 | gui = b2g.get(backend, None) | |
64 | return gui, backend |
|
139 | return gui, backend | |
65 |
|
140 | |||
66 |
|
141 | |||
67 | def activate_matplotlib(backend): |
|
142 | def activate_matplotlib(backend): | |
68 | """Activate the given backend and set interactive to True.""" |
|
143 | """Activate the given backend and set interactive to True.""" | |
69 |
|
144 | |||
70 | import matplotlib |
|
145 | import matplotlib | |
71 | if backend.startswith('module://'): |
|
146 | if backend.startswith('module://'): | |
72 | # Work around bug in matplotlib: matplotlib.use converts the |
|
147 | # Work around bug in matplotlib: matplotlib.use converts the | |
73 | # backend_id to lowercase even if a module name is specified! |
|
148 | # backend_id to lowercase even if a module name is specified! | |
74 | matplotlib.rcParams['backend'] = backend |
|
149 | matplotlib.rcParams['backend'] = backend | |
75 | else: |
|
150 | else: | |
76 | matplotlib.use(backend) |
|
151 | matplotlib.use(backend) | |
77 | matplotlib.interactive(True) |
|
152 | matplotlib.interactive(True) | |
78 |
|
153 | |||
79 | # This must be imported last in the matplotlib series, after |
|
154 | # This must be imported last in the matplotlib series, after | |
80 | # backend/interactivity choices have been made |
|
155 | # backend/interactivity choices have been made | |
81 | import matplotlib.pylab as pylab |
|
156 | import matplotlib.pylab as pylab | |
82 |
|
157 | |||
83 | # XXX For now leave this commented out, but depending on discussions with |
|
158 | # XXX For now leave this commented out, but depending on discussions with | |
84 | # mpl-dev, we may be able to allow interactive switching... |
|
159 | # mpl-dev, we may be able to allow interactive switching... | |
85 | #import matplotlib.pyplot |
|
160 | #import matplotlib.pyplot | |
86 | #matplotlib.pyplot.switch_backend(backend) |
|
161 | #matplotlib.pyplot.switch_backend(backend) | |
87 |
|
162 | |||
88 | pylab.show._needmain = False |
|
163 | pylab.show._needmain = False | |
89 | # We need to detect at runtime whether show() is called by the user. |
|
164 | # 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. |
|
165 | # For this, we wrap it into a decorator which adds a 'called' flag. | |
91 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) |
|
166 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) | |
92 |
|
167 | |||
93 |
|
168 | |||
94 | def import_pylab(user_ns, backend, import_all=True, shell=None): |
|
169 | def import_pylab(user_ns, backend, import_all=True, shell=None): | |
95 | """Import the standard pylab symbols into user_ns.""" |
|
170 | """Import the standard pylab symbols into user_ns.""" | |
96 |
|
171 | |||
97 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
172 | # Import numpy as np/pyplot as plt are conventions we're trying to | |
98 | # somewhat standardize on. Making them available to users by default |
|
173 | # somewhat standardize on. Making them available to users by default | |
99 | # will greatly help this. |
|
174 | # will greatly help this. | |
100 | s = ("import numpy\n" |
|
175 | s = ("import numpy\n" | |
101 | "import matplotlib\n" |
|
176 | "import matplotlib\n" | |
102 | "from matplotlib import pylab, mlab, pyplot\n" |
|
177 | "from matplotlib import pylab, mlab, pyplot\n" | |
103 | "np = numpy\n" |
|
178 | "np = numpy\n" | |
104 | "plt = pyplot\n" |
|
179 | "plt = pyplot\n" | |
105 | ) |
|
180 | ) | |
106 | exec s in user_ns |
|
181 | exec s in user_ns | |
107 |
|
182 | |||
108 | if shell is not None: |
|
183 | if shell is not None: | |
109 | exec s in shell.user_ns_hidden |
|
184 | exec s in shell.user_ns_hidden | |
110 | # If using our svg payload backend, register the post-execution |
|
185 | # If using our svg payload backend, register the post-execution | |
111 | # function that will pick up the results for display. This can only be |
|
186 | # function that will pick up the results for display. This can only be | |
112 | # done with access to the real shell object. |
|
187 | # done with access to the real shell object. | |
113 | if backend == backends['inline']: |
|
188 | if backend == backends['inline']: | |
114 |
from IPython.zmq.pylab.backend_inline import flush_svg |
|
189 | from IPython.zmq.pylab.backend_inline import flush_svg | |
115 | from matplotlib import pyplot |
|
190 | from matplotlib import pyplot | |
116 | shell.register_post_execute(flush_svg) |
|
191 | shell.register_post_execute(flush_svg) | |
117 | # The typical default figure size is too large for inline use. We |
|
192 | # The typical default figure size is too large for inline use. We | |
118 | # might make this a user-configurable parameter later. |
|
193 | # might make this a user-configurable parameter later. | |
119 | figsize(6.0, 4.0) |
|
194 | figsize(6.0, 4.0) | |
120 | # Add 'figsize' to pyplot and to the user's namespace |
|
195 | # Add 'figsize' to pyplot and to the user's namespace | |
121 | user_ns['figsize'] = pyplot.figsize = figsize |
|
196 | user_ns['figsize'] = pyplot.figsize = figsize | |
122 | shell.user_ns_hidden['figsize'] = figsize |
|
197 | shell.user_ns_hidden['figsize'] = figsize | |
123 |
|
|
198 | ||
124 | from IPython.zmq.pylab.backend_inline import pastefig |
|
199 | # The old pastefig function has been replaced by display | |
125 | from matplotlib import pyplot |
|
200 | # Always add this svg formatter so display works. | |
126 | # Add 'paste' to pyplot and to the user's namespace |
|
201 | from IPython.zmq.pylab.backend_inline import figure_to_svg | |
127 | user_ns['pastefig'] = pyplot.pastefig = pastefig |
|
202 | from IPython.core.display import display, display_svg | |
|
203 | svg_formatter = shell.display_formatter.formatters['image/svg+xml'] | |||
|
204 | svg_formatter.for_type_by_name( | |||
|
205 | 'matplotlib.figure','Figure',figure_to_svg | |||
|
206 | ) | |||
|
207 | # Add display and display_png to the user's namespace | |||
|
208 | user_ns['display'] = display | |||
|
209 | shell.user_ns_hidden['display'] = display | |||
|
210 | user_ns['display_svg'] = display_svg | |||
|
211 | shell.user_ns_hidden['display_svg'] = display_svg | |||
128 |
|
212 | |||
129 | if import_all: |
|
213 | if import_all: | |
130 | s = ("from matplotlib.pylab import *\n" |
|
214 | s = ("from matplotlib.pylab import *\n" | |
131 | "from numpy import *\n") |
|
215 | "from numpy import *\n") | |
132 | exec s in user_ns |
|
216 | exec s in user_ns | |
133 | if shell is not None: |
|
217 | if shell is not None: | |
134 | exec s in shell.user_ns_hidden |
|
218 | exec s in shell.user_ns_hidden | |
135 |
|
219 | |||
136 |
|
220 | |||
137 | def pylab_activate(user_ns, gui=None, import_all=True): |
|
221 | def pylab_activate(user_ns, gui=None, import_all=True): | |
138 | """Activate pylab mode in the user's namespace. |
|
222 | """Activate pylab mode in the user's namespace. | |
139 |
|
223 | |||
140 | Loads and initializes numpy, matplotlib and friends for interactive use. |
|
224 | Loads and initializes numpy, matplotlib and friends for interactive use. | |
141 |
|
225 | |||
142 | Parameters |
|
226 | Parameters | |
143 | ---------- |
|
227 | ---------- | |
144 | user_ns : dict |
|
228 | user_ns : dict | |
145 | Namespace where the imports will occur. |
|
229 | Namespace where the imports will occur. | |
146 |
|
230 | |||
147 | gui : optional, string |
|
231 | gui : optional, string | |
148 | A valid gui name following the conventions of the %gui magic. |
|
232 | A valid gui name following the conventions of the %gui magic. | |
149 |
|
233 | |||
150 | import_all : optional, boolean |
|
234 | import_all : optional, boolean | |
151 | If true, an 'import *' is done from numpy and pylab. |
|
235 | If true, an 'import *' is done from numpy and pylab. | |
152 |
|
236 | |||
153 | Returns |
|
237 | Returns | |
154 | ------- |
|
238 | ------- | |
155 | The actual gui used (if not given as input, it was obtained from matplotlib |
|
239 | 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. |
|
240 | itself, and will be needed next to configure IPython's gui integration. | |
157 | """ |
|
241 | """ | |
158 | gui, backend = find_gui_and_backend(gui) |
|
242 | gui, backend = find_gui_and_backend(gui) | |
159 | activate_matplotlib(backend) |
|
243 | activate_matplotlib(backend) | |
160 | import_pylab(user_ns, backend) |
|
244 | import_pylab(user_ns, backend) | |
161 |
|
245 | |||
162 | print """ |
|
246 | print """ | |
163 | Welcome to pylab, a matplotlib-based Python environment [backend: %s]. |
|
247 | Welcome to pylab, a matplotlib-based Python environment [backend: %s]. | |
164 | For more information, type 'help(pylab)'.""" % backend |
|
248 | For more information, type 'help(pylab)'.""" % backend | |
165 |
|
249 | |||
166 | return gui |
|
250 | return gui | |
167 |
|
251 | |||
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,123 +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 IPython.core.displaypub import publish_display_data |
|
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= |
|
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_ |
|
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 | publish_display_data( |
|
|||
89 | 'IPython.zmq.pylab.backend_inline.send_svg_canvas', |
|
|||
90 | 'Matplotlib Plot', |
|
|||
91 | {'image/svg+xml' : svg_from_canvas(canvas)} |
|
|||
92 | ) |
|
|||
93 | finally: |
|
|||
94 | canvas.figure.set_facecolor(fc) |
|
|||
95 | canvas.figure.set_edgecolor(ec) |
|
|||
96 |
|
||||
97 |
|
||||
98 | def svg_from_canvas(canvas): |
|
|||
99 | """ Return a string containing the SVG representation of a FigureCanvasSvg. |
|
|||
100 | """ |
|
|||
101 | string_io = StringIO() |
|
|||
102 | canvas.print_figure(string_io, format='svg') |
|
|||
103 | return string_io.getvalue() |
|
|||
104 |
|
||||
105 |
|
||||
106 | def draw_if_interactive(): |
|
42 | def draw_if_interactive(): | |
107 | """ |
|
43 | """ | |
108 | Is called after every pylab drawing command |
|
44 | Is called after every pylab drawing command | |
109 | """ |
|
45 | """ | |
110 | # 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 | |
111 | # 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. | |
112 | show._draw_called = True |
|
48 | show._draw_called = True | |
113 |
|
49 | |||
114 |
|
50 | |||
115 | def flush_svg(): |
|
51 | def flush_svg(): | |
116 | """Call show, close all open figures, sending all SVG images. |
|
52 | """Call show, close all open figures, sending all SVG images. | |
117 |
|
53 | |||
118 | 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 | |
119 | 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. | |
120 | """ |
|
56 | """ | |
121 | if show._draw_called: |
|
57 | if show._draw_called: | |
122 | 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() | |||
123 | 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,605 +1,610 b'' | |||||
1 | """A ZMQ-based subclass of InteractiveShell. |
|
1 | """A ZMQ-based subclass of InteractiveShell. | |
2 |
|
2 | |||
3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
3 | This code is meant to ease the refactoring of the base InteractiveShell into | |
4 | something with a cleaner architecture for 2-process use, without actually |
|
4 | something with a cleaner architecture for 2-process use, without actually | |
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where |
|
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where | |
6 | we subclass and override what we want to fix. Once this is working well, we |
|
6 | we subclass and override what we want to fix. Once this is working well, we | |
7 | can go back to the base class and refactor the code for a cleaner inheritance |
|
7 | can go back to the base class and refactor the code for a cleaner inheritance | |
8 | implementation that doesn't rely on so much monkeypatching. |
|
8 | implementation that doesn't rely on so much monkeypatching. | |
9 |
|
9 | |||
10 | But this lets us maintain a fully working IPython as we develop the new |
|
10 | But this lets us maintain a fully working IPython as we develop the new | |
11 | machinery. This should thus be thought of as scaffolding. |
|
11 | machinery. This should thus be thought of as scaffolding. | |
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 | # Stdlib |
|
18 | # Stdlib | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 |
|
22 | |||
23 | # Our own |
|
23 | # Our own | |
24 | from IPython.core.interactiveshell import ( |
|
24 | from IPython.core.interactiveshell import ( | |
25 | InteractiveShell, InteractiveShellABC |
|
25 | InteractiveShell, InteractiveShellABC | |
26 | ) |
|
26 | ) | |
27 | from IPython.core import page |
|
27 | from IPython.core import page | |
28 | from IPython.core.displayhook import DisplayHook |
|
28 | from IPython.core.displayhook import DisplayHook | |
29 | from IPython.core.displaypub import DisplayPublisher |
|
29 | from IPython.core.displaypub import DisplayPublisher | |
30 | from IPython.core.macro import Macro |
|
30 | from IPython.core.macro import Macro | |
31 | from IPython.core.payloadpage import install_payload_page |
|
31 | from IPython.core.payloadpage import install_payload_page | |
32 | from IPython.utils import io |
|
32 | from IPython.utils import io | |
33 | from IPython.utils.path import get_py_filename |
|
33 | from IPython.utils.path import get_py_filename | |
34 | from IPython.utils.text import StringTypes |
|
34 | from IPython.utils.text import StringTypes | |
35 | from IPython.utils.traitlets import Instance, Type, Dict |
|
35 | from IPython.utils.traitlets import Instance, Type, Dict | |
36 | from IPython.utils.warn import warn |
|
36 | from IPython.utils.warn import warn | |
37 | from IPython.zmq.session import extract_header |
|
37 | from IPython.zmq.session import extract_header | |
38 | from session import Session |
|
38 | from session import Session | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Globals and side-effects |
|
41 | # Globals and side-effects | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | # Install the payload version of page. |
|
44 | # Install the payload version of page. | |
45 | install_payload_page() |
|
45 | install_payload_page() | |
46 |
|
46 | |||
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 | # Functions and classes |
|
48 | # Functions and classes | |
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 |
|
50 | |||
51 | class ZMQDisplayHook(DisplayHook): |
|
51 | class ZMQDisplayHook(DisplayHook): | |
52 | """A displayhook subclass that publishes data using ZeroMQ.""" |
|
52 | """A displayhook subclass that publishes data using ZeroMQ.""" | |
53 |
|
53 | |||
54 | session = Instance(Session) |
|
54 | session = Instance(Session) | |
55 | pub_socket = Instance('zmq.Socket') |
|
55 | pub_socket = Instance('zmq.Socket') | |
56 | parent_header = Dict({}) |
|
56 | parent_header = Dict({}) | |
57 |
|
57 | |||
58 | def set_parent(self, parent): |
|
58 | def set_parent(self, parent): | |
59 | """Set the parent for outbound messages.""" |
|
59 | """Set the parent for outbound messages.""" | |
60 | self.parent_header = extract_header(parent) |
|
60 | self.parent_header = extract_header(parent) | |
61 |
|
61 | |||
62 | def start_displayhook(self): |
|
62 | def start_displayhook(self): | |
63 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
63 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
64 |
|
64 | |||
65 | def write_output_prompt(self): |
|
65 | def write_output_prompt(self): | |
66 | """Write the output prompt.""" |
|
66 | """Write the output prompt.""" | |
67 | if self.do_full_cache: |
|
67 | if self.do_full_cache: | |
68 | self.msg['content']['execution_count'] = self.prompt_count |
|
68 | self.msg['content']['execution_count'] = self.prompt_count | |
69 |
|
69 | |||
70 | def write_format_data(self, format_dict): |
|
70 | def write_format_data(self, format_dict): | |
71 | self.msg['content']['data'] = format_dict |
|
71 | self.msg['content']['data'] = format_dict | |
72 |
|
72 | |||
73 | def finish_displayhook(self): |
|
73 | def finish_displayhook(self): | |
74 | """Finish up all displayhook activities.""" |
|
74 | """Finish up all displayhook activities.""" | |
75 | self.session.send(self.pub_socket, self.msg) |
|
75 | self.session.send(self.pub_socket, self.msg) | |
76 | self.msg = None |
|
76 | self.msg = None | |
77 |
|
77 | |||
78 |
|
78 | |||
79 | class ZMQDisplayPublisher(DisplayPublisher): |
|
79 | class ZMQDisplayPublisher(DisplayPublisher): | |
80 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" |
|
80 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" | |
81 |
|
81 | |||
82 | session = Instance(Session) |
|
82 | session = Instance(Session) | |
83 | pub_socket = Instance('zmq.Socket') |
|
83 | pub_socket = Instance('zmq.Socket') | |
84 | parent_header = Dict({}) |
|
84 | parent_header = Dict({}) | |
85 |
|
85 | |||
86 | def set_parent(self, parent): |
|
86 | def set_parent(self, parent): | |
87 | """Set the parent for outbound messages.""" |
|
87 | """Set the parent for outbound messages.""" | |
88 | self.parent_header = extract_header(parent) |
|
88 | self.parent_header = extract_header(parent) | |
89 |
|
89 | |||
90 | def publish(self, source, data, metadata=None): |
|
90 | def publish(self, source, data, metadata=None): | |
91 | if metadata is None: |
|
91 | if metadata is None: | |
92 | metadata = {} |
|
92 | metadata = {} | |
93 | self._validate_data(source, data, metadata) |
|
93 | self._validate_data(source, data, metadata) | |
94 | msg = self.session.msg(u'display_data', {}, parent=self.parent_header) |
|
94 | msg = self.session.msg(u'display_data', {}, parent=self.parent_header) | |
95 | msg['content']['source'] = source |
|
95 | msg['content']['source'] = source | |
96 | msg['content']['data'] = data |
|
96 | msg['content']['data'] = data | |
97 | msg['content']['metadata'] = metadata |
|
97 | msg['content']['metadata'] = metadata | |
98 | self.pub_socket.send_json(msg) |
|
98 | self.pub_socket.send_json(msg) | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | class ZMQInteractiveShell(InteractiveShell): |
|
101 | class ZMQInteractiveShell(InteractiveShell): | |
102 | """A subclass of InteractiveShell for ZMQ.""" |
|
102 | """A subclass of InteractiveShell for ZMQ.""" | |
103 |
|
103 | |||
104 | displayhook_class = Type(ZMQDisplayHook) |
|
104 | displayhook_class = Type(ZMQDisplayHook) | |
105 | display_pub_class = Type(ZMQDisplayPublisher) |
|
105 | display_pub_class = Type(ZMQDisplayPublisher) | |
106 |
|
106 | |||
107 | keepkernel_on_exit = None |
|
107 | keepkernel_on_exit = None | |
108 |
|
108 | |||
109 | def init_environment(self): |
|
109 | def init_environment(self): | |
110 | """Configure the user's environment. |
|
110 | """Configure the user's environment. | |
111 |
|
111 | |||
112 | """ |
|
112 | """ | |
113 | env = os.environ |
|
113 | env = os.environ | |
114 | # These two ensure 'ls' produces nice coloring on BSD-derived systems |
|
114 | # These two ensure 'ls' produces nice coloring on BSD-derived systems | |
115 | env['TERM'] = 'xterm-color' |
|
115 | env['TERM'] = 'xterm-color' | |
116 | env['CLICOLOR'] = '1' |
|
116 | env['CLICOLOR'] = '1' | |
117 | # Since normal pagers don't work at all (over pexpect we don't have |
|
117 | # Since normal pagers don't work at all (over pexpect we don't have | |
118 | # single-key control of the subprocess), try to disable paging in |
|
118 | # single-key control of the subprocess), try to disable paging in | |
119 | # subprocesses as much as possible. |
|
119 | # subprocesses as much as possible. | |
120 | env['PAGER'] = 'cat' |
|
120 | env['PAGER'] = 'cat' | |
121 | env['GIT_PAGER'] = 'cat' |
|
121 | env['GIT_PAGER'] = 'cat' | |
122 |
|
122 | |||
123 | def auto_rewrite_input(self, cmd): |
|
123 | def auto_rewrite_input(self, cmd): | |
124 | """Called to show the auto-rewritten input for autocall and friends. |
|
124 | """Called to show the auto-rewritten input for autocall and friends. | |
125 |
|
125 | |||
126 | FIXME: this payload is currently not correctly processed by the |
|
126 | FIXME: this payload is currently not correctly processed by the | |
127 | frontend. |
|
127 | frontend. | |
128 | """ |
|
128 | """ | |
129 | new = self.displayhook.prompt1.auto_rewrite() + cmd |
|
129 | new = self.displayhook.prompt1.auto_rewrite() + cmd | |
130 | payload = dict( |
|
130 | payload = dict( | |
131 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
131 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', | |
132 | transformed_input=new, |
|
132 | transformed_input=new, | |
133 | ) |
|
133 | ) | |
134 | self.payload_manager.write_payload(payload) |
|
134 | self.payload_manager.write_payload(payload) | |
135 |
|
135 | |||
136 | def ask_exit(self): |
|
136 | def ask_exit(self): | |
137 | """Engage the exit actions.""" |
|
137 | """Engage the exit actions.""" | |
138 | payload = dict( |
|
138 | payload = dict( | |
139 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
139 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', | |
140 | exit=True, |
|
140 | exit=True, | |
141 | keepkernel=self.keepkernel_on_exit, |
|
141 | keepkernel=self.keepkernel_on_exit, | |
142 | ) |
|
142 | ) | |
143 | self.payload_manager.write_payload(payload) |
|
143 | self.payload_manager.write_payload(payload) | |
144 |
|
144 | |||
145 | def _showtraceback(self, etype, evalue, stb): |
|
145 | def _showtraceback(self, etype, evalue, stb): | |
146 |
|
146 | |||
147 | exc_content = { |
|
147 | exc_content = { | |
148 | u'traceback' : stb, |
|
148 | u'traceback' : stb, | |
149 | u'ename' : unicode(etype.__name__), |
|
149 | u'ename' : unicode(etype.__name__), | |
150 | u'evalue' : unicode(evalue) |
|
150 | u'evalue' : unicode(evalue) | |
151 | } |
|
151 | } | |
152 |
|
152 | |||
153 | dh = self.displayhook |
|
153 | dh = self.displayhook | |
154 | # Send exception info over pub socket for other clients than the caller |
|
154 | # Send exception info over pub socket for other clients than the caller | |
155 | # to pick up |
|
155 | # to pick up | |
156 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) |
|
156 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) | |
157 |
|
157 | |||
158 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
158 | # FIXME - Hack: store exception info in shell object. Right now, the | |
159 | # caller is reading this info after the fact, we need to fix this logic |
|
159 | # caller is reading this info after the fact, we need to fix this logic | |
160 | # to remove this hack. Even uglier, we need to store the error status |
|
160 | # to remove this hack. Even uglier, we need to store the error status | |
161 | # here, because in the main loop, the logic that sets it is being |
|
161 | # here, because in the main loop, the logic that sets it is being | |
162 | # skipped because runlines swallows the exceptions. |
|
162 | # skipped because runlines swallows the exceptions. | |
163 | exc_content[u'status'] = u'error' |
|
163 | exc_content[u'status'] = u'error' | |
164 | self._reply_content = exc_content |
|
164 | self._reply_content = exc_content | |
165 | # /FIXME |
|
165 | # /FIXME | |
166 |
|
166 | |||
167 | return exc_content |
|
167 | return exc_content | |
168 |
|
168 | |||
169 | #------------------------------------------------------------------------ |
|
169 | #------------------------------------------------------------------------ | |
170 | # Magic overrides |
|
170 | # Magic overrides | |
171 | #------------------------------------------------------------------------ |
|
171 | #------------------------------------------------------------------------ | |
172 | # Once the base class stops inheriting from magic, this code needs to be |
|
172 | # Once the base class stops inheriting from magic, this code needs to be | |
173 | # moved into a separate machinery as well. For now, at least isolate here |
|
173 | # moved into a separate machinery as well. For now, at least isolate here | |
174 | # the magics which this class needs to implement differently from the base |
|
174 | # the magics which this class needs to implement differently from the base | |
175 | # class, or that are unique to it. |
|
175 | # class, or that are unique to it. | |
176 |
|
176 | |||
177 | def magic_doctest_mode(self,parameter_s=''): |
|
177 | def magic_doctest_mode(self,parameter_s=''): | |
178 | """Toggle doctest mode on and off. |
|
178 | """Toggle doctest mode on and off. | |
179 |
|
179 | |||
180 | This mode is intended to make IPython behave as much as possible like a |
|
180 | This mode is intended to make IPython behave as much as possible like a | |
181 | plain Python shell, from the perspective of how its prompts, exceptions |
|
181 | plain Python shell, from the perspective of how its prompts, exceptions | |
182 | and output look. This makes it easy to copy and paste parts of a |
|
182 | and output look. This makes it easy to copy and paste parts of a | |
183 | session into doctests. It does so by: |
|
183 | session into doctests. It does so by: | |
184 |
|
184 | |||
185 | - Changing the prompts to the classic ``>>>`` ones. |
|
185 | - Changing the prompts to the classic ``>>>`` ones. | |
186 | - Changing the exception reporting mode to 'Plain'. |
|
186 | - Changing the exception reporting mode to 'Plain'. | |
187 | - Disabling pretty-printing of output. |
|
187 | - Disabling pretty-printing of output. | |
188 |
|
188 | |||
189 | Note that IPython also supports the pasting of code snippets that have |
|
189 | Note that IPython also supports the pasting of code snippets that have | |
190 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
190 | leading '>>>' and '...' prompts in them. This means that you can paste | |
191 | doctests from files or docstrings (even if they have leading |
|
191 | doctests from files or docstrings (even if they have leading | |
192 | whitespace), and the code will execute correctly. You can then use |
|
192 | whitespace), and the code will execute correctly. You can then use | |
193 | '%history -t' to see the translated history; this will give you the |
|
193 | '%history -t' to see the translated history; this will give you the | |
194 | input after removal of all the leading prompts and whitespace, which |
|
194 | input after removal of all the leading prompts and whitespace, which | |
195 | can be pasted back into an editor. |
|
195 | can be pasted back into an editor. | |
196 |
|
196 | |||
197 | With these features, you can switch into this mode easily whenever you |
|
197 | With these features, you can switch into this mode easily whenever you | |
198 | need to do testing and changes to doctests, without having to leave |
|
198 | need to do testing and changes to doctests, without having to leave | |
199 | your existing IPython session. |
|
199 | your existing IPython session. | |
200 | """ |
|
200 | """ | |
201 |
|
201 | |||
202 | from IPython.utils.ipstruct import Struct |
|
202 | from IPython.utils.ipstruct import Struct | |
203 |
|
203 | |||
204 | # Shorthands |
|
204 | # Shorthands | |
205 | shell = self.shell |
|
205 | shell = self.shell | |
|
206 | disp_formatter = self.shell.display_formatter | |||
|
207 | ptformatter = disp_formatter.formatters['text/plain'] | |||
206 | # dstore is a data store kept in the instance metadata bag to track any |
|
208 | # dstore is a data store kept in the instance metadata bag to track any | |
207 | # changes we make, so we can undo them later. |
|
209 | # changes we make, so we can undo them later. | |
208 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
210 | dstore = shell.meta.setdefault('doctest_mode', Struct()) | |
209 | save_dstore = dstore.setdefault |
|
211 | save_dstore = dstore.setdefault | |
210 |
|
212 | |||
211 | # save a few values we'll need to recover later |
|
213 | # save a few values we'll need to recover later | |
212 | mode = save_dstore('mode', False) |
|
214 | mode = save_dstore('mode', False) | |
213 |
save_dstore('rc_pprint', |
|
215 | save_dstore('rc_pprint', ptformatter.pprint) | |
|
216 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |||
214 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
217 | save_dstore('xmode', shell.InteractiveTB.mode) | |
215 |
|
218 | |||
216 | if mode == False: |
|
219 | if mode == False: | |
217 | # turn on |
|
220 | # turn on | |
218 |
|
|
221 | ptformatter.pprint = False | |
|
222 | disp_formatter.plain_text_only = True | |||
219 | shell.magic_xmode('Plain') |
|
223 | shell.magic_xmode('Plain') | |
220 | else: |
|
224 | else: | |
221 | # turn off |
|
225 | # turn off | |
222 |
|
|
226 | ptformatter.pprint = dstore.rc_pprint | |
|
227 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |||
223 | shell.magic_xmode(dstore.xmode) |
|
228 | shell.magic_xmode(dstore.xmode) | |
224 |
|
229 | |||
225 | # Store new mode and inform on console |
|
230 | # Store new mode and inform on console | |
226 | dstore.mode = bool(1-int(mode)) |
|
231 | dstore.mode = bool(1-int(mode)) | |
227 | mode_label = ['OFF','ON'][dstore.mode] |
|
232 | mode_label = ['OFF','ON'][dstore.mode] | |
228 | print('Doctest mode is:', mode_label) |
|
233 | print('Doctest mode is:', mode_label) | |
229 |
|
234 | |||
230 | # Send the payload back so that clients can modify their prompt display |
|
235 | # Send the payload back so that clients can modify their prompt display | |
231 | payload = dict( |
|
236 | payload = dict( | |
232 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', |
|
237 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', | |
233 | mode=dstore.mode) |
|
238 | mode=dstore.mode) | |
234 | self.payload_manager.write_payload(payload) |
|
239 | self.payload_manager.write_payload(payload) | |
235 |
|
240 | |||
236 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
241 | def magic_edit(self,parameter_s='',last_call=['','']): | |
237 | """Bring up an editor and execute the resulting code. |
|
242 | """Bring up an editor and execute the resulting code. | |
238 |
|
243 | |||
239 | Usage: |
|
244 | Usage: | |
240 | %edit [options] [args] |
|
245 | %edit [options] [args] | |
241 |
|
246 | |||
242 | %edit runs IPython's editor hook. The default version of this hook is |
|
247 | %edit runs IPython's editor hook. The default version of this hook is | |
243 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
248 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
244 | environment variable $EDITOR. If this isn't found, it will default to |
|
249 | environment variable $EDITOR. If this isn't found, it will default to | |
245 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
250 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
246 | docstring for how to change the editor hook. |
|
251 | docstring for how to change the editor hook. | |
247 |
|
252 | |||
248 | You can also set the value of this editor via the command line option |
|
253 | You can also set the value of this editor via the command line option | |
249 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
254 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
250 | specifically for IPython an editor different from your typical default |
|
255 | specifically for IPython an editor different from your typical default | |
251 | (and for Windows users who typically don't set environment variables). |
|
256 | (and for Windows users who typically don't set environment variables). | |
252 |
|
257 | |||
253 | This command allows you to conveniently edit multi-line code right in |
|
258 | This command allows you to conveniently edit multi-line code right in | |
254 | your IPython session. |
|
259 | your IPython session. | |
255 |
|
260 | |||
256 | If called without arguments, %edit opens up an empty editor with a |
|
261 | If called without arguments, %edit opens up an empty editor with a | |
257 | temporary file and will execute the contents of this file when you |
|
262 | temporary file and will execute the contents of this file when you | |
258 | close it (don't forget to save it!). |
|
263 | close it (don't forget to save it!). | |
259 |
|
264 | |||
260 |
|
265 | |||
261 | Options: |
|
266 | Options: | |
262 |
|
267 | |||
263 | -n <number>: open the editor at a specified line number. By default, |
|
268 | -n <number>: open the editor at a specified line number. By default, | |
264 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
269 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
265 | you can configure this by providing your own modified hook if your |
|
270 | you can configure this by providing your own modified hook if your | |
266 | favorite editor supports line-number specifications with a different |
|
271 | favorite editor supports line-number specifications with a different | |
267 | syntax. |
|
272 | syntax. | |
268 |
|
273 | |||
269 | -p: this will call the editor with the same data as the previous time |
|
274 | -p: this will call the editor with the same data as the previous time | |
270 | it was used, regardless of how long ago (in your current session) it |
|
275 | it was used, regardless of how long ago (in your current session) it | |
271 | was. |
|
276 | was. | |
272 |
|
277 | |||
273 | -r: use 'raw' input. This option only applies to input taken from the |
|
278 | -r: use 'raw' input. This option only applies to input taken from the | |
274 | user's history. By default, the 'processed' history is used, so that |
|
279 | user's history. By default, the 'processed' history is used, so that | |
275 | magics are loaded in their transformed version to valid Python. If |
|
280 | magics are loaded in their transformed version to valid Python. If | |
276 | this option is given, the raw input as typed as the command line is |
|
281 | this option is given, the raw input as typed as the command line is | |
277 | used instead. When you exit the editor, it will be executed by |
|
282 | used instead. When you exit the editor, it will be executed by | |
278 | IPython's own processor. |
|
283 | IPython's own processor. | |
279 |
|
284 | |||
280 | -x: do not execute the edited code immediately upon exit. This is |
|
285 | -x: do not execute the edited code immediately upon exit. This is | |
281 | mainly useful if you are editing programs which need to be called with |
|
286 | mainly useful if you are editing programs which need to be called with | |
282 | command line arguments, which you can then do using %run. |
|
287 | command line arguments, which you can then do using %run. | |
283 |
|
288 | |||
284 |
|
289 | |||
285 | Arguments: |
|
290 | Arguments: | |
286 |
|
291 | |||
287 | If arguments are given, the following possibilites exist: |
|
292 | If arguments are given, the following possibilites exist: | |
288 |
|
293 | |||
289 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
294 | - The arguments are numbers or pairs of colon-separated numbers (like | |
290 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
295 | 1 4:8 9). These are interpreted as lines of previous input to be | |
291 | loaded into the editor. The syntax is the same of the %macro command. |
|
296 | loaded into the editor. The syntax is the same of the %macro command. | |
292 |
|
297 | |||
293 | - If the argument doesn't start with a number, it is evaluated as a |
|
298 | - If the argument doesn't start with a number, it is evaluated as a | |
294 | variable and its contents loaded into the editor. You can thus edit |
|
299 | variable and its contents loaded into the editor. You can thus edit | |
295 | any string which contains python code (including the result of |
|
300 | any string which contains python code (including the result of | |
296 | previous edits). |
|
301 | previous edits). | |
297 |
|
302 | |||
298 | - If the argument is the name of an object (other than a string), |
|
303 | - If the argument is the name of an object (other than a string), | |
299 | IPython will try to locate the file where it was defined and open the |
|
304 | IPython will try to locate the file where it was defined and open the | |
300 | editor at the point where it is defined. You can use `%edit function` |
|
305 | editor at the point where it is defined. You can use `%edit function` | |
301 | to load an editor exactly at the point where 'function' is defined, |
|
306 | to load an editor exactly at the point where 'function' is defined, | |
302 | edit it and have the file be executed automatically. |
|
307 | edit it and have the file be executed automatically. | |
303 |
|
308 | |||
304 | If the object is a macro (see %macro for details), this opens up your |
|
309 | If the object is a macro (see %macro for details), this opens up your | |
305 | specified editor with a temporary file containing the macro's data. |
|
310 | specified editor with a temporary file containing the macro's data. | |
306 | Upon exit, the macro is reloaded with the contents of the file. |
|
311 | Upon exit, the macro is reloaded with the contents of the file. | |
307 |
|
312 | |||
308 | Note: opening at an exact line is only supported under Unix, and some |
|
313 | Note: opening at an exact line is only supported under Unix, and some | |
309 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
314 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
310 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
315 | '+NUMBER' parameter necessary for this feature. Good editors like | |
311 | (X)Emacs, vi, jed, pico and joe all do. |
|
316 | (X)Emacs, vi, jed, pico and joe all do. | |
312 |
|
317 | |||
313 | - If the argument is not found as a variable, IPython will look for a |
|
318 | - If the argument is not found as a variable, IPython will look for a | |
314 | file with that name (adding .py if necessary) and load it into the |
|
319 | file with that name (adding .py if necessary) and load it into the | |
315 | editor. It will execute its contents with execfile() when you exit, |
|
320 | editor. It will execute its contents with execfile() when you exit, | |
316 | loading any code in the file into your interactive namespace. |
|
321 | loading any code in the file into your interactive namespace. | |
317 |
|
322 | |||
318 | After executing your code, %edit will return as output the code you |
|
323 | After executing your code, %edit will return as output the code you | |
319 | typed in the editor (except when it was an existing file). This way |
|
324 | typed in the editor (except when it was an existing file). This way | |
320 | you can reload the code in further invocations of %edit as a variable, |
|
325 | you can reload the code in further invocations of %edit as a variable, | |
321 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
326 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
322 | the output. |
|
327 | the output. | |
323 |
|
328 | |||
324 | Note that %edit is also available through the alias %ed. |
|
329 | Note that %edit is also available through the alias %ed. | |
325 |
|
330 | |||
326 | This is an example of creating a simple function inside the editor and |
|
331 | This is an example of creating a simple function inside the editor and | |
327 | then modifying it. First, start up the editor: |
|
332 | then modifying it. First, start up the editor: | |
328 |
|
333 | |||
329 | In [1]: ed |
|
334 | In [1]: ed | |
330 | Editing... done. Executing edited code... |
|
335 | Editing... done. Executing edited code... | |
331 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
336 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
332 |
|
337 | |||
333 | We can then call the function foo(): |
|
338 | We can then call the function foo(): | |
334 |
|
339 | |||
335 | In [2]: foo() |
|
340 | In [2]: foo() | |
336 | foo() was defined in an editing session |
|
341 | foo() was defined in an editing session | |
337 |
|
342 | |||
338 | Now we edit foo. IPython automatically loads the editor with the |
|
343 | Now we edit foo. IPython automatically loads the editor with the | |
339 | (temporary) file where foo() was previously defined: |
|
344 | (temporary) file where foo() was previously defined: | |
340 |
|
345 | |||
341 | In [3]: ed foo |
|
346 | In [3]: ed foo | |
342 | Editing... done. Executing edited code... |
|
347 | Editing... done. Executing edited code... | |
343 |
|
348 | |||
344 | And if we call foo() again we get the modified version: |
|
349 | And if we call foo() again we get the modified version: | |
345 |
|
350 | |||
346 | In [4]: foo() |
|
351 | In [4]: foo() | |
347 | foo() has now been changed! |
|
352 | foo() has now been changed! | |
348 |
|
353 | |||
349 | Here is an example of how to edit a code snippet successive |
|
354 | Here is an example of how to edit a code snippet successive | |
350 | times. First we call the editor: |
|
355 | times. First we call the editor: | |
351 |
|
356 | |||
352 | In [5]: ed |
|
357 | In [5]: ed | |
353 | Editing... done. Executing edited code... |
|
358 | Editing... done. Executing edited code... | |
354 | hello |
|
359 | hello | |
355 | Out[5]: "print 'hello'n" |
|
360 | Out[5]: "print 'hello'n" | |
356 |
|
361 | |||
357 | Now we call it again with the previous output (stored in _): |
|
362 | Now we call it again with the previous output (stored in _): | |
358 |
|
363 | |||
359 | In [6]: ed _ |
|
364 | In [6]: ed _ | |
360 | Editing... done. Executing edited code... |
|
365 | Editing... done. Executing edited code... | |
361 | hello world |
|
366 | hello world | |
362 | Out[6]: "print 'hello world'n" |
|
367 | Out[6]: "print 'hello world'n" | |
363 |
|
368 | |||
364 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
369 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
365 |
|
370 | |||
366 | In [7]: ed _8 |
|
371 | In [7]: ed _8 | |
367 | Editing... done. Executing edited code... |
|
372 | Editing... done. Executing edited code... | |
368 | hello again |
|
373 | hello again | |
369 | Out[7]: "print 'hello again'n" |
|
374 | Out[7]: "print 'hello again'n" | |
370 |
|
375 | |||
371 |
|
376 | |||
372 | Changing the default editor hook: |
|
377 | Changing the default editor hook: | |
373 |
|
378 | |||
374 | If you wish to write your own editor hook, you can put it in a |
|
379 | If you wish to write your own editor hook, you can put it in a | |
375 | configuration file which you load at startup time. The default hook |
|
380 | configuration file which you load at startup time. The default hook | |
376 | is defined in the IPython.core.hooks module, and you can use that as a |
|
381 | is defined in the IPython.core.hooks module, and you can use that as a | |
377 | starting example for further modifications. That file also has |
|
382 | starting example for further modifications. That file also has | |
378 | general instructions on how to set a new hook for use once you've |
|
383 | general instructions on how to set a new hook for use once you've | |
379 | defined it.""" |
|
384 | defined it.""" | |
380 |
|
385 | |||
381 | # FIXME: This function has become a convoluted mess. It needs a |
|
386 | # FIXME: This function has become a convoluted mess. It needs a | |
382 | # ground-up rewrite with clean, simple logic. |
|
387 | # ground-up rewrite with clean, simple logic. | |
383 |
|
388 | |||
384 | def make_filename(arg): |
|
389 | def make_filename(arg): | |
385 | "Make a filename from the given args" |
|
390 | "Make a filename from the given args" | |
386 | try: |
|
391 | try: | |
387 | filename = get_py_filename(arg) |
|
392 | filename = get_py_filename(arg) | |
388 | except IOError: |
|
393 | except IOError: | |
389 | if args.endswith('.py'): |
|
394 | if args.endswith('.py'): | |
390 | filename = arg |
|
395 | filename = arg | |
391 | else: |
|
396 | else: | |
392 | filename = None |
|
397 | filename = None | |
393 | return filename |
|
398 | return filename | |
394 |
|
399 | |||
395 | # custom exceptions |
|
400 | # custom exceptions | |
396 | class DataIsObject(Exception): pass |
|
401 | class DataIsObject(Exception): pass | |
397 |
|
402 | |||
398 | opts,args = self.parse_options(parameter_s,'prn:') |
|
403 | opts,args = self.parse_options(parameter_s,'prn:') | |
399 | # Set a few locals from the options for convenience: |
|
404 | # Set a few locals from the options for convenience: | |
400 | opts_p = opts.has_key('p') |
|
405 | opts_p = opts.has_key('p') | |
401 | opts_r = opts.has_key('r') |
|
406 | opts_r = opts.has_key('r') | |
402 |
|
407 | |||
403 | # Default line number value |
|
408 | # Default line number value | |
404 | lineno = opts.get('n',None) |
|
409 | lineno = opts.get('n',None) | |
405 | if lineno is not None: |
|
410 | if lineno is not None: | |
406 | try: |
|
411 | try: | |
407 | lineno = int(lineno) |
|
412 | lineno = int(lineno) | |
408 | except: |
|
413 | except: | |
409 | warn("The -n argument must be an integer.") |
|
414 | warn("The -n argument must be an integer.") | |
410 | return |
|
415 | return | |
411 |
|
416 | |||
412 | if opts_p: |
|
417 | if opts_p: | |
413 | args = '_%s' % last_call[0] |
|
418 | args = '_%s' % last_call[0] | |
414 | if not self.shell.user_ns.has_key(args): |
|
419 | if not self.shell.user_ns.has_key(args): | |
415 | args = last_call[1] |
|
420 | args = last_call[1] | |
416 |
|
421 | |||
417 | # use last_call to remember the state of the previous call, but don't |
|
422 | # use last_call to remember the state of the previous call, but don't | |
418 | # let it be clobbered by successive '-p' calls. |
|
423 | # let it be clobbered by successive '-p' calls. | |
419 | try: |
|
424 | try: | |
420 | last_call[0] = self.shell.displayhook.prompt_count |
|
425 | last_call[0] = self.shell.displayhook.prompt_count | |
421 | if not opts_p: |
|
426 | if not opts_p: | |
422 | last_call[1] = parameter_s |
|
427 | last_call[1] = parameter_s | |
423 | except: |
|
428 | except: | |
424 | pass |
|
429 | pass | |
425 |
|
430 | |||
426 | # by default this is done with temp files, except when the given |
|
431 | # by default this is done with temp files, except when the given | |
427 | # arg is a filename |
|
432 | # arg is a filename | |
428 | use_temp = 1 |
|
433 | use_temp = 1 | |
429 |
|
434 | |||
430 | if re.match(r'\d',args): |
|
435 | if re.match(r'\d',args): | |
431 | # Mode where user specifies ranges of lines, like in %macro. |
|
436 | # Mode where user specifies ranges of lines, like in %macro. | |
432 | # This means that you can't edit files whose names begin with |
|
437 | # This means that you can't edit files whose names begin with | |
433 | # numbers this way. Tough. |
|
438 | # numbers this way. Tough. | |
434 | ranges = args.split() |
|
439 | ranges = args.split() | |
435 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
440 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
436 | elif args.endswith('.py'): |
|
441 | elif args.endswith('.py'): | |
437 | filename = make_filename(args) |
|
442 | filename = make_filename(args) | |
438 | data = '' |
|
443 | data = '' | |
439 | use_temp = 0 |
|
444 | use_temp = 0 | |
440 | elif args: |
|
445 | elif args: | |
441 | try: |
|
446 | try: | |
442 | # Load the parameter given as a variable. If not a string, |
|
447 | # Load the parameter given as a variable. If not a string, | |
443 | # process it as an object instead (below) |
|
448 | # process it as an object instead (below) | |
444 |
|
449 | |||
445 | #print '*** args',args,'type',type(args) # dbg |
|
450 | #print '*** args',args,'type',type(args) # dbg | |
446 | data = eval(args,self.shell.user_ns) |
|
451 | data = eval(args,self.shell.user_ns) | |
447 | if not type(data) in StringTypes: |
|
452 | if not type(data) in StringTypes: | |
448 | raise DataIsObject |
|
453 | raise DataIsObject | |
449 |
|
454 | |||
450 | except (NameError,SyntaxError): |
|
455 | except (NameError,SyntaxError): | |
451 | # given argument is not a variable, try as a filename |
|
456 | # given argument is not a variable, try as a filename | |
452 | filename = make_filename(args) |
|
457 | filename = make_filename(args) | |
453 | if filename is None: |
|
458 | if filename is None: | |
454 | warn("Argument given (%s) can't be found as a variable " |
|
459 | warn("Argument given (%s) can't be found as a variable " | |
455 | "or as a filename." % args) |
|
460 | "or as a filename." % args) | |
456 | return |
|
461 | return | |
457 |
|
462 | |||
458 | data = '' |
|
463 | data = '' | |
459 | use_temp = 0 |
|
464 | use_temp = 0 | |
460 | except DataIsObject: |
|
465 | except DataIsObject: | |
461 |
|
466 | |||
462 | # macros have a special edit function |
|
467 | # macros have a special edit function | |
463 | if isinstance(data,Macro): |
|
468 | if isinstance(data,Macro): | |
464 | self._edit_macro(args,data) |
|
469 | self._edit_macro(args,data) | |
465 | return |
|
470 | return | |
466 |
|
471 | |||
467 | # For objects, try to edit the file where they are defined |
|
472 | # For objects, try to edit the file where they are defined | |
468 | try: |
|
473 | try: | |
469 | filename = inspect.getabsfile(data) |
|
474 | filename = inspect.getabsfile(data) | |
470 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
475 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
471 | # class created by %edit? Try to find source |
|
476 | # class created by %edit? Try to find source | |
472 | # by looking for method definitions instead, the |
|
477 | # by looking for method definitions instead, the | |
473 | # __module__ in those classes is FakeModule. |
|
478 | # __module__ in those classes is FakeModule. | |
474 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
479 | attrs = [getattr(data, aname) for aname in dir(data)] | |
475 | for attr in attrs: |
|
480 | for attr in attrs: | |
476 | if not inspect.ismethod(attr): |
|
481 | if not inspect.ismethod(attr): | |
477 | continue |
|
482 | continue | |
478 | filename = inspect.getabsfile(attr) |
|
483 | filename = inspect.getabsfile(attr) | |
479 | if filename and 'fakemodule' not in filename.lower(): |
|
484 | if filename and 'fakemodule' not in filename.lower(): | |
480 | # change the attribute to be the edit target instead |
|
485 | # change the attribute to be the edit target instead | |
481 | data = attr |
|
486 | data = attr | |
482 | break |
|
487 | break | |
483 |
|
488 | |||
484 | datafile = 1 |
|
489 | datafile = 1 | |
485 | except TypeError: |
|
490 | except TypeError: | |
486 | filename = make_filename(args) |
|
491 | filename = make_filename(args) | |
487 | datafile = 1 |
|
492 | datafile = 1 | |
488 | warn('Could not find file where `%s` is defined.\n' |
|
493 | warn('Could not find file where `%s` is defined.\n' | |
489 | 'Opening a file named `%s`' % (args,filename)) |
|
494 | 'Opening a file named `%s`' % (args,filename)) | |
490 | # Now, make sure we can actually read the source (if it was in |
|
495 | # Now, make sure we can actually read the source (if it was in | |
491 | # a temp file it's gone by now). |
|
496 | # a temp file it's gone by now). | |
492 | if datafile: |
|
497 | if datafile: | |
493 | try: |
|
498 | try: | |
494 | if lineno is None: |
|
499 | if lineno is None: | |
495 | lineno = inspect.getsourcelines(data)[1] |
|
500 | lineno = inspect.getsourcelines(data)[1] | |
496 | except IOError: |
|
501 | except IOError: | |
497 | filename = make_filename(args) |
|
502 | filename = make_filename(args) | |
498 | if filename is None: |
|
503 | if filename is None: | |
499 | warn('The file `%s` where `%s` was defined cannot ' |
|
504 | warn('The file `%s` where `%s` was defined cannot ' | |
500 | 'be read.' % (filename,data)) |
|
505 | 'be read.' % (filename,data)) | |
501 | return |
|
506 | return | |
502 | use_temp = 0 |
|
507 | use_temp = 0 | |
503 | else: |
|
508 | else: | |
504 | data = '' |
|
509 | data = '' | |
505 |
|
510 | |||
506 | if use_temp: |
|
511 | if use_temp: | |
507 | filename = self.shell.mktempfile(data) |
|
512 | filename = self.shell.mktempfile(data) | |
508 | print('IPython will make a temporary file named:', filename) |
|
513 | print('IPython will make a temporary file named:', filename) | |
509 |
|
514 | |||
510 | # Make sure we send to the client an absolute path, in case the working |
|
515 | # Make sure we send to the client an absolute path, in case the working | |
511 | # directory of client and kernel don't match |
|
516 | # directory of client and kernel don't match | |
512 | filename = os.path.abspath(filename) |
|
517 | filename = os.path.abspath(filename) | |
513 |
|
518 | |||
514 | payload = { |
|
519 | payload = { | |
515 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
520 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
516 | 'filename' : filename, |
|
521 | 'filename' : filename, | |
517 | 'line_number' : lineno |
|
522 | 'line_number' : lineno | |
518 | } |
|
523 | } | |
519 | self.payload_manager.write_payload(payload) |
|
524 | self.payload_manager.write_payload(payload) | |
520 |
|
525 | |||
521 | def magic_gui(self, *args, **kwargs): |
|
526 | def magic_gui(self, *args, **kwargs): | |
522 | raise NotImplementedError( |
|
527 | raise NotImplementedError( | |
523 | 'GUI support must be enabled in command line options.') |
|
528 | 'GUI support must be enabled in command line options.') | |
524 |
|
529 | |||
525 | def magic_pylab(self, *args, **kwargs): |
|
530 | def magic_pylab(self, *args, **kwargs): | |
526 | raise NotImplementedError( |
|
531 | raise NotImplementedError( | |
527 | 'pylab support must be enabled in command line options.') |
|
532 | 'pylab support must be enabled in command line options.') | |
528 |
|
533 | |||
529 | # A few magics that are adapted to the specifics of using pexpect and a |
|
534 | # A few magics that are adapted to the specifics of using pexpect and a | |
530 | # remote terminal |
|
535 | # remote terminal | |
531 |
|
536 | |||
532 | def magic_clear(self, arg_s): |
|
537 | def magic_clear(self, arg_s): | |
533 | """Clear the terminal.""" |
|
538 | """Clear the terminal.""" | |
534 | if os.name == 'posix': |
|
539 | if os.name == 'posix': | |
535 | self.shell.system("clear") |
|
540 | self.shell.system("clear") | |
536 | else: |
|
541 | else: | |
537 | self.shell.system("cls") |
|
542 | self.shell.system("cls") | |
538 |
|
543 | |||
539 | if os.name == 'nt': |
|
544 | if os.name == 'nt': | |
540 | # This is the usual name in windows |
|
545 | # This is the usual name in windows | |
541 | magic_cls = magic_clear |
|
546 | magic_cls = magic_clear | |
542 |
|
547 | |||
543 | # Terminal pagers won't work over pexpect, but we do have our own pager |
|
548 | # Terminal pagers won't work over pexpect, but we do have our own pager | |
544 |
|
549 | |||
545 | def magic_less(self, arg_s): |
|
550 | def magic_less(self, arg_s): | |
546 | """Show a file through the pager. |
|
551 | """Show a file through the pager. | |
547 |
|
552 | |||
548 | Files ending in .py are syntax-highlighted.""" |
|
553 | Files ending in .py are syntax-highlighted.""" | |
549 | cont = open(arg_s).read() |
|
554 | cont = open(arg_s).read() | |
550 | if arg_s.endswith('.py'): |
|
555 | if arg_s.endswith('.py'): | |
551 | cont = self.shell.pycolorize(cont) |
|
556 | cont = self.shell.pycolorize(cont) | |
552 | page.page(cont) |
|
557 | page.page(cont) | |
553 |
|
558 | |||
554 | magic_more = magic_less |
|
559 | magic_more = magic_less | |
555 |
|
560 | |||
556 | # Man calls a pager, so we also need to redefine it |
|
561 | # Man calls a pager, so we also need to redefine it | |
557 | if os.name == 'posix': |
|
562 | if os.name == 'posix': | |
558 | def magic_man(self, arg_s): |
|
563 | def magic_man(self, arg_s): | |
559 | """Find the man page for the given command and display in pager.""" |
|
564 | """Find the man page for the given command and display in pager.""" | |
560 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, |
|
565 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, | |
561 | split=False)) |
|
566 | split=False)) | |
562 |
|
567 | |||
563 | # FIXME: this is specific to the GUI, so we should let the gui app load |
|
568 | # FIXME: this is specific to the GUI, so we should let the gui app load | |
564 | # magics at startup that are only for the gui. Once the gui app has proper |
|
569 | # magics at startup that are only for the gui. Once the gui app has proper | |
565 | # profile and configuration management, we can have it initialize a kernel |
|
570 | # profile and configuration management, we can have it initialize a kernel | |
566 | # with a special config file that provides these. |
|
571 | # with a special config file that provides these. | |
567 | def magic_guiref(self, arg_s): |
|
572 | def magic_guiref(self, arg_s): | |
568 | """Show a basic reference about the GUI console.""" |
|
573 | """Show a basic reference about the GUI console.""" | |
569 | from IPython.core.usage import gui_reference |
|
574 | from IPython.core.usage import gui_reference | |
570 | page.page(gui_reference, auto_html=True) |
|
575 | page.page(gui_reference, auto_html=True) | |
571 |
|
576 | |||
572 | def magic_loadpy(self, arg_s): |
|
577 | def magic_loadpy(self, arg_s): | |
573 | """Load a .py python script into the GUI console. |
|
578 | """Load a .py python script into the GUI console. | |
574 |
|
579 | |||
575 | This magic command can either take a local filename or a url:: |
|
580 | This magic command can either take a local filename or a url:: | |
576 |
|
581 | |||
577 | %loadpy myscript.py |
|
582 | %loadpy myscript.py | |
578 | %loadpy http://www.example.com/myscript.py |
|
583 | %loadpy http://www.example.com/myscript.py | |
579 | """ |
|
584 | """ | |
580 | if not arg_s.endswith('.py'): |
|
585 | if not arg_s.endswith('.py'): | |
581 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
586 | raise ValueError('%%load only works with .py files: %s' % arg_s) | |
582 | if arg_s.startswith('http'): |
|
587 | if arg_s.startswith('http'): | |
583 | import urllib2 |
|
588 | import urllib2 | |
584 | response = urllib2.urlopen(arg_s) |
|
589 | response = urllib2.urlopen(arg_s) | |
585 | content = response.read() |
|
590 | content = response.read() | |
586 | else: |
|
591 | else: | |
587 | content = open(arg_s).read() |
|
592 | content = open(arg_s).read() | |
588 | payload = dict( |
|
593 | payload = dict( | |
589 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', |
|
594 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', | |
590 | text=content |
|
595 | text=content | |
591 | ) |
|
596 | ) | |
592 | self.payload_manager.write_payload(payload) |
|
597 | self.payload_manager.write_payload(payload) | |
593 |
|
598 | |||
594 | def magic_Exit(self, parameter_s=''): |
|
599 | def magic_Exit(self, parameter_s=''): | |
595 | """Exit IPython. If the -k option is provided, the kernel will be left |
|
600 | """Exit IPython. If the -k option is provided, the kernel will be left | |
596 | running. Otherwise, it will shutdown without prompting. |
|
601 | running. Otherwise, it will shutdown without prompting. | |
597 | """ |
|
602 | """ | |
598 | opts,args = self.parse_options(parameter_s,'k') |
|
603 | opts,args = self.parse_options(parameter_s,'k') | |
599 | self.shell.keepkernel_on_exit = opts.has_key('k') |
|
604 | self.shell.keepkernel_on_exit = opts.has_key('k') | |
600 | self.shell.ask_exit() |
|
605 | self.shell.ask_exit() | |
601 |
|
606 | |||
602 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
607 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
603 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
608 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
604 |
|
609 | |||
605 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
610 | InteractiveShellABC.register(ZMQInteractiveShell) |
@@ -1,375 +1,369 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | This module defines the things that are used in setup.py for building IPython |
|
3 | This module defines the things that are used in setup.py for building IPython | |
4 |
|
4 | |||
5 | This includes: |
|
5 | This includes: | |
6 |
|
6 | |||
7 | * The basic arguments to setup |
|
7 | * The basic arguments to setup | |
8 | * Functions for finding things like packages, package data, etc. |
|
8 | * Functions for finding things like packages, package data, etc. | |
9 | * A function for checking dependencies. |
|
9 | * A function for checking dependencies. | |
10 | """ |
|
10 | """ | |
11 | from __future__ import print_function |
|
11 | from __future__ import print_function | |
12 |
|
12 | |||
13 | #------------------------------------------------------------------------------- |
|
13 | #------------------------------------------------------------------------------- | |
14 | # Copyright (C) 2008 The IPython Development Team |
|
14 | # Copyright (C) 2008 The IPython Development Team | |
15 | # |
|
15 | # | |
16 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | # Distributed under the terms of the BSD License. The full license is in | |
17 | # the file COPYING, distributed as part of this software. |
|
17 | # the file COPYING, distributed as part of this software. | |
18 | #------------------------------------------------------------------------------- |
|
18 | #------------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | #------------------------------------------------------------------------------- |
|
20 | #------------------------------------------------------------------------------- | |
21 | # Imports |
|
21 | # Imports | |
22 | #------------------------------------------------------------------------------- |
|
22 | #------------------------------------------------------------------------------- | |
23 | import os |
|
23 | import os | |
24 | import sys |
|
24 | import sys | |
25 |
|
25 | |||
26 | from ConfigParser import ConfigParser |
|
26 | from ConfigParser import ConfigParser | |
27 | from distutils.command.build_py import build_py |
|
27 | from distutils.command.build_py import build_py | |
28 | from glob import glob |
|
28 | from glob import glob | |
29 |
|
29 | |||
30 | from setupext import install_data_ext |
|
30 | from setupext import install_data_ext | |
31 |
|
31 | |||
32 | #------------------------------------------------------------------------------- |
|
32 | #------------------------------------------------------------------------------- | |
33 | # Useful globals and utility functions |
|
33 | # Useful globals and utility functions | |
34 | #------------------------------------------------------------------------------- |
|
34 | #------------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | # A few handy globals |
|
36 | # A few handy globals | |
37 | isfile = os.path.isfile |
|
37 | isfile = os.path.isfile | |
38 | pjoin = os.path.join |
|
38 | pjoin = os.path.join | |
39 |
|
39 | |||
40 | def oscmd(s): |
|
40 | def oscmd(s): | |
41 | print(">", s) |
|
41 | print(">", s) | |
42 | os.system(s) |
|
42 | os.system(s) | |
43 |
|
43 | |||
44 | # A little utility we'll need below, since glob() does NOT allow you to do |
|
44 | # A little utility we'll need below, since glob() does NOT allow you to do | |
45 | # exclusion on multiple endings! |
|
45 | # exclusion on multiple endings! | |
46 | def file_doesnt_endwith(test,endings): |
|
46 | def file_doesnt_endwith(test,endings): | |
47 | """Return true if test is a file and its name does NOT end with any |
|
47 | """Return true if test is a file and its name does NOT end with any | |
48 | of the strings listed in endings.""" |
|
48 | of the strings listed in endings.""" | |
49 | if not isfile(test): |
|
49 | if not isfile(test): | |
50 | return False |
|
50 | return False | |
51 | for e in endings: |
|
51 | for e in endings: | |
52 | if test.endswith(e): |
|
52 | if test.endswith(e): | |
53 | return False |
|
53 | return False | |
54 | return True |
|
54 | return True | |
55 |
|
55 | |||
56 | #--------------------------------------------------------------------------- |
|
56 | #--------------------------------------------------------------------------- | |
57 | # Basic project information |
|
57 | # Basic project information | |
58 | #--------------------------------------------------------------------------- |
|
58 | #--------------------------------------------------------------------------- | |
59 |
|
59 | |||
60 | # release.py contains version, authors, license, url, keywords, etc. |
|
60 | # release.py contains version, authors, license, url, keywords, etc. | |
61 | execfile(pjoin('IPython','core','release.py')) |
|
61 | execfile(pjoin('IPython','core','release.py')) | |
62 |
|
62 | |||
63 | # Create a dict with the basic information |
|
63 | # Create a dict with the basic information | |
64 | # This dict is eventually passed to setup after additional keys are added. |
|
64 | # This dict is eventually passed to setup after additional keys are added. | |
65 | setup_args = dict( |
|
65 | setup_args = dict( | |
66 | name = name, |
|
66 | name = name, | |
67 | version = version, |
|
67 | version = version, | |
68 | description = description, |
|
68 | description = description, | |
69 | long_description = long_description, |
|
69 | long_description = long_description, | |
70 | author = author, |
|
70 | author = author, | |
71 | author_email = author_email, |
|
71 | author_email = author_email, | |
72 | url = url, |
|
72 | url = url, | |
73 | download_url = download_url, |
|
73 | download_url = download_url, | |
74 | license = license, |
|
74 | license = license, | |
75 | platforms = platforms, |
|
75 | platforms = platforms, | |
76 | keywords = keywords, |
|
76 | keywords = keywords, | |
77 | cmdclass = {'install_data': install_data_ext}, |
|
77 | cmdclass = {'install_data': install_data_ext}, | |
78 | ) |
|
78 | ) | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | #--------------------------------------------------------------------------- |
|
81 | #--------------------------------------------------------------------------- | |
82 | # Find packages |
|
82 | # Find packages | |
83 | #--------------------------------------------------------------------------- |
|
83 | #--------------------------------------------------------------------------- | |
84 |
|
84 | |||
85 | def add_package(packages,pname,config=False,tests=False,scripts=False, |
|
85 | def add_package(packages,pname,config=False,tests=False,scripts=False, | |
86 | others=None): |
|
86 | others=None): | |
87 | """ |
|
87 | """ | |
88 | Add a package to the list of packages, including certain subpackages. |
|
88 | Add a package to the list of packages, including certain subpackages. | |
89 | """ |
|
89 | """ | |
90 | packages.append('.'.join(['IPython',pname])) |
|
90 | packages.append('.'.join(['IPython',pname])) | |
91 | if config: |
|
91 | if config: | |
92 | packages.append('.'.join(['IPython',pname,'config'])) |
|
92 | packages.append('.'.join(['IPython',pname,'config'])) | |
93 | if tests: |
|
93 | if tests: | |
94 | packages.append('.'.join(['IPython',pname,'tests'])) |
|
94 | packages.append('.'.join(['IPython',pname,'tests'])) | |
95 | if scripts: |
|
95 | if scripts: | |
96 | packages.append('.'.join(['IPython',pname,'scripts'])) |
|
96 | packages.append('.'.join(['IPython',pname,'scripts'])) | |
97 | if others is not None: |
|
97 | if others is not None: | |
98 | for o in others: |
|
98 | for o in others: | |
99 | packages.append('.'.join(['IPython',pname,o])) |
|
99 | packages.append('.'.join(['IPython',pname,o])) | |
100 |
|
100 | |||
101 | def find_packages(): |
|
101 | def find_packages(): | |
102 | """ |
|
102 | """ | |
103 | Find all of IPython's packages. |
|
103 | Find all of IPython's packages. | |
104 | """ |
|
104 | """ | |
105 | packages = ['IPython'] |
|
105 | packages = ['IPython'] | |
106 | add_package(packages, 'config', tests=True, others=['default','profile']) |
|
106 | add_package(packages, 'config', tests=True, others=['default','profile']) | |
107 | add_package(packages, 'core', tests=True) |
|
107 | add_package(packages, 'core', tests=True) | |
108 | add_package(packages, 'deathrow', tests=True) |
|
108 | add_package(packages, 'deathrow', tests=True) | |
109 | add_package(packages, 'extensions') |
|
109 | add_package(packages, 'extensions') | |
110 | add_package(packages, 'external') |
|
110 | add_package(packages, 'external') | |
111 | add_package(packages, 'frontend') |
|
111 | add_package(packages, 'frontend') | |
112 | add_package(packages, 'frontend.qt') |
|
112 | add_package(packages, 'frontend.qt') | |
113 | add_package(packages, 'frontend.qt.console', tests=True) |
|
113 | add_package(packages, 'frontend.qt.console', tests=True) | |
114 | add_package(packages, 'frontend.terminal', tests=True) |
|
114 | add_package(packages, 'frontend.terminal', tests=True) | |
115 | add_package(packages, 'kernel', config=False, tests=True, scripts=True) |
|
115 | add_package(packages, 'kernel', config=False, tests=True, scripts=True) | |
116 | add_package(packages, 'kernel.core', config=False, tests=True) |
|
116 | add_package(packages, 'kernel.core', config=False, tests=True) | |
117 | add_package(packages, 'lib', tests=True) |
|
117 | add_package(packages, 'lib', tests=True) | |
118 | add_package(packages, 'quarantine', tests=True) |
|
118 | add_package(packages, 'quarantine', tests=True) | |
119 | add_package(packages, 'scripts') |
|
119 | add_package(packages, 'scripts') | |
120 | add_package(packages, 'testing', tests=True) |
|
120 | add_package(packages, 'testing', tests=True) | |
121 | add_package(packages, 'testing.plugin', tests=False) |
|
121 | add_package(packages, 'testing.plugin', tests=False) | |
122 | add_package(packages, 'utils', tests=True) |
|
122 | add_package(packages, 'utils', tests=True) | |
123 | add_package(packages, 'zmq') |
|
123 | add_package(packages, 'zmq') | |
124 | add_package(packages, 'zmq.pylab') |
|
124 | add_package(packages, 'zmq.pylab') | |
125 | return packages |
|
125 | return packages | |
126 |
|
126 | |||
127 | #--------------------------------------------------------------------------- |
|
127 | #--------------------------------------------------------------------------- | |
128 | # Find package data |
|
128 | # Find package data | |
129 | #--------------------------------------------------------------------------- |
|
129 | #--------------------------------------------------------------------------- | |
130 |
|
130 | |||
131 | def find_package_data(): |
|
131 | def find_package_data(): | |
132 | """ |
|
132 | """ | |
133 | Find IPython's package_data. |
|
133 | Find IPython's package_data. | |
134 | """ |
|
134 | """ | |
135 | # This is not enough for these things to appear in an sdist. |
|
135 | # This is not enough for these things to appear in an sdist. | |
136 | # We need to muck with the MANIFEST to get this to work |
|
136 | # We need to muck with the MANIFEST to get this to work | |
137 | package_data = { |
|
137 | package_data = { | |
138 | 'IPython.config.userconfig' : ['*'], |
|
138 | 'IPython.config.userconfig' : ['*'], | |
139 | 'IPython.testing' : ['*.txt'] |
|
139 | 'IPython.testing' : ['*.txt'] | |
140 | } |
|
140 | } | |
141 | return package_data |
|
141 | return package_data | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | #--------------------------------------------------------------------------- |
|
144 | #--------------------------------------------------------------------------- | |
145 | # Find data files |
|
145 | # Find data files | |
146 | #--------------------------------------------------------------------------- |
|
146 | #--------------------------------------------------------------------------- | |
147 |
|
147 | |||
148 | def make_dir_struct(tag,base,out_base): |
|
148 | def make_dir_struct(tag,base,out_base): | |
149 | """Make the directory structure of all files below a starting dir. |
|
149 | """Make the directory structure of all files below a starting dir. | |
150 |
|
150 | |||
151 | This is just a convenience routine to help build a nested directory |
|
151 | This is just a convenience routine to help build a nested directory | |
152 | hierarchy because distutils is too stupid to do this by itself. |
|
152 | hierarchy because distutils is too stupid to do this by itself. | |
153 |
|
153 | |||
154 | XXX - this needs a proper docstring! |
|
154 | XXX - this needs a proper docstring! | |
155 | """ |
|
155 | """ | |
156 |
|
156 | |||
157 | # we'll use these a lot below |
|
157 | # we'll use these a lot below | |
158 | lbase = len(base) |
|
158 | lbase = len(base) | |
159 | pathsep = os.path.sep |
|
159 | pathsep = os.path.sep | |
160 | lpathsep = len(pathsep) |
|
160 | lpathsep = len(pathsep) | |
161 |
|
161 | |||
162 | out = [] |
|
162 | out = [] | |
163 | for (dirpath,dirnames,filenames) in os.walk(base): |
|
163 | for (dirpath,dirnames,filenames) in os.walk(base): | |
164 | # we need to strip out the dirpath from the base to map it to the |
|
164 | # we need to strip out the dirpath from the base to map it to the | |
165 | # output (installation) path. This requires possibly stripping the |
|
165 | # output (installation) path. This requires possibly stripping the | |
166 | # path separator, because otherwise pjoin will not work correctly |
|
166 | # path separator, because otherwise pjoin will not work correctly | |
167 | # (pjoin('foo/','/bar') returns '/bar'). |
|
167 | # (pjoin('foo/','/bar') returns '/bar'). | |
168 |
|
168 | |||
169 | dp_eff = dirpath[lbase:] |
|
169 | dp_eff = dirpath[lbase:] | |
170 | if dp_eff.startswith(pathsep): |
|
170 | if dp_eff.startswith(pathsep): | |
171 | dp_eff = dp_eff[lpathsep:] |
|
171 | dp_eff = dp_eff[lpathsep:] | |
172 | # The output path must be anchored at the out_base marker |
|
172 | # The output path must be anchored at the out_base marker | |
173 | out_path = pjoin(out_base,dp_eff) |
|
173 | out_path = pjoin(out_base,dp_eff) | |
174 | # Now we can generate the final filenames. Since os.walk only produces |
|
174 | # Now we can generate the final filenames. Since os.walk only produces | |
175 | # filenames, we must join back with the dirpath to get full valid file |
|
175 | # filenames, we must join back with the dirpath to get full valid file | |
176 | # paths: |
|
176 | # paths: | |
177 | pfiles = [pjoin(dirpath,f) for f in filenames] |
|
177 | pfiles = [pjoin(dirpath,f) for f in filenames] | |
178 | # Finally, generate the entry we need, which is a pari of (output |
|
178 | # Finally, generate the entry we need, which is a pari of (output | |
179 | # path, files) for use as a data_files parameter in install_data. |
|
179 | # path, files) for use as a data_files parameter in install_data. | |
180 | out.append((out_path, pfiles)) |
|
180 | out.append((out_path, pfiles)) | |
181 |
|
181 | |||
182 | return out |
|
182 | return out | |
183 |
|
183 | |||
184 |
|
184 | |||
185 | def find_data_files(): |
|
185 | def find_data_files(): | |
186 | """ |
|
186 | """ | |
187 | Find IPython's data_files. |
|
187 | Find IPython's data_files. | |
188 |
|
188 | |||
189 | Most of these are docs. |
|
189 | Most of these are docs. | |
190 | """ |
|
190 | """ | |
191 |
|
191 | |||
192 | docdirbase = pjoin('share', 'doc', 'ipython') |
|
192 | docdirbase = pjoin('share', 'doc', 'ipython') | |
193 | manpagebase = pjoin('share', 'man', 'man1') |
|
193 | manpagebase = pjoin('share', 'man', 'man1') | |
194 |
|
194 | |||
195 | # Simple file lists can be made by hand |
|
195 | # Simple file lists can be made by hand | |
196 | manpages = filter(isfile, glob(pjoin('docs','man','*.1.gz'))) |
|
196 | manpages = filter(isfile, glob(pjoin('docs','man','*.1.gz'))) | |
197 | igridhelpfiles = filter(isfile, |
|
197 | igridhelpfiles = filter(isfile, | |
198 | glob(pjoin('IPython','extensions','igrid_help.*'))) |
|
198 | glob(pjoin('IPython','extensions','igrid_help.*'))) | |
199 |
|
199 | |||
200 | # For nested structures, use the utility above |
|
200 | # For nested structures, use the utility above | |
201 | example_files = make_dir_struct( |
|
201 | example_files = make_dir_struct( | |
202 | 'data', |
|
202 | 'data', | |
203 | pjoin('docs','examples'), |
|
203 | pjoin('docs','examples'), | |
204 | pjoin(docdirbase,'examples') |
|
204 | pjoin(docdirbase,'examples') | |
205 | ) |
|
205 | ) | |
206 | manual_files = make_dir_struct( |
|
206 | manual_files = make_dir_struct( | |
207 | 'data', |
|
207 | 'data', | |
208 | pjoin('docs','dist'), |
|
208 | pjoin('docs','dist'), | |
209 | pjoin(docdirbase,'manual') |
|
209 | pjoin(docdirbase,'manual') | |
210 | ) |
|
210 | ) | |
211 |
|
211 | |||
212 | # And assemble the entire output list |
|
212 | # And assemble the entire output list | |
213 | data_files = [ (manpagebase, manpages), |
|
213 | data_files = [ (manpagebase, manpages), | |
214 | (pjoin(docdirbase, 'extensions'), igridhelpfiles), |
|
214 | (pjoin(docdirbase, 'extensions'), igridhelpfiles), | |
215 | ] + manual_files + example_files |
|
215 | ] + manual_files + example_files | |
216 |
|
216 | |||
217 | ## import pprint # dbg |
|
|||
218 | ## print('*'*80) |
|
|||
219 | ## print('data files') |
|
|||
220 | ## pprint.pprint(data_files) |
|
|||
221 | ## print('*'*80) |
|
|||
222 |
|
||||
223 | return data_files |
|
217 | return data_files | |
224 |
|
218 | |||
225 |
|
219 | |||
226 | def make_man_update_target(manpage): |
|
220 | def make_man_update_target(manpage): | |
227 | """Return a target_update-compliant tuple for the given manpage. |
|
221 | """Return a target_update-compliant tuple for the given manpage. | |
228 |
|
222 | |||
229 | Parameters |
|
223 | Parameters | |
230 | ---------- |
|
224 | ---------- | |
231 | manpage : string |
|
225 | manpage : string | |
232 | Name of the manpage, must include the section number (trailing number). |
|
226 | Name of the manpage, must include the section number (trailing number). | |
233 |
|
227 | |||
234 | Example |
|
228 | Example | |
235 | ------- |
|
229 | ------- | |
236 |
|
230 | |||
237 | >>> make_man_update_target('ipython.1') #doctest: +NORMALIZE_WHITESPACE |
|
231 | >>> make_man_update_target('ipython.1') #doctest: +NORMALIZE_WHITESPACE | |
238 | ('docs/man/ipython.1.gz', |
|
232 | ('docs/man/ipython.1.gz', | |
239 | ['docs/man/ipython.1'], |
|
233 | ['docs/man/ipython.1'], | |
240 | 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz') |
|
234 | 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz') | |
241 | """ |
|
235 | """ | |
242 | man_dir = pjoin('docs', 'man') |
|
236 | man_dir = pjoin('docs', 'man') | |
243 | manpage_gz = manpage + '.gz' |
|
237 | manpage_gz = manpage + '.gz' | |
244 | manpath = pjoin(man_dir, manpage) |
|
238 | manpath = pjoin(man_dir, manpage) | |
245 | manpath_gz = pjoin(man_dir, manpage_gz) |
|
239 | manpath_gz = pjoin(man_dir, manpage_gz) | |
246 | gz_cmd = ( "cd %(man_dir)s && gzip -9c %(manpage)s > %(manpage_gz)s" % |
|
240 | gz_cmd = ( "cd %(man_dir)s && gzip -9c %(manpage)s > %(manpage_gz)s" % | |
247 | locals() ) |
|
241 | locals() ) | |
248 | return (manpath_gz, [manpath], gz_cmd) |
|
242 | return (manpath_gz, [manpath], gz_cmd) | |
249 |
|
243 | |||
250 | #--------------------------------------------------------------------------- |
|
244 | #--------------------------------------------------------------------------- | |
251 | # Find scripts |
|
245 | # Find scripts | |
252 | #--------------------------------------------------------------------------- |
|
246 | #--------------------------------------------------------------------------- | |
253 |
|
247 | |||
254 | def find_scripts(): |
|
248 | def find_scripts(): | |
255 | """ |
|
249 | """ | |
256 | Find IPython's scripts. |
|
250 | Find IPython's scripts. | |
257 | """ |
|
251 | """ | |
258 | kernel_scripts = pjoin('IPython','kernel','scripts') |
|
252 | kernel_scripts = pjoin('IPython','kernel','scripts') | |
259 | main_scripts = pjoin('IPython','scripts') |
|
253 | main_scripts = pjoin('IPython','scripts') | |
260 | scripts = [pjoin(kernel_scripts, 'ipengine'), |
|
254 | scripts = [pjoin(kernel_scripts, 'ipengine'), | |
261 | pjoin(kernel_scripts, 'ipcontroller'), |
|
255 | pjoin(kernel_scripts, 'ipcontroller'), | |
262 | pjoin(kernel_scripts, 'ipcluster'), |
|
256 | pjoin(kernel_scripts, 'ipcluster'), | |
263 | pjoin(main_scripts, 'ipython'), |
|
257 | pjoin(main_scripts, 'ipython'), | |
264 | pjoin(main_scripts, 'ipython-qtconsole'), |
|
258 | pjoin(main_scripts, 'ipython-qtconsole'), | |
265 | pjoin(main_scripts, 'pycolor'), |
|
259 | pjoin(main_scripts, 'pycolor'), | |
266 | pjoin(main_scripts, 'irunner'), |
|
260 | pjoin(main_scripts, 'irunner'), | |
267 | pjoin(main_scripts, 'iptest') |
|
261 | pjoin(main_scripts, 'iptest') | |
268 | ] |
|
262 | ] | |
269 |
|
263 | |||
270 | # Script to be run by the windows binary installer after the default setup |
|
264 | # Script to be run by the windows binary installer after the default setup | |
271 | # routine, to add shortcuts and similar windows-only things. Windows |
|
265 | # routine, to add shortcuts and similar windows-only things. Windows | |
272 | # post-install scripts MUST reside in the scripts/ dir, otherwise distutils |
|
266 | # post-install scripts MUST reside in the scripts/ dir, otherwise distutils | |
273 | # doesn't find them. |
|
267 | # doesn't find them. | |
274 | if 'bdist_wininst' in sys.argv: |
|
268 | if 'bdist_wininst' in sys.argv: | |
275 | if len(sys.argv) > 2 and \ |
|
269 | if len(sys.argv) > 2 and \ | |
276 | ('sdist' in sys.argv or 'bdist_rpm' in sys.argv): |
|
270 | ('sdist' in sys.argv or 'bdist_rpm' in sys.argv): | |
277 | print("ERROR: bdist_wininst must be run alone. Exiting.", |
|
271 | print("ERROR: bdist_wininst must be run alone. Exiting.", | |
278 | file=sys.stderr) |
|
272 | file=sys.stderr) | |
279 | sys.exit(1) |
|
273 | sys.exit(1) | |
280 | scripts.append(pjoin('scripts','ipython_win_post_install.py')) |
|
274 | scripts.append(pjoin('scripts','ipython_win_post_install.py')) | |
281 |
|
275 | |||
282 | return scripts |
|
276 | return scripts | |
283 |
|
277 | |||
284 | #--------------------------------------------------------------------------- |
|
278 | #--------------------------------------------------------------------------- | |
285 | # Verify all dependencies |
|
279 | # Verify all dependencies | |
286 | #--------------------------------------------------------------------------- |
|
280 | #--------------------------------------------------------------------------- | |
287 |
|
281 | |||
288 | def check_for_dependencies(): |
|
282 | def check_for_dependencies(): | |
289 | """Check for IPython's dependencies. |
|
283 | """Check for IPython's dependencies. | |
290 |
|
284 | |||
291 | This function should NOT be called if running under setuptools! |
|
285 | This function should NOT be called if running under setuptools! | |
292 | """ |
|
286 | """ | |
293 | from setupext.setupext import ( |
|
287 | from setupext.setupext import ( | |
294 | print_line, print_raw, print_status, |
|
288 | print_line, print_raw, print_status, | |
295 | check_for_zopeinterface, check_for_twisted, |
|
289 | check_for_zopeinterface, check_for_twisted, | |
296 | check_for_foolscap, check_for_pyopenssl, |
|
290 | check_for_foolscap, check_for_pyopenssl, | |
297 | check_for_sphinx, check_for_pygments, |
|
291 | check_for_sphinx, check_for_pygments, | |
298 | check_for_nose, check_for_pexpect |
|
292 | check_for_nose, check_for_pexpect | |
299 | ) |
|
293 | ) | |
300 | print_line() |
|
294 | print_line() | |
301 | print_raw("BUILDING IPYTHON") |
|
295 | print_raw("BUILDING IPYTHON") | |
302 | print_status('python', sys.version) |
|
296 | print_status('python', sys.version) | |
303 | print_status('platform', sys.platform) |
|
297 | print_status('platform', sys.platform) | |
304 | if sys.platform == 'win32': |
|
298 | if sys.platform == 'win32': | |
305 | print_status('Windows version', sys.getwindowsversion()) |
|
299 | print_status('Windows version', sys.getwindowsversion()) | |
306 |
|
300 | |||
307 | print_raw("") |
|
301 | print_raw("") | |
308 | print_raw("OPTIONAL DEPENDENCIES") |
|
302 | print_raw("OPTIONAL DEPENDENCIES") | |
309 |
|
303 | |||
310 | check_for_zopeinterface() |
|
304 | check_for_zopeinterface() | |
311 | check_for_twisted() |
|
305 | check_for_twisted() | |
312 | check_for_foolscap() |
|
306 | check_for_foolscap() | |
313 | check_for_pyopenssl() |
|
307 | check_for_pyopenssl() | |
314 | check_for_sphinx() |
|
308 | check_for_sphinx() | |
315 | check_for_pygments() |
|
309 | check_for_pygments() | |
316 | check_for_nose() |
|
310 | check_for_nose() | |
317 | check_for_pexpect() |
|
311 | check_for_pexpect() | |
318 |
|
312 | |||
319 |
|
313 | |||
320 | def record_commit_info(pkg_dir, build_cmd=build_py): |
|
314 | def record_commit_info(pkg_dir, build_cmd=build_py): | |
321 | """ Return extended build command class for recording commit |
|
315 | """ Return extended build command class for recording commit | |
322 |
|
316 | |||
323 | The extended command tries to run git to find the current commit, getting |
|
317 | The extended command tries to run git to find the current commit, getting | |
324 | the empty string if it fails. It then writes the commit hash into a file |
|
318 | the empty string if it fails. It then writes the commit hash into a file | |
325 | in the `pkg_dir` path, named ``.git_commit_info.ini``. |
|
319 | in the `pkg_dir` path, named ``.git_commit_info.ini``. | |
326 |
|
320 | |||
327 | In due course this information can be used by the package after it is |
|
321 | In due course this information can be used by the package after it is | |
328 | installed, to tell you what commit it was installed from if known. |
|
322 | installed, to tell you what commit it was installed from if known. | |
329 |
|
323 | |||
330 | To make use of this system, you need a package with a .git_commit_info.ini |
|
324 | To make use of this system, you need a package with a .git_commit_info.ini | |
331 | file - e.g. ``myproject/.git_commit_info.ini`` - that might well look like |
|
325 | file - e.g. ``myproject/.git_commit_info.ini`` - that might well look like | |
332 | this:: |
|
326 | this:: | |
333 |
|
327 | |||
334 | # This is an ini file that may contain information about the code state |
|
328 | # This is an ini file that may contain information about the code state | |
335 | [commit hash] |
|
329 | [commit hash] | |
336 | # The line below may contain a valid hash if it has been substituted |
|
330 | # The line below may contain a valid hash if it has been substituted | |
337 | # during 'git archive' |
|
331 | # during 'git archive' | |
338 | archive_subst_hash=$Format:%h$ |
|
332 | archive_subst_hash=$Format:%h$ | |
339 | # This line may be modified by the install process |
|
333 | # This line may be modified by the install process | |
340 | install_hash= |
|
334 | install_hash= | |
341 |
|
335 | |||
342 | The .git_commit_info file above is also designed to be used with git |
|
336 | The .git_commit_info file above is also designed to be used with git | |
343 | substitution - so you probably also want a ``.gitattributes`` file in the |
|
337 | substitution - so you probably also want a ``.gitattributes`` file in the | |
344 | root directory of your working tree that contains something like this:: |
|
338 | root directory of your working tree that contains something like this:: | |
345 |
|
339 | |||
346 | myproject/.git_commit_info.ini export-subst |
|
340 | myproject/.git_commit_info.ini export-subst | |
347 |
|
341 | |||
348 | That will cause the ``.git_commit_info.ini`` file to get filled in by ``git |
|
342 | That will cause the ``.git_commit_info.ini`` file to get filled in by ``git | |
349 | archive`` - useful in case someone makes such an archive - for example with |
|
343 | archive`` - useful in case someone makes such an archive - for example with | |
350 | via the github 'download source' button. |
|
344 | via the github 'download source' button. | |
351 |
|
345 | |||
352 | Although all the above will work as is, you might consider having something |
|
346 | Although all the above will work as is, you might consider having something | |
353 | like a ``get_info()`` function in your package to display the commit |
|
347 | like a ``get_info()`` function in your package to display the commit | |
354 | information at the terminal. See the ``pkg_info.py`` module in the nipy |
|
348 | information at the terminal. See the ``pkg_info.py`` module in the nipy | |
355 | package for an example. |
|
349 | package for an example. | |
356 | """ |
|
350 | """ | |
357 | class MyBuildPy(build_cmd): |
|
351 | class MyBuildPy(build_cmd): | |
358 | ''' Subclass to write commit data into installation tree ''' |
|
352 | ''' Subclass to write commit data into installation tree ''' | |
359 | def run(self): |
|
353 | def run(self): | |
360 | build_py.run(self) |
|
354 | build_py.run(self) | |
361 | import subprocess |
|
355 | import subprocess | |
362 | proc = subprocess.Popen('git rev-parse --short HEAD', |
|
356 | proc = subprocess.Popen('git rev-parse --short HEAD', | |
363 | stdout=subprocess.PIPE, |
|
357 | stdout=subprocess.PIPE, | |
364 | stderr=subprocess.PIPE, |
|
358 | stderr=subprocess.PIPE, | |
365 | shell=True) |
|
359 | shell=True) | |
366 | repo_commit, _ = proc.communicate() |
|
360 | repo_commit, _ = proc.communicate() | |
367 | # We write the installation commit even if it's empty |
|
361 | # We write the installation commit even if it's empty | |
368 | cfg_parser = ConfigParser() |
|
362 | cfg_parser = ConfigParser() | |
369 | cfg_parser.read(pjoin(pkg_dir, '.git_commit_info.ini')) |
|
363 | cfg_parser.read(pjoin(pkg_dir, '.git_commit_info.ini')) | |
370 | cfg_parser.set('commit hash', 'install_hash', repo_commit) |
|
364 | cfg_parser.set('commit hash', 'install_hash', repo_commit) | |
371 | out_pth = pjoin(self.build_lib, pkg_dir, '.git_commit_info.ini') |
|
365 | out_pth = pjoin(self.build_lib, pkg_dir, '.git_commit_info.ini') | |
372 | out_file = open(out_pth, 'wt') |
|
366 | out_file = open(out_pth, 'wt') | |
373 | cfg_parser.write(out_file) |
|
367 | cfg_parser.write(out_file) | |
374 | out_file.close() |
|
368 | out_file.close() | |
375 | return MyBuildPy |
|
369 | return MyBuildPy |
General Comments 0
You need to be logged in to leave comments.
Login now