##// END OF EJS Templates
Merge branch 'sqlite-history' of github.com:takluyver/ipython
Thomas Kluyver -
r3439:d7ca41af merge
parent child Browse files
Show More

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

@@ -1,150 +1,161 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.prompt_in1 = 'In [\#]: '
84 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
87 # c.InteractiveShell.prompts_pad_left = True
87 # c.InteractiveShell.prompts_pad_left = True
88
88
89 # c.InteractiveShell.quiet = False
89 # c.InteractiveShell.quiet = False
90
90
91 # c.InteractiveShell.history_length = 10000
91 # c.InteractiveShell.history_length = 10000
92
92
93 # Readline
93 # Readline
94 # c.InteractiveShell.readline_use = True
94 # c.InteractiveShell.readline_use = True
95
95
96 # c.InteractiveShell.readline_parse_and_bind = [
96 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
97 # 'tab: complete',
98 # '"\C-l": possible-completions',
98 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
99 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
100 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
101 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
102 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
104 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
105 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
106 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
107 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
108 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
109 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
110 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
111 # '"\C-u": unix-line-discard',
112 # ]
112 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit__names = 0
115 # c.InteractiveShell.readline_omit__names = 0
116
116
117 # c.TerminalInteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
118
118
119 # c.InteractiveShell.separate_in = '\n'
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
121 # c.InteractiveShell.separate_out2 = ''
122
122
123 # c.TerminalInteractiveShell.term_title = False
123 # c.TerminalInteractiveShell.term_title = False
124
124
125 # c.InteractiveShell.wildcards_case_sensitive = True
125 # c.InteractiveShell.wildcards_case_sensitive = True
126
126
127 # c.InteractiveShell.xmode = 'Context'
127 # c.InteractiveShell.xmode = 'Context'
128
128
129 #-----------------------------------------------------------------------------
129 #-----------------------------------------------------------------------------
130 # Formatter and display options
130 # Formatter and display options
131 #-----------------------------------------------------------------------------
131 #-----------------------------------------------------------------------------
132
132
133 # c.PlainTextFormatter.pprint = True
133 # c.PlainTextFormatter.pprint = True
134
134
135 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
136 # PrefilterManager options
136 # PrefilterManager options
137 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
138
138
139 # c.PrefilterManager.multi_line_specials = True
139 # c.PrefilterManager.multi_line_specials = True
140
140
141 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
142 # AliasManager options
142 # AliasManager options
143 #-----------------------------------------------------------------------------
143 #-----------------------------------------------------------------------------
144
144
145 # Do this to disable all defaults
145 # Do this to disable all defaults
146 # c.AliasManager.default_aliases = []
146 # c.AliasManager.default_aliases = []
147
147
148 # c.AliasManager.user_aliases = [
148 # c.AliasManager.user_aliases = [
149 # ('foo', 'echo Hi')
149 # ('foo', 'echo Hi')
150 # ]
150 # ]
151
152 #-----------------------------------------------------------------------------
153 # HistoryManager options
154 #-----------------------------------------------------------------------------
155
156 # Enable logging output as well as input to the database.
157 # c.HistoryManager.db_log_output = False
158
159 # Only write to the database every n commands - this can save disk
160 # access (and hence power) over the default of writing on every command.
161 # c.HistoryManager.db_cache_size = 0
@@ -1,324 +1,327 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
4 This defines a callable class that IPython uses for `sys.displayhook`.
5
5
6 Authors:
6 Authors:
7
7
8 * Fernando Perez
8 * Fernando Perez
9 * Brian Granger
9 * Brian Granger
10 * Robert Kern
10 * Robert Kern
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2010 The IPython Development Team
14 # Copyright (C) 2008-2010 The IPython Development Team
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
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 import __builtin__
25 import __builtin__
26
26
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
28 from IPython.core import prompts
28 from IPython.core import prompts
29 import IPython.utils.generics
29 import IPython.utils.generics
30 import IPython.utils.io
30 import IPython.utils.io
31 from IPython.utils.traitlets import Instance, List
31 from IPython.utils.traitlets import Instance, List
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Main displayhook class
35 # Main displayhook class
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 # TODO: The DisplayHook class should be split into two classes, one that
38 # TODO: The DisplayHook class should be split into two classes, one that
39 # manages the prompts and their synchronization and another that just does the
39 # manages the prompts and their synchronization and another that just does the
40 # displayhook logic and calls into the prompt manager.
40 # displayhook logic and calls into the prompt manager.
41
41
42 # TODO: Move the various attributes (cache_size, colors, input_sep,
42 # TODO: Move the various attributes (cache_size, colors, input_sep,
43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
44 # attributes of InteractiveShell. They should be on ONE object only and the
44 # attributes of InteractiveShell. They should be on ONE object only and the
45 # other objects should ask that one object for their values.
45 # other objects should ask that one object for their values.
46
46
47 class DisplayHook(Configurable):
47 class DisplayHook(Configurable):
48 """The custom IPython displayhook to replace sys.displayhook.
48 """The custom IPython displayhook to replace sys.displayhook.
49
49
50 This class does many things, but the basic idea is that it is a callable
50 This class does many things, but the basic idea is that it is a callable
51 that gets called anytime user code returns a value.
51 that gets called anytime user code returns a value.
52
52
53 Currently this class does more than just the displayhook logic and that
53 Currently this class does more than just the displayhook logic and that
54 extra logic should eventually be moved out of here.
54 extra logic should eventually be moved out of here.
55 """
55 """
56
56
57 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
57 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
58
58
59 def __init__(self, shell=None, cache_size=1000,
59 def __init__(self, shell=None, cache_size=1000,
60 colors='NoColor', input_sep='\n',
60 colors='NoColor', input_sep='\n',
61 output_sep='\n', output_sep2='',
61 output_sep='\n', output_sep2='',
62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
63 config=None):
63 config=None):
64 super(DisplayHook, self).__init__(shell=shell, config=config)
64 super(DisplayHook, self).__init__(shell=shell, config=config)
65
65
66 cache_size_min = 3
66 cache_size_min = 3
67 if cache_size <= 0:
67 if cache_size <= 0:
68 self.do_full_cache = 0
68 self.do_full_cache = 0
69 cache_size = 0
69 cache_size = 0
70 elif cache_size < cache_size_min:
70 elif cache_size < cache_size_min:
71 self.do_full_cache = 0
71 self.do_full_cache = 0
72 cache_size = 0
72 cache_size = 0
73 warn('caching was disabled (min value for cache size is %s).' %
73 warn('caching was disabled (min value for cache size is %s).' %
74 cache_size_min,level=3)
74 cache_size_min,level=3)
75 else:
75 else:
76 self.do_full_cache = 1
76 self.do_full_cache = 1
77
77
78 self.cache_size = cache_size
78 self.cache_size = cache_size
79 self.input_sep = input_sep
79 self.input_sep = input_sep
80
80
81 # we need a reference to the user-level namespace
81 # we need a reference to the user-level namespace
82 self.shell = shell
82 self.shell = shell
83
83
84 # Set input prompt strings and colors
84 # Set input prompt strings and colors
85 if cache_size == 0:
85 if cache_size == 0:
86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
87 or ps1.find(r'\N') > -1:
87 or ps1.find(r'\N') > -1:
88 ps1 = '>>> '
88 ps1 = '>>> '
89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
90 or ps2.find(r'\N') > -1:
90 or ps2.find(r'\N') > -1:
91 ps2 = '... '
91 ps2 = '... '
92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
95
95
96 self.color_table = prompts.PromptColors
96 self.color_table = prompts.PromptColors
97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
98 pad_left=pad_left)
98 pad_left=pad_left)
99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
101 pad_left=pad_left)
101 pad_left=pad_left)
102 self.set_colors(colors)
102 self.set_colors(colors)
103
103
104 # Store the last prompt string each time, we need it for aligning
104 # Store the last prompt string each time, we need it for aligning
105 # continuation and auto-rewrite prompts
105 # continuation and auto-rewrite prompts
106 self.last_prompt = ''
106 self.last_prompt = ''
107 self.output_sep = output_sep
107 self.output_sep = output_sep
108 self.output_sep2 = output_sep2
108 self.output_sep2 = output_sep2
109 self._,self.__,self.___ = '','',''
109 self._,self.__,self.___ = '','',''
110
110
111 # these are deliberately global:
111 # these are deliberately global:
112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
113 self.shell.user_ns.update(to_user_ns)
113 self.shell.user_ns.update(to_user_ns)
114
114
115 @property
115 @property
116 def prompt_count(self):
116 def prompt_count(self):
117 return self.shell.execution_count
117 return self.shell.execution_count
118
118
119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
120 if p_str is None:
120 if p_str is None:
121 if self.do_full_cache:
121 if self.do_full_cache:
122 return cache_def
122 return cache_def
123 else:
123 else:
124 return no_cache_def
124 return no_cache_def
125 else:
125 else:
126 return p_str
126 return p_str
127
127
128 def set_colors(self, colors):
128 def set_colors(self, colors):
129 """Set the active color scheme and configure colors for the three
129 """Set the active color scheme and configure colors for the three
130 prompt subsystems."""
130 prompt subsystems."""
131
131
132 # FIXME: This modifying of the global prompts.prompt_specials needs
132 # FIXME: This modifying of the global prompts.prompt_specials needs
133 # to be fixed. We need to refactor all of the prompts stuff to use
133 # to be fixed. We need to refactor all of the prompts stuff to use
134 # proper configuration and traits notifications.
134 # proper configuration and traits notifications.
135 if colors.lower()=='nocolor':
135 if colors.lower()=='nocolor':
136 prompts.prompt_specials = prompts.prompt_specials_nocolor
136 prompts.prompt_specials = prompts.prompt_specials_nocolor
137 else:
137 else:
138 prompts.prompt_specials = prompts.prompt_specials_color
138 prompts.prompt_specials = prompts.prompt_specials_color
139
139
140 self.color_table.set_active_scheme(colors)
140 self.color_table.set_active_scheme(colors)
141 self.prompt1.set_colors()
141 self.prompt1.set_colors()
142 self.prompt2.set_colors()
142 self.prompt2.set_colors()
143 self.prompt_out.set_colors()
143 self.prompt_out.set_colors()
144
144
145 #-------------------------------------------------------------------------
145 #-------------------------------------------------------------------------
146 # Methods used in __call__. Override these methods to modify the behavior
146 # Methods used in __call__. Override these methods to modify the behavior
147 # of the displayhook.
147 # of the displayhook.
148 #-------------------------------------------------------------------------
148 #-------------------------------------------------------------------------
149
149
150 def check_for_underscore(self):
150 def check_for_underscore(self):
151 """Check if the user has set the '_' variable by hand."""
151 """Check if the user has set the '_' variable by hand."""
152 # If something injected a '_' variable in __builtin__, delete
152 # If something injected a '_' variable in __builtin__, delete
153 # ipython's automatic one so we don't clobber that. gettext() in
153 # ipython's automatic one so we don't clobber that. gettext() in
154 # particular uses _, so we need to stay away from it.
154 # particular uses _, so we need to stay away from it.
155 if '_' in __builtin__.__dict__:
155 if '_' in __builtin__.__dict__:
156 try:
156 try:
157 del self.shell.user_ns['_']
157 del self.shell.user_ns['_']
158 except KeyError:
158 except KeyError:
159 pass
159 pass
160
160
161 def quiet(self):
161 def quiet(self):
162 """Should we silence the display hook because of ';'?"""
162 """Should we silence the display hook because of ';'?"""
163 # do not print output if input ends in ';'
163 # do not print output if input ends in ';'
164 try:
164 try:
165 if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'):
165 if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'):
166 return True
166 return True
167 except IndexError:
167 except IndexError:
168 # some uses of ipshellembed may fail here
168 # some uses of ipshellembed may fail here
169 pass
169 pass
170 return False
170 return False
171
171
172 def start_displayhook(self):
172 def start_displayhook(self):
173 """Start the displayhook, initializing resources."""
173 """Start the displayhook, initializing resources."""
174 pass
174 pass
175
175
176 def write_output_prompt(self):
176 def write_output_prompt(self):
177 """Write the output prompt.
177 """Write the output prompt.
178
178
179 The default implementation simply writes the prompt to
179 The default implementation simply writes the prompt to
180 ``io.Term.cout``.
180 ``io.Term.cout``.
181 """
181 """
182 # Use write, not print which adds an extra space.
182 # Use write, not print which adds an extra space.
183 IPython.utils.io.Term.cout.write(self.output_sep)
183 IPython.utils.io.Term.cout.write(self.output_sep)
184 outprompt = str(self.prompt_out)
184 outprompt = str(self.prompt_out)
185 if self.do_full_cache:
185 if self.do_full_cache:
186 IPython.utils.io.Term.cout.write(outprompt)
186 IPython.utils.io.Term.cout.write(outprompt)
187
187
188 def compute_format_data(self, result):
188 def compute_format_data(self, result):
189 """Compute format data of the object to be displayed.
189 """Compute format data of the object to be displayed.
190
190
191 The format data is a generalization of the :func:`repr` of an object.
191 The format data is a generalization of the :func:`repr` of an object.
192 In the default implementation the format data is a :class:`dict` of
192 In the default implementation the format data is a :class:`dict` of
193 key value pair where the keys are valid MIME types and the values
193 key value pair where the keys are valid MIME types and the values
194 are JSON'able data structure containing the raw data for that MIME
194 are JSON'able data structure containing the raw data for that MIME
195 type. It is up to frontends to determine pick a MIME to to use and
195 type. It is up to frontends to determine pick a MIME to to use and
196 display that data in an appropriate manner.
196 display that data in an appropriate manner.
197
197
198 This method only computes the format data for the object and should
198 This method only computes the format data for the object and should
199 NOT actually print or write that to a stream.
199 NOT actually print or write that to a stream.
200
200
201 Parameters
201 Parameters
202 ----------
202 ----------
203 result : object
203 result : object
204 The Python object passed to the display hook, whose format will be
204 The Python object passed to the display hook, whose format will be
205 computed.
205 computed.
206
206
207 Returns
207 Returns
208 -------
208 -------
209 format_data : dict
209 format_data : dict
210 A :class:`dict` whose keys are valid MIME types and values are
210 A :class:`dict` whose keys are valid MIME types and values are
211 JSON'able raw data for that MIME type. It is recommended that
211 JSON'able raw data for that MIME type. It is recommended that
212 all return values of this should always include the "text/plain"
212 all return values of this should always include the "text/plain"
213 MIME type representation of the object.
213 MIME type representation of the object.
214 """
214 """
215 return self.shell.display_formatter.format(result)
215 return self.shell.display_formatter.format(result)
216
216
217 def write_format_data(self, format_dict):
217 def write_format_data(self, format_dict):
218 """Write the format data dict to the frontend.
218 """Write the format data dict to the frontend.
219
219
220 This default version of this method simply writes the plain text
220 This default version of this method simply writes the plain text
221 representation of the object to ``io.Term.cout``. Subclasses should
221 representation of the object to ``io.Term.cout``. Subclasses should
222 override this method to send the entire `format_dict` to the
222 override this method to send the entire `format_dict` to the
223 frontends.
223 frontends.
224
224
225 Parameters
225 Parameters
226 ----------
226 ----------
227 format_dict : dict
227 format_dict : dict
228 The format dict for the object passed to `sys.displayhook`.
228 The format dict for the object passed to `sys.displayhook`.
229 """
229 """
230 # We want to print because we want to always make sure we have a
230 # We want to print because we want to always make sure we have a
231 # newline, even if all the prompt separators are ''. This is the
231 # newline, even if all the prompt separators are ''. This is the
232 # standard IPython behavior.
232 # standard IPython behavior.
233 result_repr = format_dict['text/plain']
233 result_repr = format_dict['text/plain']
234 if '\n' in result_repr:
234 if '\n' in result_repr:
235 # So that multi-line strings line up with the left column of
235 # So that multi-line strings line up with the left column of
236 # the screen, instead of having the output prompt mess up
236 # the screen, instead of having the output prompt mess up
237 # their first line.
237 # their first line.
238 # We use the ps_out_str template instead of the expanded prompt
238 # We use the ps_out_str template instead of the expanded prompt
239 # because the expansion may add ANSI escapes that will interfere
239 # because the expansion may add ANSI escapes that will interfere
240 # with our ability to determine whether or not we should add
240 # with our ability to determine whether or not we should add
241 # a newline.
241 # a newline.
242 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
242 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
243 # But avoid extraneous empty lines.
243 # But avoid extraneous empty lines.
244 result_repr = '\n' + result_repr
244 result_repr = '\n' + result_repr
245
245
246 print >>IPython.utils.io.Term.cout, result_repr
246 print >>IPython.utils.io.Term.cout, result_repr
247
247
248 def update_user_ns(self, result):
248 def update_user_ns(self, result):
249 """Update user_ns with various things like _, __, _1, etc."""
249 """Update user_ns with various things like _, __, _1, etc."""
250
250
251 # Avoid recursive reference when displaying _oh/Out
251 # Avoid recursive reference when displaying _oh/Out
252 if result is not self.shell.user_ns['_oh']:
252 if result is not self.shell.user_ns['_oh']:
253 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
253 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
254 warn('Output cache limit (currently '+
254 warn('Output cache limit (currently '+
255 `self.cache_size`+' entries) hit.\n'
255 `self.cache_size`+' entries) hit.\n'
256 'Flushing cache and resetting history counter...\n'
256 'Flushing cache and resetting history counter...\n'
257 'The only history variables available will be _,__,___ and _1\n'
257 'The only history variables available will be _,__,___ and _1\n'
258 'with the current result.')
258 'with the current result.')
259
259
260 self.flush()
260 self.flush()
261 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
261 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
262 # we cause buggy behavior for things like gettext).
262 # we cause buggy behavior for things like gettext).
263
263
264 if '_' not in __builtin__.__dict__:
264 if '_' not in __builtin__.__dict__:
265 self.___ = self.__
265 self.___ = self.__
266 self.__ = self._
266 self.__ = self._
267 self._ = result
267 self._ = result
268 self.shell.user_ns.update({'_':self._,
268 self.shell.user_ns.update({'_':self._,
269 '__':self.__,
269 '__':self.__,
270 '___':self.___})
270 '___':self.___})
271
271
272 # hackish access to top-level namespace to create _1,_2... dynamically
272 # hackish access to top-level namespace to create _1,_2... dynamically
273 to_main = {}
273 to_main = {}
274 if self.do_full_cache:
274 if self.do_full_cache:
275 new_result = '_'+`self.prompt_count`
275 new_result = '_'+`self.prompt_count`
276 to_main[new_result] = result
276 to_main[new_result] = result
277 self.shell.user_ns.update(to_main)
277 self.shell.user_ns.update(to_main)
278 self.shell.user_ns['_oh'][self.prompt_count] = result
278 self.shell.user_ns['_oh'][self.prompt_count] = result
279
279
280 def log_output(self, result):
280 def log_output(self, format_dict):
281 """Log the output."""
281 """Log the output."""
282 if self.shell.logger.log_output:
282 if self.shell.logger.log_output:
283 self.shell.logger.log_write(repr(result), 'output')
283 self.shell.logger.log_write(format_dict['text/plain'], 'output')
284 # This is a defaultdict of lists, so we can always append
285 self.shell.history_manager.output_hist_reprs[self.prompt_count]\
286 .append(format_dict['text/plain'])
284
287
285 def finish_displayhook(self):
288 def finish_displayhook(self):
286 """Finish up all displayhook activities."""
289 """Finish up all displayhook activities."""
287 IPython.utils.io.Term.cout.write(self.output_sep2)
290 IPython.utils.io.Term.cout.write(self.output_sep2)
288 IPython.utils.io.Term.cout.flush()
291 IPython.utils.io.Term.cout.flush()
289
292
290 def __call__(self, result=None):
293 def __call__(self, result=None):
291 """Printing with history cache management.
294 """Printing with history cache management.
292
295
293 This is invoked everytime the interpreter needs to print, and is
296 This is invoked everytime the interpreter needs to print, and is
294 activated by setting the variable sys.displayhook to it.
297 activated by setting the variable sys.displayhook to it.
295 """
298 """
296 self.check_for_underscore()
299 self.check_for_underscore()
297 if result is not None and not self.quiet():
300 if result is not None and not self.quiet():
298 self.start_displayhook()
301 self.start_displayhook()
299 self.write_output_prompt()
302 self.write_output_prompt()
300 format_dict = self.compute_format_data(result)
303 format_dict = self.compute_format_data(result)
301 self.write_format_data(format_dict)
304 self.write_format_data(format_dict)
302 self.update_user_ns(result)
305 self.update_user_ns(result)
303 self.log_output(result)
306 self.log_output(format_dict)
304 self.finish_displayhook()
307 self.finish_displayhook()
305
308
306 def flush(self):
309 def flush(self):
307 if not self.do_full_cache:
310 if not self.do_full_cache:
308 raise ValueError,"You shouldn't have reached the cache flush "\
311 raise ValueError,"You shouldn't have reached the cache flush "\
309 "if full caching is not enabled!"
312 "if full caching is not enabled!"
310 # delete auto-generated vars from global namespace
313 # delete auto-generated vars from global namespace
311
314
312 for n in range(1,self.prompt_count + 1):
315 for n in range(1,self.prompt_count + 1):
313 key = '_'+`n`
316 key = '_'+`n`
314 try:
317 try:
315 del self.shell.user_ns[key]
318 del self.shell.user_ns[key]
316 except: pass
319 except: pass
317 self.shell.user_ns['_oh'].clear()
320 self.shell.user_ns['_oh'].clear()
318
321
319 if '_' not in __builtin__.__dict__:
322 if '_' not in __builtin__.__dict__:
320 self.shell.user_ns.update({'_':None,'__':None, '___':None})
323 self.shell.user_ns.update({'_':None,'__':None, '___':None})
321 import gc
324 import gc
322 # TODO: Is this really needed?
325 # TODO: Is this really needed?
323 gc.collect()
326 gc.collect()
324
327
This diff has been collapsed as it changes many lines, (863 lines changed) Show them Hide them
@@ -1,589 +1,740 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010 The IPython Development Team.
3 # Copyright (C) 2010 The IPython Development Team.
4 #
4 #
5 # Distributed under the terms of the BSD License.
5 # Distributed under the terms of the BSD License.
6 #
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
13 from __future__ import print_function
14
14
15 # Stdlib imports
15 # Stdlib imports
16 import atexit
16 import datetime
17 import fnmatch
18 import json
17 import json
19 import os
18 import os
20 import sys
19 import re
21 import threading
20 import sqlite3
22 import time
21
22 from collections import defaultdict
23
23
24 # Our own packages
24 # Our own packages
25 from IPython.config.configurable import Configurable
25 import IPython.utils.io
26 import IPython.utils.io
26
27
27 from IPython.testing import decorators as testdec
28 from IPython.testing import decorators as testdec
28 from IPython.utils.pickleshare import PickleShareDB
29 from IPython.utils.io import ask_yes_no
29 from IPython.utils.io import ask_yes_no
30 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
30 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Classes and functions
34 # Classes and functions
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35
36
36 class HistoryManager(object):
37 class HistoryManager(Configurable):
37 """A class to organize all history-related functionality in one place.
38 """A class to organize all history-related functionality in one place.
38 """
39 """
39 # Public interface
40 # Public interface
40
41
41 # An instance of the IPython shell we are attached to
42 # An instance of the IPython shell we are attached to
42 shell = None
43 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
43 # A list to hold processed history
44 # Lists to hold processed and raw history. These start with a blank entry
44 input_hist_parsed = None
45 # so that we can index them starting from 1
45 # A list to hold raw history (as typed by user)
46 input_hist_parsed = List([""])
46 input_hist_raw = None
47 input_hist_raw = List([""])
47 # A list of directories visited during session
48 # A list of directories visited during session
48 dir_hist = None
49 dir_hist = List()
49 # A dict of output history, keyed with ints from the shell's execution count
50 # A dict of output history, keyed with ints from the shell's
50 output_hist = None
51 # execution count. If there are several outputs from one command,
51 # String with path to the history file
52 # only the last one is stored.
52 hist_file = None
53 output_hist = Dict()
53 # PickleShareDB instance holding the raw data for the shadow history
54 # Contains all outputs, in lists of reprs.
54 shadow_db = None
55 output_hist_reprs = Instance(defaultdict)
55 # ShadowHist instance with the actual shadow history
56
56 shadow_hist = None
57 # String holding the path to the history file
58 hist_file = Unicode()
59 # The SQLite database
60 db = Instance(sqlite3.Connection)
61 # The number of the current session in the history database
62 session_number = Int()
63 # Should we log output to the database? (default no)
64 db_log_output = Bool(False, config=True)
65 # Write to database every x commands (higher values save disk access & power)
66 # Values of 1 or less effectively disable caching.
67 db_cache_size = Int(0, config=True)
68 # The input and output caches
69 db_input_cache = List()
70 db_output_cache = List()
57
71
58 # Private interface
72 # Private interface
59 # Variables used to store the three last inputs from the user. On each new
73 # Variables used to store the three last inputs from the user. On each new
60 # history update, we populate the user's namespace with these, shifted as
74 # history update, we populate the user's namespace with these, shifted as
61 # necessary.
75 # necessary.
62 _i00, _i, _ii, _iii = '','','',''
76 _i00, _i, _ii, _iii = '','','',''
63
77
64 # A set with all forms of the exit command, so that we don't store them in
78 # A set with all forms of the exit command, so that we don't store them in
65 # the history (it's annoying to rewind the first entry and land on an exit
79 # the history (it's annoying to rewind the first entry and land on an exit
66 # call).
80 # call).
67 _exit_commands = None
81 _exit_commands = None
68
82
69 def __init__(self, shell):
83 def __init__(self, shell, config=None):
70 """Create a new history manager associated with a shell instance.
84 """Create a new history manager associated with a shell instance.
71 """
85 """
72 # We need a pointer back to the shell for various tasks.
86 # We need a pointer back to the shell for various tasks.
73 self.shell = shell
87 super(HistoryManager, self).__init__(shell=shell, config=config)
74
75 # List of input with multi-line handling.
76 self.input_hist_parsed = []
77 # This one will hold the 'raw' input history, without any
78 # pre-processing. This will allow users to retrieve the input just as
79 # it was exactly typed in by the user, with %hist -r.
80 self.input_hist_raw = []
81
88
82 # list of visited directories
89 # list of visited directories
83 try:
90 try:
84 self.dir_hist = [os.getcwd()]
91 self.dir_hist = [os.getcwd()]
85 except OSError:
92 except OSError:
86 self.dir_hist = []
93 self.dir_hist = []
87
94
88 # dict of output history
89 self.output_hist = {}
90
91 # Now the history file
95 # Now the history file
92 if shell.profile:
96 if shell.profile:
93 histfname = 'history-%s' % shell.profile
97 histfname = 'history-%s' % shell.profile
94 else:
98 else:
95 histfname = 'history'
99 histfname = 'history'
96 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json')
100 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
97
101 try:
98 # Objects related to shadow history management
102 self.init_db()
99 self._init_shadow_hist()
103 except sqlite3.DatabaseError:
104 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
105 os.rename(self.hist_file, newpath)
106 print("ERROR! History file wasn't a valid SQLite database.",
107 "It was moved to %s" % newpath, "and a new file created.")
108 self.init_db()
109
110 self.new_session()
100
111
101 self._i00, self._i, self._ii, self._iii = '','','',''
112 self._i00, self._i, self._ii, self._iii = '','','',''
113 self.output_hist_reprs = defaultdict(list)
102
114
103 self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit',
115 self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit',
104 '%quit', '%Exit', '%exit'])
116 '%quit', '%Exit', '%exit'])
105
106 # Object is fully initialized, we can now call methods on it.
107
117
108 # Fill the history zero entry, user counter starts at 1
118 def init_db(self):
109 self.store_inputs('\n', '\n')
119 """Connect to the database, and create tables if necessary."""
120 self.db = sqlite3.connect(self.hist_file)
121 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
122 primary key autoincrement, start timestamp,
123 end timestamp, num_cmds integer, remark text)""")
124 self.db.execute("""CREATE TABLE IF NOT EXISTS history
125 (session integer, line integer, source text, source_raw text,
126 PRIMARY KEY (session, line))""")
127 # Output history is optional, but ensure the table's there so it can be
128 # enabled later.
129 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
130 (session integer, line integer, output text,
131 PRIMARY KEY (session, line))""")
132 self.db.commit()
133
134 def new_session(self):
135 """Get a new session number."""
136 with self.db:
137 cur = self.db.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
138 NULL, "") """, (datetime.datetime.now(),))
139 self.session_number = cur.lastrowid
140
141 def end_session(self):
142 """Close the database session, filling in the end time and line count."""
143 self.writeout_cache()
144 with self.db:
145 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
146 session==?""", (datetime.datetime.now(),
147 len(self.input_hist_parsed)-1, self.session_number))
148 self.session_number = 0
149
150 def name_session(self, name):
151 """Give the current session a name in the history database."""
152 with self.db:
153 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
154 (name, self.session_number))
155
156 def reset(self, new_session=True):
157 """Clear the session history, releasing all object references, and
158 optionally open a new session."""
159 if self.session_number:
160 self.end_session()
161 self.input_hist_parsed[:] = [""]
162 self.input_hist_raw[:] = [""]
163 self.output_hist.clear()
164 # The directory history can't be completely empty
165 self.dir_hist[:] = [os.getcwd()]
110
166
111 # Create and start the autosaver.
167 if new_session:
112 self.autosave_flag = threading.Event()
168 self.new_session()
113 self.autosave_timer = HistorySaveThread(self.autosave_flag, 60)
169
114 self.autosave_timer.start()
170 ## -------------------------------
115 # Register the autosave handler to be triggered as a post execute
171 ## Methods for retrieving history:
116 # callback.
172 ## -------------------------------
117 self.shell.register_post_execute(self.autosave_if_due)
173 def _run_sql(self, sql, params, raw=True, output=False):
118
174 """Prepares and runs an SQL query for the history database.
119 def _init_shadow_hist(self):
120 try:
121 self.shadow_db = PickleShareDB(os.path.join(
122 self.shell.ipython_dir, 'db'))
123 except UnicodeDecodeError:
124 print("Your ipython_dir can't be decoded to unicode!")
125 print("Please set HOME environment variable to something that")
126 print(r"only has ASCII characters, e.g. c:\home")
127 print("Now it is", self.ipython_dir)
128 sys.exit()
129 self.shadow_hist = ShadowHist(self.shadow_db, self.shell)
130
175
131 def populate_readline_history(self):
176 Parameters
132 """Populate the readline history from the raw history.
177 ----------
133
178 sql : str
134 We only store one copy of the raw history, which is persisted to a json
179 Any filtering expressions to go after SELECT ... FROM ...
135 file on disk. The readline history is repopulated from the contents of
180 params : tuple
136 this file."""
181 Parameters passed to the SQL query (to replace "?")
137
182 raw, output : bool
138 try:
183 See :meth:`get_range`
139 self.shell.readline.clear_history()
140 except AttributeError:
141 pass
142 else:
143 for h in self.input_hist_raw:
144 if not h.isspace():
145 for line in h.splitlines():
146 self.shell.readline.add_history(line)
147
148 def save_history(self):
149 """Save input history to a file (via readline library)."""
150 hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:],
151 parsed=self.input_hist_parsed) #[-self.shell.history_length:])
152 with open(self.hist_file,'wt') as hfile:
153 json.dump(hist, hfile,
154 sort_keys=True, indent=4)
155
156 def autosave_if_due(self):
157 """Check if the autosave event is set; if so, save history. We do it
158 this way so that the save takes place in the main thread."""
159 if self.autosave_flag.is_set():
160 self.save_history()
161 self.autosave_flag.clear()
162
184
163 def reload_history(self):
185 Returns
164 """Reload the input history from disk file."""
186 -------
165
187 Tuples as :meth:`get_range`
166 with open(self.hist_file,'rt') as hfile:
188 """
167 try:
189 toget = 'source_raw' if raw else 'source'
168 hist = json.load(hfile)
190 sqlfrom = "history"
169 except ValueError: # Ignore it if JSON is corrupt.
191 if output:
170 return
192 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
171 self.input_hist_parsed = hist['parsed']
193 toget = "history.%s, output_history.output" % toget
172 self.input_hist_raw = hist['raw']
194 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
173 if self.shell.has_readline:
195 (toget, sqlfrom) + sql, params)
174 self.populate_readline_history()
196 if output: # Regroup into 3-tuples, and parse JSON
197 loads = lambda out: json.loads(out) if out else None
198 return ((ses, lin, (inp, loads(out))) \
199 for ses, lin, inp, out in cur)
200 return cur
201
202
203 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
204 """Get the last n lines from the history database.
175
205
176 def get_history(self, index=None, raw=False, output=True):
177 """Get the history list.
178
179 Get the input and output history.
180
181 Parameters
206 Parameters
182 ----------
207 ----------
183 index : n or (n1, n2) or None
208 n : int
184 If n, then the last entries. If a tuple, then all in
209 The number of lines to get
185 range(n1, n2). If None, then all entries. Raises IndexError if
210 raw, output : bool
186 the format of index is incorrect.
211 See :meth:`get_range`
187 raw : bool
212 include_latest : bool
188 If True, return the raw input.
213 If False (default), n+1 lines are fetched, and the latest one
189 output : bool
214 is discarded. This is intended to be used where the function
190 If True, then return the output as well.
215 is called by a user command, which it should not return.
191
216
192 Returns
217 Returns
193 -------
218 -------
194 If output is True, then return a dict of tuples, keyed by the prompt
219 Tuples as :meth:`get_range`
195 numbers and with values of (input, output). If output is False, then
196 a dict, keyed by the prompt number with the values of input. Raises
197 IndexError if no history is found.
198 """
220 """
199 if raw:
221 self.writeout_cache()
200 input_hist = self.input_hist_raw
222 if not include_latest:
201 else:
223 n += 1
202 input_hist = self.input_hist_parsed
224 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
225 (n,), raw=raw, output=output)
226 if not include_latest:
227 return reversed(list(cur)[1:])
228 return reversed(list(cur))
229
230 def search(self, pattern="*", raw=True, search_raw=True,
231 output=False):
232 """Search the database using unix glob-style matching (wildcards
233 * and ?).
234
235 Parameters
236 ----------
237 pattern : str
238 The wildcarded pattern to match when searching
239 search_raw : bool
240 If True, search the raw input, otherwise, the parsed input
241 raw, output : bool
242 See :meth:`get_range`
243
244 Returns
245 -------
246 Tuples as :meth:`get_range`
247 """
248 tosearch = "source_raw" if search_raw else "source"
203 if output:
249 if output:
204 output_hist = self.output_hist
250 tosearch = "history." + tosearch
251 self.writeout_cache()
252 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
253 raw=raw, output=output)
254
255 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
256 """Get input and output history from the current session. Called by
257 get_range, and takes similar parameters."""
258 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
259
205 n = len(input_hist)
260 n = len(input_hist)
206 if index is None:
261 if start < 0:
207 start=0; stop=n
262 start += n
208 elif isinstance(index, int):
263 if not stop:
209 start=n-index; stop=n
264 stop = n
210 elif isinstance(index, tuple) and len(index) == 2:
265 elif stop < 0:
211 start=index[0]; stop=index[1]
266 stop += n
212 else:
267
213 raise IndexError('Not a valid index for the input history: %r'
214 % index)
215 hist = {}
216 for i in range(start, stop):
268 for i in range(start, stop):
217 if output:
269 if output:
218 hist[i] = (input_hist[i], output_hist.get(i))
270 line = (input_hist[i], self.output_hist_reprs.get(i))
219 else:
271 else:
220 hist[i] = input_hist[i]
272 line = input_hist[i]
221 if not hist:
273 yield (0, i, line)
222 raise IndexError('No history for range of indices: %r' % index)
274
223 return hist
275 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
224
276 """Retrieve input by session.
225 def store_inputs(self, source, source_raw=None):
277
278 Parameters
279 ----------
280 session : int
281 Session number to retrieve. The current session is 0, and negative
282 numbers count back from current session, so -1 is previous session.
283 start : int
284 First line to retrieve.
285 stop : int
286 End of line range (excluded from output itself). If None, retrieve
287 to the end of the session.
288 raw : bool
289 If True, return untranslated input
290 output : bool
291 If True, attempt to include output. This will be 'real' Python
292 objects for the current session, or text reprs from previous
293 sessions if db_log_output was enabled at the time. Where no output
294 is found, None is used.
295
296 Returns
297 -------
298 An iterator over the desired lines. Each line is a 3-tuple, either
299 (session, line, input) if output is False, or
300 (session, line, (input, output)) if output is True.
301 """
302 if session == 0 or session==self.session_number: # Current session
303 return self._get_range_session(start, stop, raw, output)
304 if session < 0:
305 session += self.session_number
306
307 if stop:
308 lineclause = "line >= ? AND line < ?"
309 params = (session, start, stop)
310 else:
311 lineclause = "line>=?"
312 params = (session, start)
313
314 return self._run_sql("WHERE session==? AND %s""" % lineclause,
315 params, raw=raw, output=output)
316
317 def get_range_by_str(self, rangestr, raw=True, output=False):
318 """Get lines of history from a string of ranges, as used by magic
319 commands %hist, %save, %macro, etc.
320
321 Parameters
322 ----------
323 rangestr : str
324 A string specifying ranges, e.g. "5 ~2/1-4". See
325 :func:`magic_history` for full details.
326 raw, output : bool
327 As :meth:`get_range`
328
329 Returns
330 -------
331 Tuples as :meth:`get_range`
332 """
333 for sess, s, e in extract_hist_ranges(rangestr):
334 for line in self.get_range(sess, s, e, raw=raw, output=output):
335 yield line
336
337 ## ----------------------------
338 ## Methods for storing history:
339 ## ----------------------------
340 def store_inputs(self, line_num, source, source_raw=None):
226 """Store source and raw input in history and create input cache
341 """Store source and raw input in history and create input cache
227 variables _i*.
342 variables _i*.
228
343
229 Parameters
344 Parameters
230 ----------
345 ----------
346 line_num : int
347 The prompt number of this input.
348
231 source : str
349 source : str
232 Python input.
350 Python input.
233
351
234 source_raw : str, optional
352 source_raw : str, optional
235 If given, this is the raw input without any IPython transformations
353 If given, this is the raw input without any IPython transformations
236 applied to it. If not given, ``source`` is used.
354 applied to it. If not given, ``source`` is used.
237 """
355 """
238 if source_raw is None:
356 if source_raw is None:
239 source_raw = source
357 source_raw = source
358 source = source.rstrip('\n')
359 source_raw = source_raw.rstrip('\n')
240
360
241 # do not store exit/quit commands
361 # do not store exit/quit commands
242 if source_raw.strip() in self._exit_commands:
362 if source_raw.strip() in self._exit_commands:
243 return
363 return
244
364
245 self.input_hist_parsed.append(source.rstrip())
365 self.input_hist_parsed.append(source)
246 self.input_hist_raw.append(source_raw.rstrip())
366 self.input_hist_raw.append(source_raw)
247 self.shadow_hist.add(source)
367
368 self.db_input_cache.append((line_num, source, source_raw))
369 # Trigger to flush cache and write to DB.
370 if len(self.db_input_cache) >= self.db_cache_size:
371 self.writeout_cache()
248
372
249 # update the auto _i variables
373 # update the auto _i variables
250 self._iii = self._ii
374 self._iii = self._ii
251 self._ii = self._i
375 self._ii = self._i
252 self._i = self._i00
376 self._i = self._i00
253 self._i00 = source_raw
377 self._i00 = source_raw
254
378
255 # hackish access to user namespace to create _i1,_i2... dynamically
379 # hackish access to user namespace to create _i1,_i2... dynamically
256 new_i = '_i%s' % self.shell.execution_count
380 new_i = '_i%s' % line_num
257 to_main = {'_i': self._i,
381 to_main = {'_i': self._i,
258 '_ii': self._ii,
382 '_ii': self._ii,
259 '_iii': self._iii,
383 '_iii': self._iii,
260 new_i : self._i00 }
384 new_i : self._i00 }
261 self.shell.user_ns.update(to_main)
385 self.shell.user_ns.update(to_main)
262
386
263 def sync_inputs(self):
387 def store_output(self, line_num):
264 """Ensure raw and translated histories have same length."""
388 """If database output logging is enabled, this saves all the
265 if len(self.input_hist_parsed) != len (self.input_hist_raw):
389 outputs from the indicated prompt number to the database. It's
266 self.input_hist_raw[:] = self.input_hist_parsed
390 called by run_cell after code has been executed.
267
391
268 def reset(self):
392 Parameters
269 """Clear all histories managed by this object."""
393 ----------
270 self.input_hist_parsed[:] = []
394 line_num : int
271 self.input_hist_raw[:] = []
395 The line number from which to save outputs
272 self.output_hist.clear()
396 """
273 # The directory history can't be completely empty
397 if (not self.db_log_output) or not self.output_hist_reprs[line_num]:
274 self.dir_hist[:] = [os.getcwd()]
398 return
275
399 output = json.dumps(self.output_hist_reprs[line_num])
276 class HistorySaveThread(threading.Thread):
400
277 """This thread makes IPython save history periodically.
401 self.db_output_cache.append((line_num, output))
278
402 if self.db_cache_size <= 1:
279 Without this class, IPython would only save the history on a clean exit.
403 self.writeout_cache()
280 This saves the history periodically (the current default is once per
404
281 minute), so that it is not lost in the event of a crash.
405 def _writeout_input_cache(self):
406 for line in self.db_input_cache:
407 with self.db:
408 self.db.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
409 (self.session_number,)+line)
282
410
283 The implementation sets an event to indicate that history should be saved.
411 def _writeout_output_cache(self):
284 The actual save is carried out after executing a user command, to avoid
412 for line in self.db_output_cache:
285 thread issues.
413 with self.db:
286 """
414 self.db.execute("INSERT INTO output_history VALUES (?, ?, ?)",
287 daemon = True
415 (self.session_number,)+line)
288
416
289 def __init__(self, autosave_flag, time_interval=60):
417 def writeout_cache(self):
290 threading.Thread.__init__(self)
418 """Write any entries in the cache to the database."""
291 self.time_interval = time_interval
419 try:
292 self.autosave_flag = autosave_flag
420 self._writeout_input_cache()
293 self.exit_now = threading.Event()
421 except sqlite3.IntegrityError:
294 # Ensure the thread is stopped tidily when exiting normally
422 self.new_session()
295 atexit.register(self.stop)
423 print("ERROR! Session/line number was not unique in",
296
424 "database. History logging moved to new session",
297 def run(self):
425 self.session_number)
298 while True:
426 try: # Try writing to the new session. If this fails, don't recurse
299 self.exit_now.wait(self.time_interval)
427 self.writeout_cache()
300 if self.exit_now.is_set():
428 except sqlite3.IntegrityError:
301 break
429 pass
302 self.autosave_flag.set()
430 finally:
431 self.db_input_cache = []
303
432
304 def stop(self):
433 try:
305 """Safely and quickly stop the autosave timer thread."""
434 self._writeout_output_cache()
306 self.exit_now.set()
435 except sqlite3.IntegrityError:
307 self.join()
436 print("!! Session/line number for output was not unique",
437 "in database. Output will not be stored.")
438 finally:
439 self.db_output_cache = []
440
441
442 # To match, e.g. ~5/8-~2/3
443 range_re = re.compile(r"""
444 ((?P<startsess>~?\d+)/)?
445 (?P<start>\d+) # Only the start line num is compulsory
446 ((?P<sep>[\-:])
447 ((?P<endsess>~?\d+)/)?
448 (?P<end>\d+))?
449 """, re.VERBOSE)
450
451 def extract_hist_ranges(ranges_str):
452 """Turn a string of history ranges into 3-tuples of (session, start, stop).
453
454 Examples
455 --------
456 list(extract_input_ranges("~8/5-~7/4 2"))
457 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
458 """
459 for range_str in ranges_str.split():
460 rmatch = range_re.match(range_str)
461 if not rmatch:
462 continue
463 start = int(rmatch.group("start"))
464 end = rmatch.group("end")
465 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
466 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
467 end += 1
468 startsess = rmatch.group("startsess") or "0"
469 endsess = rmatch.group("endsess") or startsess
470 startsess = int(startsess.replace("~","-"))
471 endsess = int(endsess.replace("~","-"))
472 assert endsess >= startsess
473
474 if endsess == startsess:
475 yield (startsess, start, end)
476 continue
477 # Multiple sessions in one range:
478 yield (startsess, start, None)
479 for sess in range(startsess+1, endsess):
480 yield (sess, 1, None)
481 yield (endsess, 1, end)
482
483 def _format_lineno(session, line):
484 """Helper function to format line numbers properly."""
485 if session == 0:
486 return str(line)
487 return "%s#%s" % (session, line)
308
488
309 @testdec.skip_doctest
489 @testdec.skip_doctest
310 def magic_history(self, parameter_s = ''):
490 def magic_history(self, parameter_s = ''):
311 """Print input history (_i<n> variables), with most recent last.
491 """Print input history (_i<n> variables), with most recent last.
312
492
313 %history -> print at most 40 inputs (some may be multi-line)\\
493 %history -> print at most 40 inputs (some may be multi-line)\\
314 %history n -> print at most n inputs\\
494 %history n -> print at most n inputs\\
315 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
495 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
316
496
317 By default, input history is printed without line numbers so it can be
497 By default, input history is printed without line numbers so it can be
318 directly pasted into an editor.
498 directly pasted into an editor. Use -n to show them.
319
499
320 With -n, each input's number <n> is shown, and is accessible as the
500 Ranges of history can be indicated using the syntax:
321 automatically generated variable _i<n> as well as In[<n>]. Multi-line
501 4 : Line 4, current session
322 statements are printed starting at a new line for easy copy/paste.
502 4-6 : Lines 4-6, current session
503 243/1-5: Lines 1-5, session 243
504 ~2/7 : Line 7, session 2 before current
505 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
506 of 6 sessions ago.
507 Multiple ranges can be entered, separated by spaces
508
509 The same syntax is used by %macro, %save, %edit, %rerun
323
510
324 Options:
511 Options:
325
512
326 -n: print line numbers for each input.
513 -n: print line numbers for each input.
327 This feature is only available if numbered prompts are in use.
514 This feature is only available if numbered prompts are in use.
328
515
329 -o: also print outputs for each input.
516 -o: also print outputs for each input.
330
517
331 -p: print classic '>>>' python prompts before each input. This is useful
518 -p: print classic '>>>' python prompts before each input. This is useful
332 for making documentation, and in conjunction with -o, for producing
519 for making documentation, and in conjunction with -o, for producing
333 doctest-ready output.
520 doctest-ready output.
334
521
335 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
522 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
336
523
337 -t: print the 'translated' history, as IPython understands it. IPython
524 -t: print the 'translated' history, as IPython understands it. IPython
338 filters your input and converts it all into valid Python source before
525 filters your input and converts it all into valid Python source before
339 executing it (things like magics or aliases are turned into function
526 executing it (things like magics or aliases are turned into function
340 calls, for example). With this option, you'll see the native history
527 calls, for example). With this option, you'll see the native history
341 instead of the user-entered version: '%cd /' will be seen as
528 instead of the user-entered version: '%cd /' will be seen as
342 'get_ipython().magic("%cd /")' instead of '%cd /'.
529 'get_ipython().magic("%cd /")' instead of '%cd /'.
343
530
344 -g: treat the arg as a pattern to grep for in (full) history.
531 -g: treat the arg as a pattern to grep for in (full) history.
345 This includes the "shadow history" (almost all commands ever written).
532 This includes the saved history (almost all commands ever written).
346 Use '%hist -g' to show full shadow history (may be very long).
533 Use '%hist -g' to show full saved history (may be very long).
347 In shadow history, every index nuwber starts with 0.
534
535 -l: get the last n lines from all sessions. Specify n as a single arg, or
536 the default is the last 10 lines.
348
537
349 -f FILENAME: instead of printing the output to the screen, redirect it to
538 -f FILENAME: instead of printing the output to the screen, redirect it to
350 the given file. The file is always overwritten, though IPython asks for
539 the given file. The file is always overwritten, though IPython asks for
351 confirmation first if it already exists.
540 confirmation first if it already exists.
352
541
353 Examples
542 Examples
354 --------
543 --------
355 ::
544 ::
356
545
357 In [6]: %hist -n 4 6
546 In [6]: %hist -n 4 6
358 4:a = 12
547 4:a = 12
359 5:print a**2
548 5:print a**2
360
549
361 """
550 """
362
551
363 if not self.shell.displayhook.do_full_cache:
552 if not self.shell.displayhook.do_full_cache:
364 print('This feature is only available if numbered prompts are in use.')
553 print('This feature is only available if numbered prompts are in use.')
365 return
554 return
366 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
555 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
556
557 # For brevity
558 history_manager = self.shell.history_manager
559
560 def _format_lineno(session, line):
561 """Helper function to format line numbers properly."""
562 if session in (0, history_manager.session_number):
563 return str(line)
564 return "%s/%s" % (session, line)
367
565
368 # Check if output to specific file was requested.
566 # Check if output to specific file was requested.
369 try:
567 try:
370 outfname = opts['f']
568 outfname = opts['f']
371 except KeyError:
569 except KeyError:
372 outfile = IPython.utils.io.Term.cout # default
570 outfile = IPython.utils.io.Term.cout # default
373 # We don't want to close stdout at the end!
571 # We don't want to close stdout at the end!
374 close_at_end = False
572 close_at_end = False
375 else:
573 else:
376 if os.path.exists(outfname):
574 if os.path.exists(outfname):
377 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
575 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
378 print('Aborting.')
576 print('Aborting.')
379 return
577 return
380
578
381 outfile = open(outfname,'w')
579 outfile = open(outfname,'w')
382 close_at_end = True
580 close_at_end = True
383
384 if 't' in opts:
385 input_hist = self.shell.history_manager.input_hist_parsed
386 elif 'r' in opts:
387 input_hist = self.shell.history_manager.input_hist_raw
388 else:
389 # Raw history is the default
390 input_hist = self.shell.history_manager.input_hist_raw
391
392 default_length = 40
393 pattern = None
394 if 'g' in opts:
395 init = 1
396 final = len(input_hist)
397 parts = parameter_s.split(None, 1)
398 if len(parts) == 1:
399 parts += '*'
400 head, pattern = parts
401 pattern = "*" + pattern + "*"
402 elif len(args) == 0:
403 final = len(input_hist)-1
404 init = max(1,final-default_length)
405 elif len(args) == 1:
406 final = len(input_hist)
407 init = max(1, final-int(args[0]))
408 elif len(args) == 2:
409 init, final = map(int, args)
410 else:
411 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
412 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
413 return
414
581
415 width = len(str(final))
416 line_sep = ['','\n']
417 print_nums = 'n' in opts
582 print_nums = 'n' in opts
418 print_outputs = 'o' in opts
583 get_output = 'o' in opts
419 pyprompts = 'p' in opts
584 pyprompts = 'p' in opts
585 # Raw history is the default
586 raw = not('t' in opts)
587
588 default_length = 40
589 pattern = None
420
590
421 found = False
591 if 'g' in opts: # Glob search
422 if pattern is not None:
592 pattern = "*" + args + "*" if args else "*"
423 sh = self.shell.history_manager.shadowhist.all()
593 hist = history_manager.search(pattern, raw=raw, output=get_output)
424 for idx, s in sh:
594 elif 'l' in opts: # Get 'tail'
425 if fnmatch.fnmatch(s, pattern):
595 try:
426 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
596 n = int(args)
427 found = True
597 except ValueError, IndexError:
598 n = 10
599 hist = history_manager.get_tail(n, raw=raw, output=get_output)
600 else:
601 if args: # Get history by ranges
602 hist = history_manager.get_range_by_str(args, raw, get_output)
603 else: # Just get history for the current session
604 hist = history_manager.get_range(raw=raw, output=get_output)
428
605
429 if found:
606 # We could be displaying the entire history, so let's not try to pull it
430 print("===", file=outfile)
607 # into a list in memory. Anything that needs more space will just misalign.
431 print("shadow history ends, fetch by %rep <number> (must start with 0)",
608 width = 4
432 file=outfile)
433 print("=== start of normal history ===", file=outfile)
434
609
435 for in_num in range(init, final):
610 for session, lineno, inline in hist:
436 # Print user history with tabs expanded to 4 spaces. The GUI clients
611 # Print user history with tabs expanded to 4 spaces. The GUI clients
437 # use hard tabs for easier usability in auto-indented code, but we want
612 # use hard tabs for easier usability in auto-indented code, but we want
438 # to produce PEP-8 compliant history for safe pasting into an editor.
613 # to produce PEP-8 compliant history for safe pasting into an editor.
439 inline = input_hist[in_num].expandtabs(4).rstrip()+'\n'
614 if get_output:
440
615 inline, output = inline
441 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
616 inline = inline.expandtabs(4).rstrip()
442 continue
443
617
444 multiline = int(inline.count('\n') > 1)
618 multiline = "\n" in inline
619 line_sep = '\n' if multiline else ' '
445 if print_nums:
620 if print_nums:
446 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
621 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
447 file=outfile)
622 line_sep), file=outfile, end='')
448 if pyprompts:
623 if pyprompts:
449 print('>>>', file=outfile)
624 print(">>> ", end="", file=outfile)
450 if multiline:
625 if multiline:
451 lines = inline.splitlines()
626 inline = "\n... ".join(inline.splitlines()) + "\n..."
452 print('\n... '.join(lines), file=outfile)
627 print(inline, file=outfile)
453 print('... ', file=outfile)
628 if get_output and output:
454 else:
629 print("\n".join(output), file=outfile)
455 print(inline, end='', file=outfile)
456 else:
457 print(inline, end='', file=outfile)
458 if print_outputs:
459 output = self.shell.history_manager.output_hist.get(in_num)
460 if output is not None:
461 print(repr(output), file=outfile)
462
630
463 if close_at_end:
631 if close_at_end:
464 outfile.close()
632 outfile.close()
465
633
466
634
467 def magic_hist(self, parameter_s=''):
635 def magic_rep(self, arg):
468 """Alternate name for %history."""
469 return self.magic_history(parameter_s)
470
471
472 def rep_f(self, arg):
473 r""" Repeat a command, or get command to input line for editing
636 r""" Repeat a command, or get command to input line for editing
474
637
475 - %rep (no arguments):
638 - %rep (no arguments):
476
639
477 Place a string version of last computation result (stored in the special '_'
640 Place a string version of last computation result (stored in the special '_'
478 variable) to the next input prompt. Allows you to create elaborate command
641 variable) to the next input prompt. Allows you to create elaborate command
479 lines without using copy-paste::
642 lines without using copy-paste::
480
643
481 $ l = ["hei", "vaan"]
644 In[1]: l = ["hei", "vaan"]
482 $ "".join(l)
645 In[2]: "".join(l)
483 ==> heivaan
646 Out[2]: heivaan
484 $ %rep
647 In[3]: %rep
485 $ heivaan_ <== cursor blinking
648 In[4]: heivaan_ <== cursor blinking
486
649
487 %rep 45
650 %rep 45
488
651
489 Place history line 45 to next input prompt. Use %hist to find out the
652 Place history line 45 on the next input prompt. Use %hist to find
490 number.
653 out the number.
491
654
492 %rep 1-4 6-7 3
655 %rep 1-4
493
656
494 Repeat the specified lines immediately. Input slice syntax is the same as
657 Combine the specified lines into one cell, and place it on the next
495 in %macro and %save.
658 input prompt. See %history for the slice syntax.
496
659
497 %rep foo
660 %rep foo+bar
498
661
499 Place the most recent line that has the substring "foo" to next input.
662 If foo+bar can be evaluated in the user namespace, the result is
500 (e.g. 'svn ci -m foobar').
663 placed at the next input prompt. Otherwise, the history is searched
664 for lines which contain that substring, and the most recent one is
665 placed at the next input prompt.
501 """
666 """
502
667 if not arg: # Last output
503 opts,args = self.parse_options(arg,'',mode='list')
504 if not args:
505 self.set_next_input(str(self.shell.user_ns["_"]))
668 self.set_next_input(str(self.shell.user_ns["_"]))
506 return
669 return
670 # Get history range
671 histlines = self.history_manager.get_range_by_str(arg)
672 cmd = "\n".join(x[2] for x in histlines)
673 if cmd:
674 self.set_next_input(cmd.rstrip())
675 return
507
676
508 if len(args) == 1 and not '-' in args[0]:
677 try: # Variable in user namespace
509 arg = args[0]
678 cmd = str(eval(arg, self.shell.user_ns))
510 if len(arg) > 1 and arg.startswith('0'):
679 except Exception: # Search for term in history
511 # get from shadow hist
680 histlines = self.history_manager.search("*"+arg+"*")
512 num = int(arg[1:])
681 for h in reversed([x[2] for x in histlines]):
513 line = self.shell.shadowhist.get(num)
514 self.set_next_input(str(line))
515 return
516 try:
517 num = int(args[0])
518 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
519 return
520 except ValueError:
521 pass
522
523 for h in reversed(self.shell.input_hist_raw):
524 if 'rep' in h:
682 if 'rep' in h:
525 continue
683 continue
526 if fnmatch.fnmatch(h,'*' + arg + '*'):
684 self.set_next_input(h.rstrip())
527 self.set_next_input(str(h).rstrip())
685 return
528 return
686 else:
529
687 self.set_next_input(cmd.rstrip())
530 try:
688 print("Couldn't evaluate or find in history:", arg)
531 lines = self.extract_input_slices(args, True)
532 print("lines", lines)
533 self.run_cell(lines)
534 except ValueError:
535 print("Not found in recent history:", args)
536
689
537
690 def magic_rerun(self, parameter_s=''):
538 _sentinel = object()
691 """Re-run previous input
539
540 class ShadowHist(object):
541 def __init__(self, db, shell):
542 # cmd => idx mapping
543 self.curidx = 0
544 self.db = db
545 self.disabled = False
546 self.shell = shell
547
692
548 def inc_idx(self):
693 By default, you can specify ranges of input history to be repeated
549 idx = self.db.get('shadowhist_idx', 1)
694 (as with %history). With no arguments, it will repeat the last line.
550 self.db['shadowhist_idx'] = idx + 1
551 return idx
552
553 def add(self, ent):
554 if self.disabled:
555 return
556 try:
557 old = self.db.hget('shadowhist', ent, _sentinel)
558 if old is not _sentinel:
559 return
560 newidx = self.inc_idx()
561 #print("new", newidx) # dbg
562 self.db.hset('shadowhist',ent, newidx)
563 except:
564 self.shell.showtraceback()
565 print("WARNING: disabling shadow history")
566 self.disabled = True
567
695
568 def all(self):
696 Options:
569 d = self.db.hdict('shadowhist')
697
570 items = [(i,s) for (s,i) in d.iteritems()]
698 -l <n> : Repeat the last n lines of input, not including the
571 items.sort()
699 current command.
572 return items
700
573
701 -g foo : Repeat the most recent line which contains foo
574 def get(self, idx):
702 """
575 all = self.all()
703 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
576
704 if "l" in opts: # Last n lines
577 for k, v in all:
705 n = int(opts['l'])
578 if k == idx:
706 hist = self.history_manager.get_tail(n)
579 return v
707 elif "g" in opts: # Search
708 p = "*"+opts['g']+"*"
709 hist = list(self.history_manager.search(p))
710 for l in reversed(hist):
711 if "rerun" not in l[2]:
712 hist = [l] # The last match which isn't a %rerun
713 break
714 else:
715 hist = [] # No matches except %rerun
716 elif args: # Specify history ranges
717 hist = self.history_manager.get_range_by_str(args)
718 else: # Last line
719 hist = self.history_manager.get_tail(1)
720 hist = [x[2] for x in hist]
721 if not hist:
722 print("No lines in history match specification")
723 return
724 histlines = "\n".join(hist)
725 print("=== Executing: ===")
726 print(histlines)
727 print("=== Output: ===")
728 self.run_cell("\n".join(hist), store_history=False)
580
729
581
730
582 def init_ipython(ip):
731 def init_ipython(ip):
583 ip.define_magic("rep",rep_f)
732 ip.define_magic("rep", magic_rep)
584 ip.define_magic("hist",magic_hist)
733 ip.define_magic("recall", magic_rep)
734 ip.define_magic("rerun", magic_rerun)
735 ip.define_magic("hist",magic_history) # Alternative name
585 ip.define_magic("history",magic_history)
736 ip.define_magic("history",magic_history)
586
737
587 # XXX - ipy_completers are in quarantine, need to be updated to new apis
738 # XXX - ipy_completers are in quarantine, need to be updated to new apis
588 #import ipy_completers
739 #import ipy_completers
589 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
740 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,2559 +1,2528 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-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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
60 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.doctestreload import doctest_reload
61 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.io import ask_yes_no, rprint
62 from IPython.utils.ipstruct import Struct
61 from IPython.utils.ipstruct import Struct
63 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 from IPython.utils.pickleshare import PickleShareDB
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 profile = Str('', config=True)
175 profile = Str('', config=True)
176 prompt_in1 = Str('In [\\#]: ', config=True)
176 prompt_in1 = Str('In [\\#]: ', config=True)
177 prompt_in2 = Str(' .\\D.: ', config=True)
177 prompt_in2 = Str(' .\\D.: ', config=True)
178 prompt_out = Str('Out[\\#]: ', config=True)
178 prompt_out = Str('Out[\\#]: ', config=True)
179 prompts_pad_left = CBool(True, config=True)
179 prompts_pad_left = CBool(True, config=True)
180 quiet = CBool(False, config=True)
180 quiet = CBool(False, config=True)
181
181
182 history_length = Int(10000, config=True)
182 history_length = Int(10000, config=True)
183
183
184 # The readline stuff will eventually be moved to the terminal subclass
184 # The readline stuff will eventually be moved to the terminal subclass
185 # 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.
186 readline_use = CBool(True, config=True)
186 readline_use = CBool(True, config=True)
187 readline_merge_completions = CBool(True, config=True)
187 readline_merge_completions = CBool(True, config=True)
188 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)
189 readline_remove_delims = Str('-/~', config=True)
189 readline_remove_delims = Str('-/~', config=True)
190 readline_parse_and_bind = List([
190 readline_parse_and_bind = List([
191 'tab: complete',
191 'tab: complete',
192 '"\C-l": clear-screen',
192 '"\C-l": clear-screen',
193 'set show-all-if-ambiguous on',
193 'set show-all-if-ambiguous on',
194 '"\C-o": tab-insert',
194 '"\C-o": tab-insert',
195 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
195 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
196 # crash IPython.
196 # crash IPython.
197 '"\M-o": "\d\d\d\d"',
197 '"\M-o": "\d\d\d\d"',
198 '"\M-I": "\d\d\d\d"',
198 '"\M-I": "\d\d\d\d"',
199 '"\C-r": reverse-search-history',
199 '"\C-r": reverse-search-history',
200 '"\C-s": forward-search-history',
200 '"\C-s": forward-search-history',
201 '"\C-p": history-search-backward',
201 '"\C-p": history-search-backward',
202 '"\C-n": history-search-forward',
202 '"\C-n": history-search-forward',
203 '"\e[A": history-search-backward',
203 '"\e[A": history-search-backward',
204 '"\e[B": history-search-forward',
204 '"\e[B": history-search-forward',
205 '"\C-k": kill-line',
205 '"\C-k": kill-line',
206 '"\C-u": unix-line-discard',
206 '"\C-u": unix-line-discard',
207 ], allow_none=False, config=True)
207 ], allow_none=False, config=True)
208
208
209 # TODO: this part of prompt management should be moved to the frontends.
209 # TODO: this part of prompt management should be moved to the frontends.
210 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
210 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
211 separate_in = SeparateStr('\n', config=True)
211 separate_in = SeparateStr('\n', config=True)
212 separate_out = SeparateStr('', config=True)
212 separate_out = SeparateStr('', config=True)
213 separate_out2 = SeparateStr('', config=True)
213 separate_out2 = SeparateStr('', config=True)
214 wildcards_case_sensitive = CBool(True, config=True)
214 wildcards_case_sensitive = CBool(True, config=True)
215 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
215 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
216 default_value='Context', config=True)
216 default_value='Context', config=True)
217
217
218 # Subcomponents of InteractiveShell
218 # Subcomponents of InteractiveShell
219 alias_manager = Instance('IPython.core.alias.AliasManager')
219 alias_manager = Instance('IPython.core.alias.AliasManager')
220 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
220 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
221 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
221 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
222 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
222 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
223 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
223 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
224 plugin_manager = Instance('IPython.core.plugin.PluginManager')
224 plugin_manager = Instance('IPython.core.plugin.PluginManager')
225 payload_manager = Instance('IPython.core.payload.PayloadManager')
225 payload_manager = Instance('IPython.core.payload.PayloadManager')
226 history_manager = Instance('IPython.core.history.HistoryManager')
226 history_manager = Instance('IPython.core.history.HistoryManager')
227
227
228 # Private interface
228 # Private interface
229 _post_execute = set()
229 _post_execute = set()
230
230
231 def __init__(self, config=None, ipython_dir=None,
231 def __init__(self, config=None, ipython_dir=None,
232 user_ns=None, user_global_ns=None,
232 user_ns=None, user_global_ns=None,
233 custom_exceptions=((), None)):
233 custom_exceptions=((), None)):
234
234
235 # This is where traits with a config_key argument are updated
235 # This is where traits with a config_key argument are updated
236 # from the values on config.
236 # from the values on config.
237 super(InteractiveShell, self).__init__(config=config)
237 super(InteractiveShell, self).__init__(config=config)
238
238
239 # These are relatively independent and stateless
239 # These are relatively independent and stateless
240 self.init_ipython_dir(ipython_dir)
240 self.init_ipython_dir(ipython_dir)
241 self.init_instance_attrs()
241 self.init_instance_attrs()
242 self.init_environment()
242 self.init_environment()
243
243
244 # Create namespaces (user_ns, user_global_ns, etc.)
244 # Create namespaces (user_ns, user_global_ns, etc.)
245 self.init_create_namespaces(user_ns, user_global_ns)
245 self.init_create_namespaces(user_ns, user_global_ns)
246 # This has to be done after init_create_namespaces because it uses
246 # This has to be done after init_create_namespaces because it uses
247 # something in self.user_ns, but before init_sys_modules, which
247 # something in self.user_ns, but before init_sys_modules, which
248 # is the first thing to modify sys.
248 # is the first thing to modify sys.
249 # TODO: When we override sys.stdout and sys.stderr before this class
249 # 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
250 # is created, we are saving the overridden ones here. Not sure if this
251 # is what we want to do.
251 # is what we want to do.
252 self.save_sys_module_state()
252 self.save_sys_module_state()
253 self.init_sys_modules()
253 self.init_sys_modules()
254
255 # While we're trying to have each part of the code directly access what
256 # it needs without keeping redundant references to objects, we have too
257 # much legacy code that expects ip.db to exist.
258 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
254
259
255 self.init_history()
260 self.init_history()
256 self.init_encoding()
261 self.init_encoding()
257 self.init_prefilter()
262 self.init_prefilter()
258
263
259 Magic.__init__(self, self)
264 Magic.__init__(self, self)
260
265
261 self.init_syntax_highlighting()
266 self.init_syntax_highlighting()
262 self.init_hooks()
267 self.init_hooks()
263 self.init_pushd_popd_magic()
268 self.init_pushd_popd_magic()
264 # self.init_traceback_handlers use to be here, but we moved it below
269 # 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.
270 # because it and init_io have to come after init_readline.
266 self.init_user_ns()
271 self.init_user_ns()
267 self.init_logger()
272 self.init_logger()
268 self.init_alias()
273 self.init_alias()
269 self.init_builtins()
274 self.init_builtins()
270
275
271 # pre_config_initialization
276 # pre_config_initialization
272
277
273 # The next section should contain everything that was in ipmaker.
278 # The next section should contain everything that was in ipmaker.
274 self.init_logstart()
279 self.init_logstart()
275
280
276 # The following was in post_config_initialization
281 # The following was in post_config_initialization
277 self.init_inspector()
282 self.init_inspector()
278 # init_readline() must come before init_io(), because init_io uses
283 # init_readline() must come before init_io(), because init_io uses
279 # readline related things.
284 # readline related things.
280 self.init_readline()
285 self.init_readline()
281 # init_completer must come after init_readline, because it needs to
286 # init_completer must come after init_readline, because it needs to
282 # know whether readline is present or not system-wide to configure the
287 # know whether readline is present or not system-wide to configure the
283 # completers, since the completion machinery can now operate
288 # completers, since the completion machinery can now operate
284 # independently of readline (e.g. over the network)
289 # independently of readline (e.g. over the network)
285 self.init_completer()
290 self.init_completer()
286 # TODO: init_io() needs to happen before init_traceback handlers
291 # TODO: init_io() needs to happen before init_traceback handlers
287 # because the traceback handlers hardcode the stdout/stderr streams.
292 # because the traceback handlers hardcode the stdout/stderr streams.
288 # This logic in in debugger.Pdb and should eventually be changed.
293 # This logic in in debugger.Pdb and should eventually be changed.
289 self.init_io()
294 self.init_io()
290 self.init_traceback_handlers(custom_exceptions)
295 self.init_traceback_handlers(custom_exceptions)
291 self.init_prompts()
296 self.init_prompts()
292 self.init_display_formatter()
297 self.init_display_formatter()
293 self.init_display_pub()
298 self.init_display_pub()
294 self.init_displayhook()
299 self.init_displayhook()
295 self.init_reload_doctest()
300 self.init_reload_doctest()
296 self.init_magics()
301 self.init_magics()
297 self.init_pdb()
302 self.init_pdb()
298 self.init_extension_manager()
303 self.init_extension_manager()
299 self.init_plugin_manager()
304 self.init_plugin_manager()
300 self.init_payload()
305 self.init_payload()
301 self.hooks.late_startup_hook()
306 self.hooks.late_startup_hook()
302 atexit.register(self.atexit_operations)
307 atexit.register(self.atexit_operations)
303
308
304 # 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
306 # 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.
308 @property
309 def db(self):
310 return self.history_manager.shadow_db
311
312 @classmethod
309 @classmethod
313 def instance(cls, *args, **kwargs):
310 def instance(cls, *args, **kwargs):
314 """Returns a global InteractiveShell instance."""
311 """Returns a global InteractiveShell instance."""
315 if cls._instance is None:
312 if cls._instance is None:
316 inst = cls(*args, **kwargs)
313 inst = cls(*args, **kwargs)
317 # Now make sure that the instance will also be returned by
314 # Now make sure that the instance will also be returned by
318 # the subclasses instance attribute.
315 # the subclasses instance attribute.
319 for subclass in cls.mro():
316 for subclass in cls.mro():
320 if issubclass(cls, subclass) and \
317 if issubclass(cls, subclass) and \
321 issubclass(subclass, InteractiveShell):
318 issubclass(subclass, InteractiveShell):
322 subclass._instance = inst
319 subclass._instance = inst
323 else:
320 else:
324 break
321 break
325 if isinstance(cls._instance, cls):
322 if isinstance(cls._instance, cls):
326 return cls._instance
323 return cls._instance
327 else:
324 else:
328 raise MultipleInstanceError(
325 raise MultipleInstanceError(
329 'Multiple incompatible subclass instances of '
326 'Multiple incompatible subclass instances of '
330 'InteractiveShell are being created.'
327 'InteractiveShell are being created.'
331 )
328 )
332
329
333 @classmethod
330 @classmethod
334 def initialized(cls):
331 def initialized(cls):
335 return hasattr(cls, "_instance")
332 return hasattr(cls, "_instance")
336
333
337 def get_ipython(self):
334 def get_ipython(self):
338 """Return the currently running IPython instance."""
335 """Return the currently running IPython instance."""
339 return self
336 return self
340
337
341 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
342 # Trait changed handlers
339 # Trait changed handlers
343 #-------------------------------------------------------------------------
340 #-------------------------------------------------------------------------
344
341
345 def _ipython_dir_changed(self, name, new):
342 def _ipython_dir_changed(self, name, new):
346 if not os.path.isdir(new):
343 if not os.path.isdir(new):
347 os.makedirs(new, mode = 0777)
344 os.makedirs(new, mode = 0777)
348
345
349 def set_autoindent(self,value=None):
346 def set_autoindent(self,value=None):
350 """Set the autoindent flag, checking for readline support.
347 """Set the autoindent flag, checking for readline support.
351
348
352 If called with no arguments, it acts as a toggle."""
349 If called with no arguments, it acts as a toggle."""
353
350
354 if not self.has_readline:
351 if not self.has_readline:
355 if os.name == 'posix':
352 if os.name == 'posix':
356 warn("The auto-indent feature requires the readline library")
353 warn("The auto-indent feature requires the readline library")
357 self.autoindent = 0
354 self.autoindent = 0
358 return
355 return
359 if value is None:
356 if value is None:
360 self.autoindent = not self.autoindent
357 self.autoindent = not self.autoindent
361 else:
358 else:
362 self.autoindent = value
359 self.autoindent = value
363
360
364 #-------------------------------------------------------------------------
361 #-------------------------------------------------------------------------
365 # init_* methods called by __init__
362 # init_* methods called by __init__
366 #-------------------------------------------------------------------------
363 #-------------------------------------------------------------------------
367
364
368 def init_ipython_dir(self, ipython_dir):
365 def init_ipython_dir(self, ipython_dir):
369 if ipython_dir is not None:
366 if ipython_dir is not None:
370 self.ipython_dir = ipython_dir
367 self.ipython_dir = ipython_dir
371 self.config.Global.ipython_dir = self.ipython_dir
368 self.config.Global.ipython_dir = self.ipython_dir
372 return
369 return
373
370
374 if hasattr(self.config.Global, 'ipython_dir'):
371 if hasattr(self.config.Global, 'ipython_dir'):
375 self.ipython_dir = self.config.Global.ipython_dir
372 self.ipython_dir = self.config.Global.ipython_dir
376 else:
373 else:
377 self.ipython_dir = get_ipython_dir()
374 self.ipython_dir = get_ipython_dir()
378
375
379 # All children can just read this
376 # All children can just read this
380 self.config.Global.ipython_dir = self.ipython_dir
377 self.config.Global.ipython_dir = self.ipython_dir
381
378
382 def init_instance_attrs(self):
379 def init_instance_attrs(self):
383 self.more = False
380 self.more = False
384
381
385 # command compiler
382 # command compiler
386 self.compile = CachingCompiler()
383 self.compile = CachingCompiler()
387
384
388 # User input buffers
385 # User input buffers
389 # NOTE: these variables are slated for full removal, once we are 100%
386 # 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,
387 # 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
388 # push_line and these buffers, as all input will be managed by the
392 # frontends via an inputsplitter instance.
389 # frontends via an inputsplitter instance.
393 self.buffer = []
390 self.buffer = []
394 self.buffer_raw = []
391 self.buffer_raw = []
395
392
396 # Make an empty namespace, which extension writers can rely on both
393 # Make an empty namespace, which extension writers can rely on both
397 # existing and NEVER being used by ipython itself. This gives them a
394 # existing and NEVER being used by ipython itself. This gives them a
398 # convenient location for storing additional information and state
395 # convenient location for storing additional information and state
399 # their extensions may require, without fear of collisions with other
396 # their extensions may require, without fear of collisions with other
400 # ipython names that may develop later.
397 # ipython names that may develop later.
401 self.meta = Struct()
398 self.meta = Struct()
402
399
403 # Object variable to store code object waiting execution. This is
400 # Object variable to store code object waiting execution. This is
404 # used mainly by the multithreaded shells, but it can come in handy in
401 # 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
402 # other situations. No need to use a Queue here, since it's a single
406 # item which gets cleared once run.
403 # item which gets cleared once run.
407 self.code_to_run = None
404 self.code_to_run = None
408
405
409 # Temporary files used for various purposes. Deleted at exit.
406 # Temporary files used for various purposes. Deleted at exit.
410 self.tempfiles = []
407 self.tempfiles = []
411
408
412 # Keep track of readline usage (later set by init_readline)
409 # Keep track of readline usage (later set by init_readline)
413 self.has_readline = False
410 self.has_readline = False
414
411
415 # keep track of where we started running (mainly for crash post-mortem)
412 # keep track of where we started running (mainly for crash post-mortem)
416 # This is not being used anywhere currently.
413 # This is not being used anywhere currently.
417 self.starting_dir = os.getcwd()
414 self.starting_dir = os.getcwd()
418
415
419 # Indentation management
416 # Indentation management
420 self.indent_current_nsp = 0
417 self.indent_current_nsp = 0
421
418
422 def init_environment(self):
419 def init_environment(self):
423 """Any changes we need to make to the user's environment."""
420 """Any changes we need to make to the user's environment."""
424 pass
421 pass
425
422
426 def init_encoding(self):
423 def init_encoding(self):
427 # Get system encoding at startup time. Certain terminals (like Emacs
424 # 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
425 # under Win32 have it set to None, and we need to have a known valid
429 # encoding to use in the raw_input() method
426 # encoding to use in the raw_input() method
430 try:
427 try:
431 self.stdin_encoding = sys.stdin.encoding or 'ascii'
428 self.stdin_encoding = sys.stdin.encoding or 'ascii'
432 except AttributeError:
429 except AttributeError:
433 self.stdin_encoding = 'ascii'
430 self.stdin_encoding = 'ascii'
434
431
435 def init_syntax_highlighting(self):
432 def init_syntax_highlighting(self):
436 # Python source parser/formatter for syntax highlighting
433 # Python source parser/formatter for syntax highlighting
437 pyformat = PyColorize.Parser().format
434 pyformat = PyColorize.Parser().format
438 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
435 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
439
436
440 def init_pushd_popd_magic(self):
437 def init_pushd_popd_magic(self):
441 # for pushd/popd management
438 # for pushd/popd management
442 try:
439 try:
443 self.home_dir = get_home_dir()
440 self.home_dir = get_home_dir()
444 except HomeDirError, msg:
441 except HomeDirError, msg:
445 fatal(msg)
442 fatal(msg)
446
443
447 self.dir_stack = []
444 self.dir_stack = []
448
445
449 def init_logger(self):
446 def init_logger(self):
450 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
447 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
451 logmode='rotate')
448 logmode='rotate')
452
449
453 def init_logstart(self):
450 def init_logstart(self):
454 """Initialize logging in case it was requested at the command line.
451 """Initialize logging in case it was requested at the command line.
455 """
452 """
456 if self.logappend:
453 if self.logappend:
457 self.magic_logstart(self.logappend + ' append')
454 self.magic_logstart(self.logappend + ' append')
458 elif self.logfile:
455 elif self.logfile:
459 self.magic_logstart(self.logfile)
456 self.magic_logstart(self.logfile)
460 elif self.logstart:
457 elif self.logstart:
461 self.magic_logstart()
458 self.magic_logstart()
462
459
463 def init_builtins(self):
460 def init_builtins(self):
464 self.builtin_trap = BuiltinTrap(shell=self)
461 self.builtin_trap = BuiltinTrap(shell=self)
465
462
466 def init_inspector(self):
463 def init_inspector(self):
467 # Object inspector
464 # Object inspector
468 self.inspector = oinspect.Inspector(oinspect.InspectColors,
465 self.inspector = oinspect.Inspector(oinspect.InspectColors,
469 PyColorize.ANSICodeColors,
466 PyColorize.ANSICodeColors,
470 'NoColor',
467 'NoColor',
471 self.object_info_string_level)
468 self.object_info_string_level)
472
469
473 def init_io(self):
470 def init_io(self):
474 # This will just use sys.stdout and sys.stderr. If you want to
471 # 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
472 # override sys.stdout and sys.stderr themselves, you need to do that
476 # *before* instantiating this class, because Term holds onto
473 # *before* instantiating this class, because Term holds onto
477 # references to the underlying streams.
474 # references to the underlying streams.
478 if sys.platform == 'win32' and self.has_readline:
475 if sys.platform == 'win32' and self.has_readline:
479 Term = io.IOTerm(cout=self.readline._outputfile,
476 Term = io.IOTerm(cout=self.readline._outputfile,
480 cerr=self.readline._outputfile)
477 cerr=self.readline._outputfile)
481 else:
478 else:
482 Term = io.IOTerm()
479 Term = io.IOTerm()
483 io.Term = Term
480 io.Term = Term
484
481
485 def init_prompts(self):
482 def init_prompts(self):
486 # TODO: This is a pass for now because the prompts are managed inside
483 # TODO: This is a pass for now because the prompts are managed inside
487 # the DisplayHook. Once there is a separate prompt manager, this
484 # the DisplayHook. Once there is a separate prompt manager, this
488 # will initialize that object and all prompt related information.
485 # will initialize that object and all prompt related information.
489 pass
486 pass
490
487
491 def init_display_formatter(self):
488 def init_display_formatter(self):
492 self.display_formatter = DisplayFormatter(config=self.config)
489 self.display_formatter = DisplayFormatter(config=self.config)
493
490
494 def init_display_pub(self):
491 def init_display_pub(self):
495 self.display_pub = self.display_pub_class(config=self.config)
492 self.display_pub = self.display_pub_class(config=self.config)
496
493
497 def init_displayhook(self):
494 def init_displayhook(self):
498 # Initialize displayhook, set in/out prompts and printing system
495 # Initialize displayhook, set in/out prompts and printing system
499 self.displayhook = self.displayhook_class(
496 self.displayhook = self.displayhook_class(
500 config=self.config,
497 config=self.config,
501 shell=self,
498 shell=self,
502 cache_size=self.cache_size,
499 cache_size=self.cache_size,
503 input_sep = self.separate_in,
500 input_sep = self.separate_in,
504 output_sep = self.separate_out,
501 output_sep = self.separate_out,
505 output_sep2 = self.separate_out2,
502 output_sep2 = self.separate_out2,
506 ps1 = self.prompt_in1,
503 ps1 = self.prompt_in1,
507 ps2 = self.prompt_in2,
504 ps2 = self.prompt_in2,
508 ps_out = self.prompt_out,
505 ps_out = self.prompt_out,
509 pad_left = self.prompts_pad_left
506 pad_left = self.prompts_pad_left
510 )
507 )
511 # This is a context manager that installs/revmoes the displayhook at
508 # This is a context manager that installs/revmoes the displayhook at
512 # the appropriate time.
509 # the appropriate time.
513 self.display_trap = DisplayTrap(hook=self.displayhook)
510 self.display_trap = DisplayTrap(hook=self.displayhook)
514
511
515 def init_reload_doctest(self):
512 def init_reload_doctest(self):
516 # Do a proper resetting of doctest, including the necessary displayhook
513 # Do a proper resetting of doctest, including the necessary displayhook
517 # monkeypatching
514 # monkeypatching
518 try:
515 try:
519 doctest_reload()
516 doctest_reload()
520 except ImportError:
517 except ImportError:
521 warn("doctest module does not exist.")
518 warn("doctest module does not exist.")
522
519
523 #-------------------------------------------------------------------------
520 #-------------------------------------------------------------------------
524 # Things related to injections into the sys module
521 # Things related to injections into the sys module
525 #-------------------------------------------------------------------------
522 #-------------------------------------------------------------------------
526
523
527 def save_sys_module_state(self):
524 def save_sys_module_state(self):
528 """Save the state of hooks in the sys module.
525 """Save the state of hooks in the sys module.
529
526
530 This has to be called after self.user_ns is created.
527 This has to be called after self.user_ns is created.
531 """
528 """
532 self._orig_sys_module_state = {}
529 self._orig_sys_module_state = {}
533 self._orig_sys_module_state['stdin'] = sys.stdin
530 self._orig_sys_module_state['stdin'] = sys.stdin
534 self._orig_sys_module_state['stdout'] = sys.stdout
531 self._orig_sys_module_state['stdout'] = sys.stdout
535 self._orig_sys_module_state['stderr'] = sys.stderr
532 self._orig_sys_module_state['stderr'] = sys.stderr
536 self._orig_sys_module_state['excepthook'] = sys.excepthook
533 self._orig_sys_module_state['excepthook'] = sys.excepthook
537 try:
534 try:
538 self._orig_sys_modules_main_name = self.user_ns['__name__']
535 self._orig_sys_modules_main_name = self.user_ns['__name__']
539 except KeyError:
536 except KeyError:
540 pass
537 pass
541
538
542 def restore_sys_module_state(self):
539 def restore_sys_module_state(self):
543 """Restore the state of the sys module."""
540 """Restore the state of the sys module."""
544 try:
541 try:
545 for k, v in self._orig_sys_module_state.iteritems():
542 for k, v in self._orig_sys_module_state.iteritems():
546 setattr(sys, k, v)
543 setattr(sys, k, v)
547 except AttributeError:
544 except AttributeError:
548 pass
545 pass
549 # Reset what what done in self.init_sys_modules
546 # Reset what what done in self.init_sys_modules
550 try:
547 try:
551 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
548 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
552 except (AttributeError, KeyError):
549 except (AttributeError, KeyError):
553 pass
550 pass
554
551
555 #-------------------------------------------------------------------------
552 #-------------------------------------------------------------------------
556 # Things related to hooks
553 # Things related to hooks
557 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
558
555
559 def init_hooks(self):
556 def init_hooks(self):
560 # hooks holds pointers used for user-side customizations
557 # hooks holds pointers used for user-side customizations
561 self.hooks = Struct()
558 self.hooks = Struct()
562
559
563 self.strdispatchers = {}
560 self.strdispatchers = {}
564
561
565 # Set all default hooks, defined in the IPython.hooks module.
562 # Set all default hooks, defined in the IPython.hooks module.
566 hooks = IPython.core.hooks
563 hooks = IPython.core.hooks
567 for hook_name in hooks.__all__:
564 for hook_name in hooks.__all__:
568 # default hooks have priority 100, i.e. low; user hooks should have
565 # default hooks have priority 100, i.e. low; user hooks should have
569 # 0-100 priority
566 # 0-100 priority
570 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
567 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
571
568
572 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
569 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
573 """set_hook(name,hook) -> sets an internal IPython hook.
570 """set_hook(name,hook) -> sets an internal IPython hook.
574
571
575 IPython exposes some of its internal API as user-modifiable hooks. By
572 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
573 adding your function to one of these hooks, you can modify IPython's
577 behavior to call at runtime your own routines."""
574 behavior to call at runtime your own routines."""
578
575
579 # At some point in the future, this should validate the hook before it
576 # 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
577 # accepts it. Probably at least check that the hook takes the number
581 # of args it's supposed to.
578 # of args it's supposed to.
582
579
583 f = types.MethodType(hook,self)
580 f = types.MethodType(hook,self)
584
581
585 # check if the hook is for strdispatcher first
582 # check if the hook is for strdispatcher first
586 if str_key is not None:
583 if str_key is not None:
587 sdp = self.strdispatchers.get(name, StrDispatch())
584 sdp = self.strdispatchers.get(name, StrDispatch())
588 sdp.add_s(str_key, f, priority )
585 sdp.add_s(str_key, f, priority )
589 self.strdispatchers[name] = sdp
586 self.strdispatchers[name] = sdp
590 return
587 return
591 if re_key is not None:
588 if re_key is not None:
592 sdp = self.strdispatchers.get(name, StrDispatch())
589 sdp = self.strdispatchers.get(name, StrDispatch())
593 sdp.add_re(re.compile(re_key), f, priority )
590 sdp.add_re(re.compile(re_key), f, priority )
594 self.strdispatchers[name] = sdp
591 self.strdispatchers[name] = sdp
595 return
592 return
596
593
597 dp = getattr(self.hooks, name, None)
594 dp = getattr(self.hooks, name, None)
598 if name not in IPython.core.hooks.__all__:
595 if name not in IPython.core.hooks.__all__:
599 print "Warning! Hook '%s' is not one of %s" % \
596 print "Warning! Hook '%s' is not one of %s" % \
600 (name, IPython.core.hooks.__all__ )
597 (name, IPython.core.hooks.__all__ )
601 if not dp:
598 if not dp:
602 dp = IPython.core.hooks.CommandChainDispatcher()
599 dp = IPython.core.hooks.CommandChainDispatcher()
603
600
604 try:
601 try:
605 dp.add(f,priority)
602 dp.add(f,priority)
606 except AttributeError:
603 except AttributeError:
607 # it was not commandchain, plain old func - replace
604 # it was not commandchain, plain old func - replace
608 dp = f
605 dp = f
609
606
610 setattr(self.hooks,name, dp)
607 setattr(self.hooks,name, dp)
611
608
612 def register_post_execute(self, func):
609 def register_post_execute(self, func):
613 """Register a function for calling after code execution.
610 """Register a function for calling after code execution.
614 """
611 """
615 if not callable(func):
612 if not callable(func):
616 raise ValueError('argument %s must be callable' % func)
613 raise ValueError('argument %s must be callable' % func)
617 self._post_execute.add(func)
614 self._post_execute.add(func)
618
615
619 #-------------------------------------------------------------------------
616 #-------------------------------------------------------------------------
620 # Things related to the "main" module
617 # Things related to the "main" module
621 #-------------------------------------------------------------------------
618 #-------------------------------------------------------------------------
622
619
623 def new_main_mod(self,ns=None):
620 def new_main_mod(self,ns=None):
624 """Return a new 'main' module object for user code execution.
621 """Return a new 'main' module object for user code execution.
625 """
622 """
626 main_mod = self._user_main_module
623 main_mod = self._user_main_module
627 init_fakemod_dict(main_mod,ns)
624 init_fakemod_dict(main_mod,ns)
628 return main_mod
625 return main_mod
629
626
630 def cache_main_mod(self,ns,fname):
627 def cache_main_mod(self,ns,fname):
631 """Cache a main module's namespace.
628 """Cache a main module's namespace.
632
629
633 When scripts are executed via %run, we must keep a reference to the
630 When scripts are executed via %run, we must keep a reference to the
634 namespace of their __main__ module (a FakeModule instance) around so
631 namespace of their __main__ module (a FakeModule instance) around so
635 that Python doesn't clear it, rendering objects defined therein
632 that Python doesn't clear it, rendering objects defined therein
636 useless.
633 useless.
637
634
638 This method keeps said reference in a private dict, keyed by the
635 This method keeps said reference in a private dict, keyed by the
639 absolute path of the module object (which corresponds to the script
636 absolute path of the module object (which corresponds to the script
640 path). This way, for multiple executions of the same script we only
637 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
638 keep one copy of the namespace (the last one), thus preventing memory
642 leaks from old references while allowing the objects from the last
639 leaks from old references while allowing the objects from the last
643 execution to be accessible.
640 execution to be accessible.
644
641
645 Note: we can not allow the actual FakeModule instances to be deleted,
642 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
643 because of how Python tears down modules (it hard-sets all their
647 references to None without regard for reference counts). This method
644 references to None without regard for reference counts). This method
648 must therefore make a *copy* of the given namespace, to allow the
645 must therefore make a *copy* of the given namespace, to allow the
649 original module's __dict__ to be cleared and reused.
646 original module's __dict__ to be cleared and reused.
650
647
651
648
652 Parameters
649 Parameters
653 ----------
650 ----------
654 ns : a namespace (a dict, typically)
651 ns : a namespace (a dict, typically)
655
652
656 fname : str
653 fname : str
657 Filename associated with the namespace.
654 Filename associated with the namespace.
658
655
659 Examples
656 Examples
660 --------
657 --------
661
658
662 In [10]: import IPython
659 In [10]: import IPython
663
660
664 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
661 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
665
662
666 In [12]: IPython.__file__ in _ip._main_ns_cache
663 In [12]: IPython.__file__ in _ip._main_ns_cache
667 Out[12]: True
664 Out[12]: True
668 """
665 """
669 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
666 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
670
667
671 def clear_main_mod_cache(self):
668 def clear_main_mod_cache(self):
672 """Clear the cache of main modules.
669 """Clear the cache of main modules.
673
670
674 Mainly for use by utilities like %reset.
671 Mainly for use by utilities like %reset.
675
672
676 Examples
673 Examples
677 --------
674 --------
678
675
679 In [15]: import IPython
676 In [15]: import IPython
680
677
681 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
678 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
682
679
683 In [17]: len(_ip._main_ns_cache) > 0
680 In [17]: len(_ip._main_ns_cache) > 0
684 Out[17]: True
681 Out[17]: True
685
682
686 In [18]: _ip.clear_main_mod_cache()
683 In [18]: _ip.clear_main_mod_cache()
687
684
688 In [19]: len(_ip._main_ns_cache) == 0
685 In [19]: len(_ip._main_ns_cache) == 0
689 Out[19]: True
686 Out[19]: True
690 """
687 """
691 self._main_ns_cache.clear()
688 self._main_ns_cache.clear()
692
689
693 #-------------------------------------------------------------------------
690 #-------------------------------------------------------------------------
694 # Things related to debugging
691 # Things related to debugging
695 #-------------------------------------------------------------------------
692 #-------------------------------------------------------------------------
696
693
697 def init_pdb(self):
694 def init_pdb(self):
698 # Set calling of pdb on exceptions
695 # Set calling of pdb on exceptions
699 # self.call_pdb is a property
696 # self.call_pdb is a property
700 self.call_pdb = self.pdb
697 self.call_pdb = self.pdb
701
698
702 def _get_call_pdb(self):
699 def _get_call_pdb(self):
703 return self._call_pdb
700 return self._call_pdb
704
701
705 def _set_call_pdb(self,val):
702 def _set_call_pdb(self,val):
706
703
707 if val not in (0,1,False,True):
704 if val not in (0,1,False,True):
708 raise ValueError,'new call_pdb value must be boolean'
705 raise ValueError,'new call_pdb value must be boolean'
709
706
710 # store value in instance
707 # store value in instance
711 self._call_pdb = val
708 self._call_pdb = val
712
709
713 # notify the actual exception handlers
710 # notify the actual exception handlers
714 self.InteractiveTB.call_pdb = val
711 self.InteractiveTB.call_pdb = val
715
712
716 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
713 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
717 'Control auto-activation of pdb at exceptions')
714 'Control auto-activation of pdb at exceptions')
718
715
719 def debugger(self,force=False):
716 def debugger(self,force=False):
720 """Call the pydb/pdb debugger.
717 """Call the pydb/pdb debugger.
721
718
722 Keywords:
719 Keywords:
723
720
724 - force(False): by default, this routine checks the instance call_pdb
721 - 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.
722 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
723 The 'force' option forces the debugger to activate even if the flag
727 is false.
724 is false.
728 """
725 """
729
726
730 if not (force or self.call_pdb):
727 if not (force or self.call_pdb):
731 return
728 return
732
729
733 if not hasattr(sys,'last_traceback'):
730 if not hasattr(sys,'last_traceback'):
734 error('No traceback has been produced, nothing to debug.')
731 error('No traceback has been produced, nothing to debug.')
735 return
732 return
736
733
737 # use pydb if available
734 # use pydb if available
738 if debugger.has_pydb:
735 if debugger.has_pydb:
739 from pydb import pm
736 from pydb import pm
740 else:
737 else:
741 # fallback to our internal debugger
738 # fallback to our internal debugger
742 pm = lambda : self.InteractiveTB.debugger(force=True)
739 pm = lambda : self.InteractiveTB.debugger(force=True)
743 self.history_saving_wrapper(pm)()
740 self.history_saving_wrapper(pm)()
744
741
745 #-------------------------------------------------------------------------
742 #-------------------------------------------------------------------------
746 # Things related to IPython's various namespaces
743 # Things related to IPython's various namespaces
747 #-------------------------------------------------------------------------
744 #-------------------------------------------------------------------------
748
745
749 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
746 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
750 # Create the namespace where the user will operate. user_ns is
747 # 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
748 # 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
749 # the locals argument. But we do carry a user_global_ns namespace
753 # given as the exec 'globals' argument, This is useful in embedding
750 # given as the exec 'globals' argument, This is useful in embedding
754 # situations where the ipython shell opens in a context where the
751 # situations where the ipython shell opens in a context where the
755 # distinction between locals and globals is meaningful. For
752 # distinction between locals and globals is meaningful. For
756 # non-embedded contexts, it is just the same object as the user_ns dict.
753 # non-embedded contexts, it is just the same object as the user_ns dict.
757
754
758 # FIXME. For some strange reason, __builtins__ is showing up at user
755 # 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
756 # 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
757 # should really track down where the problem is coming from. Alex
761 # Schmolck reported this problem first.
758 # Schmolck reported this problem first.
762
759
763 # A useful post by Alex Martelli on this topic:
760 # A useful post by Alex Martelli on this topic:
764 # Re: inconsistent value from __builtins__
761 # Re: inconsistent value from __builtins__
765 # Von: Alex Martelli <aleaxit@yahoo.com>
762 # Von: Alex Martelli <aleaxit@yahoo.com>
766 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
763 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
767 # Gruppen: comp.lang.python
764 # Gruppen: comp.lang.python
768
765
769 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
766 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
770 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
767 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
771 # > <type 'dict'>
768 # > <type 'dict'>
772 # > >>> print type(__builtins__)
769 # > >>> print type(__builtins__)
773 # > <type 'module'>
770 # > <type 'module'>
774 # > Is this difference in return value intentional?
771 # > Is this difference in return value intentional?
775
772
776 # Well, it's documented that '__builtins__' can be either a dictionary
773 # 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
774 # 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
775 # 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
776 # that if you need to access the built-in namespace directly, you
780 # should start with "import __builtin__" (note, no 's') which will
777 # should start with "import __builtin__" (note, no 's') which will
781 # definitely give you a module. Yeah, it's somewhat confusing:-(.
778 # definitely give you a module. Yeah, it's somewhat confusing:-(.
782
779
783 # These routines return properly built dicts as needed by the rest of
780 # 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
781 # the code, and can also be used by extension writers to generate
785 # properly initialized namespaces.
782 # properly initialized namespaces.
786 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
783 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
787 user_global_ns)
784 user_global_ns)
788
785
789 # Assign namespaces
786 # Assign namespaces
790 # This is the namespace where all normal user variables live
787 # This is the namespace where all normal user variables live
791 self.user_ns = user_ns
788 self.user_ns = user_ns
792 self.user_global_ns = user_global_ns
789 self.user_global_ns = user_global_ns
793
790
794 # An auxiliary namespace that checks what parts of the user_ns were
791 # 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
792 # 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
793 # 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.
794 # doesn't need to be separately tracked in the ns_table.
798 self.user_ns_hidden = {}
795 self.user_ns_hidden = {}
799
796
800 # A namespace to keep track of internal data structures to prevent
797 # A namespace to keep track of internal data structures to prevent
801 # them from cluttering user-visible stuff. Will be updated later
798 # them from cluttering user-visible stuff. Will be updated later
802 self.internal_ns = {}
799 self.internal_ns = {}
803
800
804 # Now that FakeModule produces a real module, we've run into a nasty
801 # 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
802 # 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
803 # code ran is deleted. Now that this object is a true module (needed
807 # so docetst and other tools work correctly), the Python module
804 # so docetst and other tools work correctly), the Python module
808 # teardown mechanism runs over it, and sets to None every variable
805 # teardown mechanism runs over it, and sets to None every variable
809 # present in that module. Top-level references to objects from the
806 # present in that module. Top-level references to objects from the
810 # script survive, because the user_ns is updated with them. However,
807 # script survive, because the user_ns is updated with them. However,
811 # calling functions defined in the script that use other things from
808 # calling functions defined in the script that use other things from
812 # the script will fail, because the function's closure had references
809 # 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
810 # to the original objects, which are now all None. So we must protect
814 # these modules from deletion by keeping a cache.
811 # these modules from deletion by keeping a cache.
815 #
812 #
816 # To avoid keeping stale modules around (we only need the one from the
813 # 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
814 # 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,
815 # only the last version of the module is held in the cache. Note,
819 # however, that we must cache the module *namespace contents* (their
816 # however, that we must cache the module *namespace contents* (their
820 # __dict__). Because if we try to cache the actual modules, old ones
817 # __dict__). Because if we try to cache the actual modules, old ones
821 # (uncached) could be destroyed while still holding references (such as
818 # (uncached) could be destroyed while still holding references (such as
822 # those held by GUI objects that tend to be long-lived)>
819 # those held by GUI objects that tend to be long-lived)>
823 #
820 #
824 # The %reset command will flush this cache. See the cache_main_mod()
821 # The %reset command will flush this cache. See the cache_main_mod()
825 # and clear_main_mod_cache() methods for details on use.
822 # and clear_main_mod_cache() methods for details on use.
826
823
827 # This is the cache used for 'main' namespaces
824 # This is the cache used for 'main' namespaces
828 self._main_ns_cache = {}
825 self._main_ns_cache = {}
829 # And this is the single instance of FakeModule whose __dict__ we keep
826 # And this is the single instance of FakeModule whose __dict__ we keep
830 # copying and clearing for reuse on each %run
827 # copying and clearing for reuse on each %run
831 self._user_main_module = FakeModule()
828 self._user_main_module = FakeModule()
832
829
833 # A table holding all the namespaces IPython deals with, so that
830 # A table holding all the namespaces IPython deals with, so that
834 # introspection facilities can search easily.
831 # introspection facilities can search easily.
835 self.ns_table = {'user':user_ns,
832 self.ns_table = {'user':user_ns,
836 'user_global':user_global_ns,
833 'user_global':user_global_ns,
837 'internal':self.internal_ns,
834 'internal':self.internal_ns,
838 'builtin':__builtin__.__dict__
835 'builtin':__builtin__.__dict__
839 }
836 }
840
837
841 # Similarly, track all namespaces where references can be held and that
838 # 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
839 # 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
840 # 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
841 # user_global_ns, can NOT be listed here, as clearing them blindly
845 # causes errors in object __del__ methods. Instead, the reset() method
842 # causes errors in object __del__ methods. Instead, the reset() method
846 # clears them manually and carefully.
843 # clears them manually and carefully.
847 self.ns_refs_table = [ self.user_ns_hidden,
844 self.ns_refs_table = [ self.user_ns_hidden,
848 self.internal_ns, self._main_ns_cache ]
845 self.internal_ns, self._main_ns_cache ]
849
846
850 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
847 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
851 """Return a valid local and global user interactive namespaces.
848 """Return a valid local and global user interactive namespaces.
852
849
853 This builds a dict with the minimal information needed to operate as a
850 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
851 valid IPython user namespace, which you can pass to the various
855 embedding classes in ipython. The default implementation returns the
852 embedding classes in ipython. The default implementation returns the
856 same dict for both the locals and the globals to allow functions to
853 same dict for both the locals and the globals to allow functions to
857 refer to variables in the namespace. Customized implementations can
854 refer to variables in the namespace. Customized implementations can
858 return different dicts. The locals dictionary can actually be anything
855 return different dicts. The locals dictionary can actually be anything
859 following the basic mapping protocol of a dict, but the globals dict
856 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
857 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
858 custom object for the locals namespace synchronize with the globals
862 dict somehow.
859 dict somehow.
863
860
864 Raises TypeError if the provided globals namespace is not a true dict.
861 Raises TypeError if the provided globals namespace is not a true dict.
865
862
866 Parameters
863 Parameters
867 ----------
864 ----------
868 user_ns : dict-like, optional
865 user_ns : dict-like, optional
869 The current user namespace. The items in this namespace should
866 The current user namespace. The items in this namespace should
870 be included in the output. If None, an appropriate blank
867 be included in the output. If None, an appropriate blank
871 namespace should be created.
868 namespace should be created.
872 user_global_ns : dict, optional
869 user_global_ns : dict, optional
873 The current user global namespace. The items in this namespace
870 The current user global namespace. The items in this namespace
874 should be included in the output. If None, an appropriate
871 should be included in the output. If None, an appropriate
875 blank namespace should be created.
872 blank namespace should be created.
876
873
877 Returns
874 Returns
878 -------
875 -------
879 A pair of dictionary-like object to be used as the local namespace
876 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.
877 of the interpreter and a dict to be used as the global namespace.
881 """
878 """
882
879
883
880
884 # We must ensure that __builtin__ (without the final 's') is always
881 # We must ensure that __builtin__ (without the final 's') is always
885 # available and pointing to the __builtin__ *module*. For more details:
882 # available and pointing to the __builtin__ *module*. For more details:
886 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
883 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
887
884
888 if user_ns is None:
885 if user_ns is None:
889 # Set __name__ to __main__ to better match the behavior of the
886 # Set __name__ to __main__ to better match the behavior of the
890 # normal interpreter.
887 # normal interpreter.
891 user_ns = {'__name__' :'__main__',
888 user_ns = {'__name__' :'__main__',
892 '__builtin__' : __builtin__,
889 '__builtin__' : __builtin__,
893 '__builtins__' : __builtin__,
890 '__builtins__' : __builtin__,
894 }
891 }
895 else:
892 else:
896 user_ns.setdefault('__name__','__main__')
893 user_ns.setdefault('__name__','__main__')
897 user_ns.setdefault('__builtin__',__builtin__)
894 user_ns.setdefault('__builtin__',__builtin__)
898 user_ns.setdefault('__builtins__',__builtin__)
895 user_ns.setdefault('__builtins__',__builtin__)
899
896
900 if user_global_ns is None:
897 if user_global_ns is None:
901 user_global_ns = user_ns
898 user_global_ns = user_ns
902 if type(user_global_ns) is not dict:
899 if type(user_global_ns) is not dict:
903 raise TypeError("user_global_ns must be a true dict; got %r"
900 raise TypeError("user_global_ns must be a true dict; got %r"
904 % type(user_global_ns))
901 % type(user_global_ns))
905
902
906 return user_ns, user_global_ns
903 return user_ns, user_global_ns
907
904
908 def init_sys_modules(self):
905 def init_sys_modules(self):
909 # We need to insert into sys.modules something that looks like a
906 # We need to insert into sys.modules something that looks like a
910 # module but which accesses the IPython namespace, for shelve and
907 # module but which accesses the IPython namespace, for shelve and
911 # pickle to work interactively. Normally they rely on getting
908 # pickle to work interactively. Normally they rely on getting
912 # everything out of __main__, but for embedding purposes each IPython
909 # everything out of __main__, but for embedding purposes each IPython
913 # instance has its own private namespace, so we can't go shoving
910 # instance has its own private namespace, so we can't go shoving
914 # everything into __main__.
911 # everything into __main__.
915
912
916 # note, however, that we should only do this for non-embedded
913 # note, however, that we should only do this for non-embedded
917 # ipythons, which really mimic the __main__.__dict__ with their own
914 # ipythons, which really mimic the __main__.__dict__ with their own
918 # namespace. Embedded instances, on the other hand, should not do
915 # namespace. Embedded instances, on the other hand, should not do
919 # this because they need to manage the user local/global namespaces
916 # this because they need to manage the user local/global namespaces
920 # only, but they live within a 'normal' __main__ (meaning, they
917 # only, but they live within a 'normal' __main__ (meaning, they
921 # shouldn't overtake the execution environment of the script they're
918 # shouldn't overtake the execution environment of the script they're
922 # embedded in).
919 # embedded in).
923
920
924 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
921 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
925
922
926 try:
923 try:
927 main_name = self.user_ns['__name__']
924 main_name = self.user_ns['__name__']
928 except KeyError:
925 except KeyError:
929 raise KeyError('user_ns dictionary MUST have a "__name__" key')
926 raise KeyError('user_ns dictionary MUST have a "__name__" key')
930 else:
927 else:
931 sys.modules[main_name] = FakeModule(self.user_ns)
928 sys.modules[main_name] = FakeModule(self.user_ns)
932
929
933 def init_user_ns(self):
930 def init_user_ns(self):
934 """Initialize all user-visible namespaces to their minimum defaults.
931 """Initialize all user-visible namespaces to their minimum defaults.
935
932
936 Certain history lists are also initialized here, as they effectively
933 Certain history lists are also initialized here, as they effectively
937 act as user namespaces.
934 act as user namespaces.
938
935
939 Notes
936 Notes
940 -----
937 -----
941 All data structures here are only filled in, they are NOT reset by this
938 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
939 method. If they were not empty before, data will simply be added to
943 therm.
940 therm.
944 """
941 """
945 # This function works in two parts: first we put a few things in
942 # 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
943 # 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
944 # 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
945 # 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)
946 # session (probably nothing, so theye really only see their own stuff)
950
947
951 # The user dict must *always* have a __builtin__ reference to the
948 # The user dict must *always* have a __builtin__ reference to the
952 # Python standard __builtin__ namespace, which must be imported.
949 # Python standard __builtin__ namespace, which must be imported.
953 # This is so that certain operations in prompt evaluation can be
950 # This is so that certain operations in prompt evaluation can be
954 # reliably executed with builtins. Note that we can NOT use
951 # reliably executed with builtins. Note that we can NOT use
955 # __builtins__ (note the 's'), because that can either be a dict or a
952 # __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
953 # module, and can even mutate at runtime, depending on the context
957 # (Python makes no guarantees on it). In contrast, __builtin__ is
954 # (Python makes no guarantees on it). In contrast, __builtin__ is
958 # always a module object, though it must be explicitly imported.
955 # always a module object, though it must be explicitly imported.
959
956
960 # For more details:
957 # For more details:
961 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
958 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
962 ns = dict(__builtin__ = __builtin__)
959 ns = dict(__builtin__ = __builtin__)
963
960
964 # Put 'help' in the user namespace
961 # Put 'help' in the user namespace
965 try:
962 try:
966 from site import _Helper
963 from site import _Helper
967 ns['help'] = _Helper()
964 ns['help'] = _Helper()
968 except ImportError:
965 except ImportError:
969 warn('help() not available - check site.py')
966 warn('help() not available - check site.py')
970
967
971 # make global variables for user access to the histories
968 # make global variables for user access to the histories
972 ns['_ih'] = self.history_manager.input_hist_parsed
969 ns['_ih'] = self.history_manager.input_hist_parsed
973 ns['_oh'] = self.history_manager.output_hist
970 ns['_oh'] = self.history_manager.output_hist
974 ns['_dh'] = self.history_manager.dir_hist
971 ns['_dh'] = self.history_manager.dir_hist
975
972
976 ns['_sh'] = shadowns
973 ns['_sh'] = shadowns
977
974
978 # user aliases to input and output histories. These shouldn't show up
975 # user aliases to input and output histories. These shouldn't show up
979 # in %who, as they can have very large reprs.
976 # in %who, as they can have very large reprs.
980 ns['In'] = self.history_manager.input_hist_parsed
977 ns['In'] = self.history_manager.input_hist_parsed
981 ns['Out'] = self.history_manager.output_hist
978 ns['Out'] = self.history_manager.output_hist
982
979
983 # Store myself as the public api!!!
980 # Store myself as the public api!!!
984 ns['get_ipython'] = self.get_ipython
981 ns['get_ipython'] = self.get_ipython
985
982
986 # Sync what we've added so far to user_ns_hidden so these aren't seen
983 # Sync what we've added so far to user_ns_hidden so these aren't seen
987 # by %who
984 # by %who
988 self.user_ns_hidden.update(ns)
985 self.user_ns_hidden.update(ns)
989
986
990 # Anything put into ns now would show up in %who. Think twice before
987 # 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
988 # putting anything here, as we really want %who to show the user their
992 # stuff, not our variables.
989 # stuff, not our variables.
993
990
994 # Finally, update the real user's namespace
991 # Finally, update the real user's namespace
995 self.user_ns.update(ns)
992 self.user_ns.update(ns)
996
993
997 def reset(self):
994 def reset(self, new_session=True):
998 """Clear all internal namespaces.
995 """Clear all internal namespaces.
999
996
1000 Note that this is much more aggressive than %reset, since it clears
997 Note that this is much more aggressive than %reset, since it clears
1001 fully all namespaces, as well as all input/output lists.
998 fully all namespaces, as well as all input/output lists.
999
1000 If new_session is True, a new history session will be opened.
1002 """
1001 """
1003 # Clear histories
1002 # Clear histories
1004 self.history_manager.reset()
1003 self.history_manager.reset(new_session)
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, config=self.config)
1253
1254 def save_history(self):
1255 """Save input history to a file (via readline library)."""
1256 self.history_manager.save_history()
1257
1258 def reload_history(self):
1259 """Reload the input history from disk file."""
1260 self.history_manager.reload_history()
1261
1252
1262 def history_saving_wrapper(self, func):
1253 def history_saving_wrapper(self, func):
1263 """ Wrap func for readline history saving
1254 """ Wrap func for readline history saving
1264
1255
1265 Convert func into callable that saves & restores
1256 Convert func into callable that saves & restores
1266 history around the call """
1257 history around the call """
1267
1258
1268 if self.has_readline:
1259 if self.has_readline:
1269 from IPython.utils import rlineimpl as readline
1260 from IPython.utils import rlineimpl as readline
1270 else:
1261 else:
1271 return func
1262 return func
1272
1263
1273 def wrapper():
1264 def wrapper():
1274 self.save_history()
1265 self.save_history()
1275 try:
1266 try:
1276 func()
1267 func()
1277 finally:
1268 finally:
1278 self.reload_history()
1269 self.reload_history()
1279 return wrapper
1270 return wrapper
1280
1271
1281 def get_history(self, index=None, raw=False, output=True):
1282 return self.history_manager.get_history(index, raw, output)
1283
1284
1272
1285 #-------------------------------------------------------------------------
1273 #-------------------------------------------------------------------------
1286 # Things related to exception handling and tracebacks (not debugging)
1274 # Things related to exception handling and tracebacks (not debugging)
1287 #-------------------------------------------------------------------------
1275 #-------------------------------------------------------------------------
1288
1276
1289 def init_traceback_handlers(self, custom_exceptions):
1277 def init_traceback_handlers(self, custom_exceptions):
1290 # Syntax error handler.
1278 # Syntax error handler.
1291 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1279 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1292
1280
1293 # The interactive one is initialized with an offset, meaning we always
1281 # 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
1282 # want to remove the topmost item in the traceback, which is our own
1295 # internal code. Valid modes: ['Plain','Context','Verbose']
1283 # internal code. Valid modes: ['Plain','Context','Verbose']
1296 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1284 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1297 color_scheme='NoColor',
1285 color_scheme='NoColor',
1298 tb_offset = 1,
1286 tb_offset = 1,
1299 check_cache=self.compile.check_cache)
1287 check_cache=self.compile.check_cache)
1300
1288
1301 # The instance will store a pointer to the system-wide exception hook,
1289 # 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
1290 # so that runtime code (such as magics) can access it. This is because
1303 # during the read-eval loop, it may get temporarily overwritten.
1291 # during the read-eval loop, it may get temporarily overwritten.
1304 self.sys_excepthook = sys.excepthook
1292 self.sys_excepthook = sys.excepthook
1305
1293
1306 # and add any custom exception handlers the user may have specified
1294 # and add any custom exception handlers the user may have specified
1307 self.set_custom_exc(*custom_exceptions)
1295 self.set_custom_exc(*custom_exceptions)
1308
1296
1309 # Set the exception mode
1297 # Set the exception mode
1310 self.InteractiveTB.set_mode(mode=self.xmode)
1298 self.InteractiveTB.set_mode(mode=self.xmode)
1311
1299
1312 def set_custom_exc(self, exc_tuple, handler):
1300 def set_custom_exc(self, exc_tuple, handler):
1313 """set_custom_exc(exc_tuple,handler)
1301 """set_custom_exc(exc_tuple,handler)
1314
1302
1315 Set a custom exception handler, which will be called if any of the
1303 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
1304 exceptions in exc_tuple occur in the mainloop (specifically, in the
1317 run_code() method.
1305 run_code() method.
1318
1306
1319 Inputs:
1307 Inputs:
1320
1308
1321 - exc_tuple: a *tuple* of valid exceptions to call the defined
1309 - 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
1310 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
1311 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:
1312 you only want to trap a single exception, use a singleton tuple:
1325
1313
1326 exc_tuple == (MyCustomException,)
1314 exc_tuple == (MyCustomException,)
1327
1315
1328 - handler: this must be defined as a function with the following
1316 - handler: this must be defined as a function with the following
1329 basic interface::
1317 basic interface::
1330
1318
1331 def my_handler(self, etype, value, tb, tb_offset=None)
1319 def my_handler(self, etype, value, tb, tb_offset=None)
1332 ...
1320 ...
1333 # The return value must be
1321 # The return value must be
1334 return structured_traceback
1322 return structured_traceback
1335
1323
1336 This will be made into an instance method (via types.MethodType)
1324 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
1325 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
1326 listed in the exc_tuple are caught. If the handler is None, an
1339 internal basic one is used, which just prints basic info.
1327 internal basic one is used, which just prints basic info.
1340
1328
1341 WARNING: by putting in your own exception handler into IPython's main
1329 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
1330 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."""
1331 facility should only be used if you really know what you are doing."""
1344
1332
1345 assert type(exc_tuple)==type(()) , \
1333 assert type(exc_tuple)==type(()) , \
1346 "The custom exceptions must be given AS A TUPLE."
1334 "The custom exceptions must be given AS A TUPLE."
1347
1335
1348 def dummy_handler(self,etype,value,tb):
1336 def dummy_handler(self,etype,value,tb):
1349 print '*** Simple custom exception handler ***'
1337 print '*** Simple custom exception handler ***'
1350 print 'Exception type :',etype
1338 print 'Exception type :',etype
1351 print 'Exception value:',value
1339 print 'Exception value:',value
1352 print 'Traceback :',tb
1340 print 'Traceback :',tb
1353 print 'Source code :','\n'.join(self.buffer)
1341 print 'Source code :','\n'.join(self.buffer)
1354
1342
1355 if handler is None: handler = dummy_handler
1343 if handler is None: handler = dummy_handler
1356
1344
1357 self.CustomTB = types.MethodType(handler,self)
1345 self.CustomTB = types.MethodType(handler,self)
1358 self.custom_exceptions = exc_tuple
1346 self.custom_exceptions = exc_tuple
1359
1347
1360 def excepthook(self, etype, value, tb):
1348 def excepthook(self, etype, value, tb):
1361 """One more defense for GUI apps that call sys.excepthook.
1349 """One more defense for GUI apps that call sys.excepthook.
1362
1350
1363 GUI frameworks like wxPython trap exceptions and call
1351 GUI frameworks like wxPython trap exceptions and call
1364 sys.excepthook themselves. I guess this is a feature that
1352 sys.excepthook themselves. I guess this is a feature that
1365 enables them to keep running after exceptions that would
1353 enables them to keep running after exceptions that would
1366 otherwise kill their mainloop. This is a bother for IPython
1354 otherwise kill their mainloop. This is a bother for IPython
1367 which excepts to catch all of the program exceptions with a try:
1355 which excepts to catch all of the program exceptions with a try:
1368 except: statement.
1356 except: statement.
1369
1357
1370 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1358 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
1359 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
1360 IPython crashed. In order to work around this, we can disable the
1373 CrashHandler and replace it with this excepthook instead, which prints a
1361 CrashHandler and replace it with this excepthook instead, which prints a
1374 regular traceback using our InteractiveTB. In this fashion, apps which
1362 regular traceback using our InteractiveTB. In this fashion, apps which
1375 call sys.excepthook will generate a regular-looking exception from
1363 call sys.excepthook will generate a regular-looking exception from
1376 IPython, and the CrashHandler will only be triggered by real IPython
1364 IPython, and the CrashHandler will only be triggered by real IPython
1377 crashes.
1365 crashes.
1378
1366
1379 This hook should be used sparingly, only in places which are not likely
1367 This hook should be used sparingly, only in places which are not likely
1380 to be true IPython errors.
1368 to be true IPython errors.
1381 """
1369 """
1382 self.showtraceback((etype,value,tb),tb_offset=0)
1370 self.showtraceback((etype,value,tb),tb_offset=0)
1383
1371
1384 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1372 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1385 exception_only=False):
1373 exception_only=False):
1386 """Display the exception that just occurred.
1374 """Display the exception that just occurred.
1387
1375
1388 If nothing is known about the exception, this is the method which
1376 If nothing is known about the exception, this is the method which
1389 should be used throughout the code for presenting user tracebacks,
1377 should be used throughout the code for presenting user tracebacks,
1390 rather than directly invoking the InteractiveTB object.
1378 rather than directly invoking the InteractiveTB object.
1391
1379
1392 A specific showsyntaxerror() also exists, but this method can take
1380 A specific showsyntaxerror() also exists, but this method can take
1393 care of calling it if needed, so unless you are explicitly catching a
1381 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
1382 SyntaxError exception, don't try to analyze the stack manually and
1395 simply call this method."""
1383 simply call this method."""
1396
1384
1397 try:
1385 try:
1398 if exc_tuple is None:
1386 if exc_tuple is None:
1399 etype, value, tb = sys.exc_info()
1387 etype, value, tb = sys.exc_info()
1400 else:
1388 else:
1401 etype, value, tb = exc_tuple
1389 etype, value, tb = exc_tuple
1402
1390
1403 if etype is None:
1391 if etype is None:
1404 if hasattr(sys, 'last_type'):
1392 if hasattr(sys, 'last_type'):
1405 etype, value, tb = sys.last_type, sys.last_value, \
1393 etype, value, tb = sys.last_type, sys.last_value, \
1406 sys.last_traceback
1394 sys.last_traceback
1407 else:
1395 else:
1408 self.write_err('No traceback available to show.\n')
1396 self.write_err('No traceback available to show.\n')
1409 return
1397 return
1410
1398
1411 if etype is SyntaxError:
1399 if etype is SyntaxError:
1412 # Though this won't be called by syntax errors in the input
1400 # Though this won't be called by syntax errors in the input
1413 # line, there may be SyntaxError cases whith imported code.
1401 # line, there may be SyntaxError cases whith imported code.
1414 self.showsyntaxerror(filename)
1402 self.showsyntaxerror(filename)
1415 elif etype is UsageError:
1403 elif etype is UsageError:
1416 print "UsageError:", value
1404 print "UsageError:", value
1417 else:
1405 else:
1418 # WARNING: these variables are somewhat deprecated and not
1406 # WARNING: these variables are somewhat deprecated and not
1419 # necessarily safe to use in a threaded environment, but tools
1407 # necessarily safe to use in a threaded environment, but tools
1420 # like pdb depend on their existence, so let's set them. If we
1408 # 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.
1409 # find problems in the field, we'll need to revisit their use.
1422 sys.last_type = etype
1410 sys.last_type = etype
1423 sys.last_value = value
1411 sys.last_value = value
1424 sys.last_traceback = tb
1412 sys.last_traceback = tb
1425
1413
1426 if etype in self.custom_exceptions:
1414 if etype in self.custom_exceptions:
1427 # FIXME: Old custom traceback objects may just return a
1415 # FIXME: Old custom traceback objects may just return a
1428 # string, in that case we just put it into a list
1416 # string, in that case we just put it into a list
1429 stb = self.CustomTB(etype, value, tb, tb_offset)
1417 stb = self.CustomTB(etype, value, tb, tb_offset)
1430 if isinstance(ctb, basestring):
1418 if isinstance(ctb, basestring):
1431 stb = [stb]
1419 stb = [stb]
1432 else:
1420 else:
1433 if exception_only:
1421 if exception_only:
1434 stb = ['An exception has occurred, use %tb to see '
1422 stb = ['An exception has occurred, use %tb to see '
1435 'the full traceback.\n']
1423 'the full traceback.\n']
1436 stb.extend(self.InteractiveTB.get_exception_only(etype,
1424 stb.extend(self.InteractiveTB.get_exception_only(etype,
1437 value))
1425 value))
1438 else:
1426 else:
1439 stb = self.InteractiveTB.structured_traceback(etype,
1427 stb = self.InteractiveTB.structured_traceback(etype,
1440 value, tb, tb_offset=tb_offset)
1428 value, tb, tb_offset=tb_offset)
1441 # FIXME: the pdb calling should be done by us, not by
1429 # FIXME: the pdb calling should be done by us, not by
1442 # the code computing the traceback.
1430 # the code computing the traceback.
1443 if self.InteractiveTB.call_pdb:
1431 if self.InteractiveTB.call_pdb:
1444 # pdb mucks up readline, fix it back
1432 # pdb mucks up readline, fix it back
1445 self.set_readline_completer()
1433 self.set_readline_completer()
1446
1434
1447 # Actually show the traceback
1435 # Actually show the traceback
1448 self._showtraceback(etype, value, stb)
1436 self._showtraceback(etype, value, stb)
1449
1437
1450 except KeyboardInterrupt:
1438 except KeyboardInterrupt:
1451 self.write_err("\nKeyboardInterrupt\n")
1439 self.write_err("\nKeyboardInterrupt\n")
1452
1440
1453 def _showtraceback(self, etype, evalue, stb):
1441 def _showtraceback(self, etype, evalue, stb):
1454 """Actually show a traceback.
1442 """Actually show a traceback.
1455
1443
1456 Subclasses may override this method to put the traceback on a different
1444 Subclasses may override this method to put the traceback on a different
1457 place, like a side channel.
1445 place, like a side channel.
1458 """
1446 """
1459 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1447 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1460
1448
1461 def showsyntaxerror(self, filename=None):
1449 def showsyntaxerror(self, filename=None):
1462 """Display the syntax error that just occurred.
1450 """Display the syntax error that just occurred.
1463
1451
1464 This doesn't display a stack trace because there isn't one.
1452 This doesn't display a stack trace because there isn't one.
1465
1453
1466 If a filename is given, it is stuffed in the exception instead
1454 If a filename is given, it is stuffed in the exception instead
1467 of what was there before (because Python's parser always uses
1455 of what was there before (because Python's parser always uses
1468 "<string>" when reading from a string).
1456 "<string>" when reading from a string).
1469 """
1457 """
1470 etype, value, last_traceback = sys.exc_info()
1458 etype, value, last_traceback = sys.exc_info()
1471
1459
1472 # See note about these variables in showtraceback() above
1460 # See note about these variables in showtraceback() above
1473 sys.last_type = etype
1461 sys.last_type = etype
1474 sys.last_value = value
1462 sys.last_value = value
1475 sys.last_traceback = last_traceback
1463 sys.last_traceback = last_traceback
1476
1464
1477 if filename and etype is SyntaxError:
1465 if filename and etype is SyntaxError:
1478 # Work hard to stuff the correct filename in the exception
1466 # Work hard to stuff the correct filename in the exception
1479 try:
1467 try:
1480 msg, (dummy_filename, lineno, offset, line) = value
1468 msg, (dummy_filename, lineno, offset, line) = value
1481 except:
1469 except:
1482 # Not the format we expect; leave it alone
1470 # Not the format we expect; leave it alone
1483 pass
1471 pass
1484 else:
1472 else:
1485 # Stuff in the right filename
1473 # Stuff in the right filename
1486 try:
1474 try:
1487 # Assume SyntaxError is a class exception
1475 # Assume SyntaxError is a class exception
1488 value = SyntaxError(msg, (filename, lineno, offset, line))
1476 value = SyntaxError(msg, (filename, lineno, offset, line))
1489 except:
1477 except:
1490 # If that failed, assume SyntaxError is a string
1478 # If that failed, assume SyntaxError is a string
1491 value = msg, (filename, lineno, offset, line)
1479 value = msg, (filename, lineno, offset, line)
1492 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1480 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1493 self._showtraceback(etype, value, stb)
1481 self._showtraceback(etype, value, stb)
1494
1482
1495 #-------------------------------------------------------------------------
1483 #-------------------------------------------------------------------------
1496 # Things related to readline
1484 # Things related to readline
1497 #-------------------------------------------------------------------------
1485 #-------------------------------------------------------------------------
1498
1486
1499 def init_readline(self):
1487 def init_readline(self):
1500 """Command history completion/saving/reloading."""
1488 """Command history completion/saving/reloading."""
1501
1489
1502 if self.readline_use:
1490 if self.readline_use:
1503 import IPython.utils.rlineimpl as readline
1491 import IPython.utils.rlineimpl as readline
1504
1492
1505 self.rl_next_input = None
1493 self.rl_next_input = None
1506 self.rl_do_indent = False
1494 self.rl_do_indent = False
1507
1495
1508 if not self.readline_use or not readline.have_readline:
1496 if not self.readline_use or not readline.have_readline:
1509 self.has_readline = False
1497 self.has_readline = False
1510 self.readline = None
1498 self.readline = None
1511 # Set a number of methods that depend on readline to be no-op
1499 # Set a number of methods that depend on readline to be no-op
1512 self.set_readline_completer = no_op
1500 self.set_readline_completer = no_op
1513 self.set_custom_completer = no_op
1501 self.set_custom_completer = no_op
1514 self.set_completer_frame = no_op
1502 self.set_completer_frame = no_op
1515 warn('Readline services not available or not loaded.')
1503 warn('Readline services not available or not loaded.')
1516 else:
1504 else:
1517 self.has_readline = True
1505 self.has_readline = True
1518 self.readline = readline
1506 self.readline = readline
1519 sys.modules['readline'] = readline
1507 sys.modules['readline'] = readline
1520
1508
1521 # Platform-specific configuration
1509 # Platform-specific configuration
1522 if os.name == 'nt':
1510 if os.name == 'nt':
1523 # FIXME - check with Frederick to see if we can harmonize
1511 # FIXME - check with Frederick to see if we can harmonize
1524 # naming conventions with pyreadline to avoid this
1512 # naming conventions with pyreadline to avoid this
1525 # platform-dependent check
1513 # platform-dependent check
1526 self.readline_startup_hook = readline.set_pre_input_hook
1514 self.readline_startup_hook = readline.set_pre_input_hook
1527 else:
1515 else:
1528 self.readline_startup_hook = readline.set_startup_hook
1516 self.readline_startup_hook = readline.set_startup_hook
1529
1517
1530 # Load user's initrc file (readline config)
1518 # Load user's initrc file (readline config)
1531 # Or if libedit is used, load editrc.
1519 # Or if libedit is used, load editrc.
1532 inputrc_name = os.environ.get('INPUTRC')
1520 inputrc_name = os.environ.get('INPUTRC')
1533 if inputrc_name is None:
1521 if inputrc_name is None:
1534 home_dir = get_home_dir()
1522 home_dir = get_home_dir()
1535 if home_dir is not None:
1523 if home_dir is not None:
1536 inputrc_name = '.inputrc'
1524 inputrc_name = '.inputrc'
1537 if readline.uses_libedit:
1525 if readline.uses_libedit:
1538 inputrc_name = '.editrc'
1526 inputrc_name = '.editrc'
1539 inputrc_name = os.path.join(home_dir, inputrc_name)
1527 inputrc_name = os.path.join(home_dir, inputrc_name)
1540 if os.path.isfile(inputrc_name):
1528 if os.path.isfile(inputrc_name):
1541 try:
1529 try:
1542 readline.read_init_file(inputrc_name)
1530 readline.read_init_file(inputrc_name)
1543 except:
1531 except:
1544 warn('Problems reading readline initialization file <%s>'
1532 warn('Problems reading readline initialization file <%s>'
1545 % inputrc_name)
1533 % inputrc_name)
1546
1534
1547 # Configure readline according to user's prefs
1535 # Configure readline according to user's prefs
1548 # This is only done if GNU readline is being used. If libedit
1536 # This is only done if GNU readline is being used. If libedit
1549 # is being used (as on Leopard) the readline config is
1537 # is being used (as on Leopard) the readline config is
1550 # not run as the syntax for libedit is different.
1538 # not run as the syntax for libedit is different.
1551 if not readline.uses_libedit:
1539 if not readline.uses_libedit:
1552 for rlcommand in self.readline_parse_and_bind:
1540 for rlcommand in self.readline_parse_and_bind:
1553 #print "loading rl:",rlcommand # dbg
1541 #print "loading rl:",rlcommand # dbg
1554 readline.parse_and_bind(rlcommand)
1542 readline.parse_and_bind(rlcommand)
1555
1543
1556 # Remove some chars from the delimiters list. If we encounter
1544 # Remove some chars from the delimiters list. If we encounter
1557 # unicode chars, discard them.
1545 # unicode chars, discard them.
1558 delims = readline.get_completer_delims().encode("ascii", "ignore")
1546 delims = readline.get_completer_delims().encode("ascii", "ignore")
1559 delims = delims.translate(None, self.readline_remove_delims)
1547 delims = delims.translate(None, self.readline_remove_delims)
1560 delims = delims.replace(ESC_MAGIC, '')
1548 delims = delims.replace(ESC_MAGIC, '')
1561 readline.set_completer_delims(delims)
1549 readline.set_completer_delims(delims)
1562 # otherwise we end up with a monster history after a while:
1550 # otherwise we end up with a monster history after a while:
1563 readline.set_history_length(self.history_length)
1551 readline.set_history_length(self.history_length)
1564 try:
1552
1565 #print '*** Reading readline history' # dbg
1553 # Load the last 1000 lines from history
1566 self.reload_history()
1554 for _, _, cell in self.history_manager.get_tail(1000,
1567 except IOError:
1555 include_latest=True):
1568 pass # It doesn't exist yet.
1556 if cell.strip(): # Ignore blank lines
1557 for line in cell.splitlines():
1558 readline.add_history(line)
1569
1559
1570 # Configure auto-indent for all platforms
1560 # Configure auto-indent for all platforms
1571 self.set_autoindent(self.autoindent)
1561 self.set_autoindent(self.autoindent)
1572
1562
1573 def set_next_input(self, s):
1563 def set_next_input(self, s):
1574 """ Sets the 'default' input string for the next command line.
1564 """ Sets the 'default' input string for the next command line.
1575
1565
1576 Requires readline.
1566 Requires readline.
1577
1567
1578 Example:
1568 Example:
1579
1569
1580 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1570 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1581 [D:\ipython]|2> Hello Word_ # cursor is here
1571 [D:\ipython]|2> Hello Word_ # cursor is here
1582 """
1572 """
1583
1573
1584 self.rl_next_input = s
1574 self.rl_next_input = s
1585
1575
1586 # Maybe move this to the terminal subclass?
1576 # Maybe move this to the terminal subclass?
1587 def pre_readline(self):
1577 def pre_readline(self):
1588 """readline hook to be used at the start of each line.
1578 """readline hook to be used at the start of each line.
1589
1579
1590 Currently it handles auto-indent only."""
1580 Currently it handles auto-indent only."""
1591
1581
1592 if self.rl_do_indent:
1582 if self.rl_do_indent:
1593 self.readline.insert_text(self._indent_current_str())
1583 self.readline.insert_text(self._indent_current_str())
1594 if self.rl_next_input is not None:
1584 if self.rl_next_input is not None:
1595 self.readline.insert_text(self.rl_next_input)
1585 self.readline.insert_text(self.rl_next_input)
1596 self.rl_next_input = None
1586 self.rl_next_input = None
1597
1587
1598 def _indent_current_str(self):
1588 def _indent_current_str(self):
1599 """return the current level of indentation as a string"""
1589 """return the current level of indentation as a string"""
1600 return self.input_splitter.indent_spaces * ' '
1590 return self.input_splitter.indent_spaces * ' '
1601
1591
1602 #-------------------------------------------------------------------------
1592 #-------------------------------------------------------------------------
1603 # Things related to text completion
1593 # Things related to text completion
1604 #-------------------------------------------------------------------------
1594 #-------------------------------------------------------------------------
1605
1595
1606 def init_completer(self):
1596 def init_completer(self):
1607 """Initialize the completion machinery.
1597 """Initialize the completion machinery.
1608
1598
1609 This creates completion machinery that can be used by client code,
1599 This creates completion machinery that can be used by client code,
1610 either interactively in-process (typically triggered by the readline
1600 either interactively in-process (typically triggered by the readline
1611 library), programatically (such as in test suites) or out-of-prcess
1601 library), programatically (such as in test suites) or out-of-prcess
1612 (typically over the network by remote frontends).
1602 (typically over the network by remote frontends).
1613 """
1603 """
1614 from IPython.core.completer import IPCompleter
1604 from IPython.core.completer import IPCompleter
1615 from IPython.core.completerlib import (module_completer,
1605 from IPython.core.completerlib import (module_completer,
1616 magic_run_completer, cd_completer)
1606 magic_run_completer, cd_completer)
1617
1607
1618 self.Completer = IPCompleter(self,
1608 self.Completer = IPCompleter(self,
1619 self.user_ns,
1609 self.user_ns,
1620 self.user_global_ns,
1610 self.user_global_ns,
1621 self.readline_omit__names,
1611 self.readline_omit__names,
1622 self.alias_manager.alias_table,
1612 self.alias_manager.alias_table,
1623 self.has_readline)
1613 self.has_readline)
1624
1614
1625 # Add custom completers to the basic ones built into IPCompleter
1615 # Add custom completers to the basic ones built into IPCompleter
1626 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1616 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1627 self.strdispatchers['complete_command'] = sdisp
1617 self.strdispatchers['complete_command'] = sdisp
1628 self.Completer.custom_completers = sdisp
1618 self.Completer.custom_completers = sdisp
1629
1619
1630 self.set_hook('complete_command', module_completer, str_key = 'import')
1620 self.set_hook('complete_command', module_completer, str_key = 'import')
1631 self.set_hook('complete_command', module_completer, str_key = 'from')
1621 self.set_hook('complete_command', module_completer, str_key = 'from')
1632 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1622 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1633 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1623 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1634
1624
1635 # Only configure readline if we truly are using readline. IPython can
1625 # Only configure readline if we truly are using readline. IPython can
1636 # do tab-completion over the network, in GUIs, etc, where readline
1626 # do tab-completion over the network, in GUIs, etc, where readline
1637 # itself may be absent
1627 # itself may be absent
1638 if self.has_readline:
1628 if self.has_readline:
1639 self.set_readline_completer()
1629 self.set_readline_completer()
1640
1630
1641 def complete(self, text, line=None, cursor_pos=None):
1631 def complete(self, text, line=None, cursor_pos=None):
1642 """Return the completed text and a list of completions.
1632 """Return the completed text and a list of completions.
1643
1633
1644 Parameters
1634 Parameters
1645 ----------
1635 ----------
1646
1636
1647 text : string
1637 text : string
1648 A string of text to be completed on. It can be given as empty and
1638 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
1639 instead a line/position pair are given. In this case, the
1650 completer itself will split the line like readline does.
1640 completer itself will split the line like readline does.
1651
1641
1652 line : string, optional
1642 line : string, optional
1653 The complete line that text is part of.
1643 The complete line that text is part of.
1654
1644
1655 cursor_pos : int, optional
1645 cursor_pos : int, optional
1656 The position of the cursor on the input line.
1646 The position of the cursor on the input line.
1657
1647
1658 Returns
1648 Returns
1659 -------
1649 -------
1660 text : string
1650 text : string
1661 The actual text that was completed.
1651 The actual text that was completed.
1662
1652
1663 matches : list
1653 matches : list
1664 A sorted list with all possible completions.
1654 A sorted list with all possible completions.
1665
1655
1666 The optional arguments allow the completion to take more context into
1656 The optional arguments allow the completion to take more context into
1667 account, and are part of the low-level completion API.
1657 account, and are part of the low-level completion API.
1668
1658
1669 This is a wrapper around the completion mechanism, similar to what
1659 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
1660 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
1661 exposing it as a method, it can be used by other non-readline
1672 environments (such as GUIs) for text completion.
1662 environments (such as GUIs) for text completion.
1673
1663
1674 Simple usage example:
1664 Simple usage example:
1675
1665
1676 In [1]: x = 'hello'
1666 In [1]: x = 'hello'
1677
1667
1678 In [2]: _ip.complete('x.l')
1668 In [2]: _ip.complete('x.l')
1679 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1669 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1680 """
1670 """
1681
1671
1682 # Inject names into __builtin__ so we can complete on the added names.
1672 # Inject names into __builtin__ so we can complete on the added names.
1683 with self.builtin_trap:
1673 with self.builtin_trap:
1684 return self.Completer.complete(text, line, cursor_pos)
1674 return self.Completer.complete(text, line, cursor_pos)
1685
1675
1686 def set_custom_completer(self, completer, pos=0):
1676 def set_custom_completer(self, completer, pos=0):
1687 """Adds a new custom completer function.
1677 """Adds a new custom completer function.
1688
1678
1689 The position argument (defaults to 0) is the index in the completers
1679 The position argument (defaults to 0) is the index in the completers
1690 list where you want the completer to be inserted."""
1680 list where you want the completer to be inserted."""
1691
1681
1692 newcomp = types.MethodType(completer,self.Completer)
1682 newcomp = types.MethodType(completer,self.Completer)
1693 self.Completer.matchers.insert(pos,newcomp)
1683 self.Completer.matchers.insert(pos,newcomp)
1694
1684
1695 def set_readline_completer(self):
1685 def set_readline_completer(self):
1696 """Reset readline's completer to be our own."""
1686 """Reset readline's completer to be our own."""
1697 self.readline.set_completer(self.Completer.rlcomplete)
1687 self.readline.set_completer(self.Completer.rlcomplete)
1698
1688
1699 def set_completer_frame(self, frame=None):
1689 def set_completer_frame(self, frame=None):
1700 """Set the frame of the completer."""
1690 """Set the frame of the completer."""
1701 if frame:
1691 if frame:
1702 self.Completer.namespace = frame.f_locals
1692 self.Completer.namespace = frame.f_locals
1703 self.Completer.global_namespace = frame.f_globals
1693 self.Completer.global_namespace = frame.f_globals
1704 else:
1694 else:
1705 self.Completer.namespace = self.user_ns
1695 self.Completer.namespace = self.user_ns
1706 self.Completer.global_namespace = self.user_global_ns
1696 self.Completer.global_namespace = self.user_global_ns
1707
1697
1708 #-------------------------------------------------------------------------
1698 #-------------------------------------------------------------------------
1709 # Things related to magics
1699 # Things related to magics
1710 #-------------------------------------------------------------------------
1700 #-------------------------------------------------------------------------
1711
1701
1712 def init_magics(self):
1702 def init_magics(self):
1713 # FIXME: Move the color initialization to the DisplayHook, which
1703 # FIXME: Move the color initialization to the DisplayHook, which
1714 # should be split into a prompt manager and displayhook. We probably
1704 # should be split into a prompt manager and displayhook. We probably
1715 # even need a centralize colors management object.
1705 # even need a centralize colors management object.
1716 self.magic_colors(self.colors)
1706 self.magic_colors(self.colors)
1717 # History was moved to a separate module
1707 # History was moved to a separate module
1718 from . import history
1708 from . import history
1719 history.init_ipython(self)
1709 history.init_ipython(self)
1720
1710
1721 def magic(self,arg_s):
1711 def magic(self,arg_s):
1722 """Call a magic function by name.
1712 """Call a magic function by name.
1723
1713
1724 Input: a string containing the name of the magic function to call and
1714 Input: a string containing the name of the magic function to call and
1725 any additional arguments to be passed to the magic.
1715 any additional arguments to be passed to the magic.
1726
1716
1727 magic('name -opt foo bar') is equivalent to typing at the ipython
1717 magic('name -opt foo bar') is equivalent to typing at the ipython
1728 prompt:
1718 prompt:
1729
1719
1730 In[1]: %name -opt foo bar
1720 In[1]: %name -opt foo bar
1731
1721
1732 To call a magic without arguments, simply use magic('name').
1722 To call a magic without arguments, simply use magic('name').
1733
1723
1734 This provides a proper Python function to call IPython's magics in any
1724 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
1725 valid Python code you can type at the interpreter, including loops and
1736 compound statements.
1726 compound statements.
1737 """
1727 """
1738 args = arg_s.split(' ',1)
1728 args = arg_s.split(' ',1)
1739 magic_name = args[0]
1729 magic_name = args[0]
1740 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1730 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1741
1731
1742 try:
1732 try:
1743 magic_args = args[1]
1733 magic_args = args[1]
1744 except IndexError:
1734 except IndexError:
1745 magic_args = ''
1735 magic_args = ''
1746 fn = getattr(self,'magic_'+magic_name,None)
1736 fn = getattr(self,'magic_'+magic_name,None)
1747 if fn is None:
1737 if fn is None:
1748 error("Magic function `%s` not found." % magic_name)
1738 error("Magic function `%s` not found." % magic_name)
1749 else:
1739 else:
1750 magic_args = self.var_expand(magic_args,1)
1740 magic_args = self.var_expand(magic_args,1)
1751 with nested(self.builtin_trap,):
1741 with nested(self.builtin_trap,):
1752 result = fn(magic_args)
1742 result = fn(magic_args)
1753 return result
1743 return result
1754
1744
1755 def define_magic(self, magicname, func):
1745 def define_magic(self, magicname, func):
1756 """Expose own function as magic function for ipython
1746 """Expose own function as magic function for ipython
1757
1747
1758 def foo_impl(self,parameter_s=''):
1748 def foo_impl(self,parameter_s=''):
1759 'My very own magic!. (Use docstrings, IPython reads them).'
1749 'My very own magic!. (Use docstrings, IPython reads them).'
1760 print 'Magic function. Passed parameter is between < >:'
1750 print 'Magic function. Passed parameter is between < >:'
1761 print '<%s>' % parameter_s
1751 print '<%s>' % parameter_s
1762 print 'The self object is:',self
1752 print 'The self object is:',self
1763
1753
1764 self.define_magic('foo',foo_impl)
1754 self.define_magic('foo',foo_impl)
1765 """
1755 """
1766
1756
1767 import new
1757 import new
1768 im = types.MethodType(func,self)
1758 im = types.MethodType(func,self)
1769 old = getattr(self, "magic_" + magicname, None)
1759 old = getattr(self, "magic_" + magicname, None)
1770 setattr(self, "magic_" + magicname, im)
1760 setattr(self, "magic_" + magicname, im)
1771 return old
1761 return old
1772
1762
1773 #-------------------------------------------------------------------------
1763 #-------------------------------------------------------------------------
1774 # Things related to macros
1764 # Things related to macros
1775 #-------------------------------------------------------------------------
1765 #-------------------------------------------------------------------------
1776
1766
1777 def define_macro(self, name, themacro):
1767 def define_macro(self, name, themacro):
1778 """Define a new macro
1768 """Define a new macro
1779
1769
1780 Parameters
1770 Parameters
1781 ----------
1771 ----------
1782 name : str
1772 name : str
1783 The name of the macro.
1773 The name of the macro.
1784 themacro : str or Macro
1774 themacro : str or Macro
1785 The action to do upon invoking the macro. If a string, a new
1775 The action to do upon invoking the macro. If a string, a new
1786 Macro object is created by passing the string to it.
1776 Macro object is created by passing the string to it.
1787 """
1777 """
1788
1778
1789 from IPython.core import macro
1779 from IPython.core import macro
1790
1780
1791 if isinstance(themacro, basestring):
1781 if isinstance(themacro, basestring):
1792 themacro = macro.Macro(themacro)
1782 themacro = macro.Macro(themacro)
1793 if not isinstance(themacro, macro.Macro):
1783 if not isinstance(themacro, macro.Macro):
1794 raise ValueError('A macro must be a string or a Macro instance.')
1784 raise ValueError('A macro must be a string or a Macro instance.')
1795 self.user_ns[name] = themacro
1785 self.user_ns[name] = themacro
1796
1786
1797 #-------------------------------------------------------------------------
1787 #-------------------------------------------------------------------------
1798 # Things related to the running of system commands
1788 # Things related to the running of system commands
1799 #-------------------------------------------------------------------------
1789 #-------------------------------------------------------------------------
1800
1790
1801 def system(self, cmd):
1791 def system(self, cmd):
1802 """Call the given cmd in a subprocess.
1792 """Call the given cmd in a subprocess.
1803
1793
1804 Parameters
1794 Parameters
1805 ----------
1795 ----------
1806 cmd : str
1796 cmd : str
1807 Command to execute (can not end in '&', as bacground processes are
1797 Command to execute (can not end in '&', as bacground processes are
1808 not supported.
1798 not supported.
1809 """
1799 """
1810 # We do not support backgrounding processes because we either use
1800 # We do not support backgrounding processes because we either use
1811 # pexpect or pipes to read from. Users can always just call
1801 # pexpect or pipes to read from. Users can always just call
1812 # os.system() if they really want a background process.
1802 # os.system() if they really want a background process.
1813 if cmd.endswith('&'):
1803 if cmd.endswith('&'):
1814 raise OSError("Background processes not supported.")
1804 raise OSError("Background processes not supported.")
1815
1805
1816 return system(self.var_expand(cmd, depth=2))
1806 return system(self.var_expand(cmd, depth=2))
1817
1807
1818 def getoutput(self, cmd, split=True):
1808 def getoutput(self, cmd, split=True):
1819 """Get output (possibly including stderr) from a subprocess.
1809 """Get output (possibly including stderr) from a subprocess.
1820
1810
1821 Parameters
1811 Parameters
1822 ----------
1812 ----------
1823 cmd : str
1813 cmd : str
1824 Command to execute (can not end in '&', as background processes are
1814 Command to execute (can not end in '&', as background processes are
1825 not supported.
1815 not supported.
1826 split : bool, optional
1816 split : bool, optional
1827
1817
1828 If True, split the output into an IPython SList. Otherwise, an
1818 If True, split the output into an IPython SList. Otherwise, an
1829 IPython LSString is returned. These are objects similar to normal
1819 IPython LSString is returned. These are objects similar to normal
1830 lists and strings, with a few convenience attributes for easier
1820 lists and strings, with a few convenience attributes for easier
1831 manipulation of line-based output. You can use '?' on them for
1821 manipulation of line-based output. You can use '?' on them for
1832 details.
1822 details.
1833 """
1823 """
1834 if cmd.endswith('&'):
1824 if cmd.endswith('&'):
1835 raise OSError("Background processes not supported.")
1825 raise OSError("Background processes not supported.")
1836 out = getoutput(self.var_expand(cmd, depth=2))
1826 out = getoutput(self.var_expand(cmd, depth=2))
1837 if split:
1827 if split:
1838 out = SList(out.splitlines())
1828 out = SList(out.splitlines())
1839 else:
1829 else:
1840 out = LSString(out)
1830 out = LSString(out)
1841 return out
1831 return out
1842
1832
1843 #-------------------------------------------------------------------------
1833 #-------------------------------------------------------------------------
1844 # Things related to aliases
1834 # Things related to aliases
1845 #-------------------------------------------------------------------------
1835 #-------------------------------------------------------------------------
1846
1836
1847 def init_alias(self):
1837 def init_alias(self):
1848 self.alias_manager = AliasManager(shell=self, config=self.config)
1838 self.alias_manager = AliasManager(shell=self, config=self.config)
1849 self.ns_table['alias'] = self.alias_manager.alias_table,
1839 self.ns_table['alias'] = self.alias_manager.alias_table,
1850
1840
1851 #-------------------------------------------------------------------------
1841 #-------------------------------------------------------------------------
1852 # Things related to extensions and plugins
1842 # Things related to extensions and plugins
1853 #-------------------------------------------------------------------------
1843 #-------------------------------------------------------------------------
1854
1844
1855 def init_extension_manager(self):
1845 def init_extension_manager(self):
1856 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1846 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1857
1847
1858 def init_plugin_manager(self):
1848 def init_plugin_manager(self):
1859 self.plugin_manager = PluginManager(config=self.config)
1849 self.plugin_manager = PluginManager(config=self.config)
1860
1850
1861 #-------------------------------------------------------------------------
1851 #-------------------------------------------------------------------------
1862 # Things related to payloads
1852 # Things related to payloads
1863 #-------------------------------------------------------------------------
1853 #-------------------------------------------------------------------------
1864
1854
1865 def init_payload(self):
1855 def init_payload(self):
1866 self.payload_manager = PayloadManager(config=self.config)
1856 self.payload_manager = PayloadManager(config=self.config)
1867
1857
1868 #-------------------------------------------------------------------------
1858 #-------------------------------------------------------------------------
1869 # Things related to the prefilter
1859 # Things related to the prefilter
1870 #-------------------------------------------------------------------------
1860 #-------------------------------------------------------------------------
1871
1861
1872 def init_prefilter(self):
1862 def init_prefilter(self):
1873 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1863 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1874 # Ultimately this will be refactored in the new interpreter code, but
1864 # Ultimately this will be refactored in the new interpreter code, but
1875 # for now, we should expose the main prefilter method (there's legacy
1865 # for now, we should expose the main prefilter method (there's legacy
1876 # code out there that may rely on this).
1866 # code out there that may rely on this).
1877 self.prefilter = self.prefilter_manager.prefilter_lines
1867 self.prefilter = self.prefilter_manager.prefilter_lines
1878
1868
1879 def auto_rewrite_input(self, cmd):
1869 def auto_rewrite_input(self, cmd):
1880 """Print to the screen the rewritten form of the user's command.
1870 """Print to the screen the rewritten form of the user's command.
1881
1871
1882 This shows visual feedback by rewriting input lines that cause
1872 This shows visual feedback by rewriting input lines that cause
1883 automatic calling to kick in, like::
1873 automatic calling to kick in, like::
1884
1874
1885 /f x
1875 /f x
1886
1876
1887 into::
1877 into::
1888
1878
1889 ------> f(x)
1879 ------> f(x)
1890
1880
1891 after the user's input prompt. This helps the user understand that the
1881 after the user's input prompt. This helps the user understand that the
1892 input line was transformed automatically by IPython.
1882 input line was transformed automatically by IPython.
1893 """
1883 """
1894 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1884 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1895
1885
1896 try:
1886 try:
1897 # plain ascii works better w/ pyreadline, on some machines, so
1887 # plain ascii works better w/ pyreadline, on some machines, so
1898 # we use it and only print uncolored rewrite if we have unicode
1888 # we use it and only print uncolored rewrite if we have unicode
1899 rw = str(rw)
1889 rw = str(rw)
1900 print >> IPython.utils.io.Term.cout, rw
1890 print >> IPython.utils.io.Term.cout, rw
1901 except UnicodeEncodeError:
1891 except UnicodeEncodeError:
1902 print "------> " + cmd
1892 print "------> " + cmd
1903
1893
1904 #-------------------------------------------------------------------------
1894 #-------------------------------------------------------------------------
1905 # Things related to extracting values/expressions from kernel and user_ns
1895 # Things related to extracting values/expressions from kernel and user_ns
1906 #-------------------------------------------------------------------------
1896 #-------------------------------------------------------------------------
1907
1897
1908 def _simple_error(self):
1898 def _simple_error(self):
1909 etype, value = sys.exc_info()[:2]
1899 etype, value = sys.exc_info()[:2]
1910 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1900 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1911
1901
1912 def user_variables(self, names):
1902 def user_variables(self, names):
1913 """Get a list of variable names from the user's namespace.
1903 """Get a list of variable names from the user's namespace.
1914
1904
1915 Parameters
1905 Parameters
1916 ----------
1906 ----------
1917 names : list of strings
1907 names : list of strings
1918 A list of names of variables to be read from the user namespace.
1908 A list of names of variables to be read from the user namespace.
1919
1909
1920 Returns
1910 Returns
1921 -------
1911 -------
1922 A dict, keyed by the input names and with the repr() of each value.
1912 A dict, keyed by the input names and with the repr() of each value.
1923 """
1913 """
1924 out = {}
1914 out = {}
1925 user_ns = self.user_ns
1915 user_ns = self.user_ns
1926 for varname in names:
1916 for varname in names:
1927 try:
1917 try:
1928 value = repr(user_ns[varname])
1918 value = repr(user_ns[varname])
1929 except:
1919 except:
1930 value = self._simple_error()
1920 value = self._simple_error()
1931 out[varname] = value
1921 out[varname] = value
1932 return out
1922 return out
1933
1923
1934 def user_expressions(self, expressions):
1924 def user_expressions(self, expressions):
1935 """Evaluate a dict of expressions in the user's namespace.
1925 """Evaluate a dict of expressions in the user's namespace.
1936
1926
1937 Parameters
1927 Parameters
1938 ----------
1928 ----------
1939 expressions : dict
1929 expressions : dict
1940 A dict with string keys and string values. The expression values
1930 A dict with string keys and string values. The expression values
1941 should be valid Python expressions, each of which will be evaluated
1931 should be valid Python expressions, each of which will be evaluated
1942 in the user namespace.
1932 in the user namespace.
1943
1933
1944 Returns
1934 Returns
1945 -------
1935 -------
1946 A dict, keyed like the input expressions dict, with the repr() of each
1936 A dict, keyed like the input expressions dict, with the repr() of each
1947 value.
1937 value.
1948 """
1938 """
1949 out = {}
1939 out = {}
1950 user_ns = self.user_ns
1940 user_ns = self.user_ns
1951 global_ns = self.user_global_ns
1941 global_ns = self.user_global_ns
1952 for key, expr in expressions.iteritems():
1942 for key, expr in expressions.iteritems():
1953 try:
1943 try:
1954 value = repr(eval(expr, global_ns, user_ns))
1944 value = repr(eval(expr, global_ns, user_ns))
1955 except:
1945 except:
1956 value = self._simple_error()
1946 value = self._simple_error()
1957 out[key] = value
1947 out[key] = value
1958 return out
1948 return out
1959
1949
1960 #-------------------------------------------------------------------------
1950 #-------------------------------------------------------------------------
1961 # Things related to the running of code
1951 # Things related to the running of code
1962 #-------------------------------------------------------------------------
1952 #-------------------------------------------------------------------------
1963
1953
1964 def ex(self, cmd):
1954 def ex(self, cmd):
1965 """Execute a normal python statement in user namespace."""
1955 """Execute a normal python statement in user namespace."""
1966 with nested(self.builtin_trap,):
1956 with nested(self.builtin_trap,):
1967 exec cmd in self.user_global_ns, self.user_ns
1957 exec cmd in self.user_global_ns, self.user_ns
1968
1958
1969 def ev(self, expr):
1959 def ev(self, expr):
1970 """Evaluate python expression expr in user namespace.
1960 """Evaluate python expression expr in user namespace.
1971
1961
1972 Returns the result of evaluation
1962 Returns the result of evaluation
1973 """
1963 """
1974 with nested(self.builtin_trap,):
1964 with nested(self.builtin_trap,):
1975 return eval(expr, self.user_global_ns, self.user_ns)
1965 return eval(expr, self.user_global_ns, self.user_ns)
1976
1966
1977 def safe_execfile(self, fname, *where, **kw):
1967 def safe_execfile(self, fname, *where, **kw):
1978 """A safe version of the builtin execfile().
1968 """A safe version of the builtin execfile().
1979
1969
1980 This version will never throw an exception, but instead print
1970 This version will never throw an exception, but instead print
1981 helpful error messages to the screen. This only works on pure
1971 helpful error messages to the screen. This only works on pure
1982 Python files with the .py extension.
1972 Python files with the .py extension.
1983
1973
1984 Parameters
1974 Parameters
1985 ----------
1975 ----------
1986 fname : string
1976 fname : string
1987 The name of the file to be executed.
1977 The name of the file to be executed.
1988 where : tuple
1978 where : tuple
1989 One or two namespaces, passed to execfile() as (globals,locals).
1979 One or two namespaces, passed to execfile() as (globals,locals).
1990 If only one is given, it is passed as both.
1980 If only one is given, it is passed as both.
1991 exit_ignore : bool (False)
1981 exit_ignore : bool (False)
1992 If True, then silence SystemExit for non-zero status (it is always
1982 If True, then silence SystemExit for non-zero status (it is always
1993 silenced for zero status, as it is so common).
1983 silenced for zero status, as it is so common).
1994 """
1984 """
1995 kw.setdefault('exit_ignore', False)
1985 kw.setdefault('exit_ignore', False)
1996
1986
1997 fname = os.path.abspath(os.path.expanduser(fname))
1987 fname = os.path.abspath(os.path.expanduser(fname))
1998
1988
1999 # Make sure we have a .py file
1989 # Make sure we have a .py file
2000 if not fname.endswith('.py'):
1990 if not fname.endswith('.py'):
2001 warn('File must end with .py to be run using execfile: <%s>' % fname)
1991 warn('File must end with .py to be run using execfile: <%s>' % fname)
2002
1992
2003 # Make sure we can open the file
1993 # Make sure we can open the file
2004 try:
1994 try:
2005 with open(fname) as thefile:
1995 with open(fname) as thefile:
2006 pass
1996 pass
2007 except:
1997 except:
2008 warn('Could not open file <%s> for safe execution.' % fname)
1998 warn('Could not open file <%s> for safe execution.' % fname)
2009 return
1999 return
2010
2000
2011 # Find things also in current directory. This is needed to mimic the
2001 # Find things also in current directory. This is needed to mimic the
2012 # behavior of running a script from the system command line, where
2002 # behavior of running a script from the system command line, where
2013 # Python inserts the script's directory into sys.path
2003 # Python inserts the script's directory into sys.path
2014 dname = os.path.dirname(fname)
2004 dname = os.path.dirname(fname)
2015
2005
2016 with prepended_to_syspath(dname):
2006 with prepended_to_syspath(dname):
2017 try:
2007 try:
2018 execfile(fname,*where)
2008 execfile(fname,*where)
2019 except SystemExit, status:
2009 except SystemExit, status:
2020 # If the call was made with 0 or None exit status (sys.exit(0)
2010 # 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
2011 # or sys.exit() ), don't bother showing a traceback, as both of
2022 # these are considered normal by the OS:
2012 # these are considered normal by the OS:
2023 # > python -c'import sys;sys.exit(0)'; echo $?
2013 # > python -c'import sys;sys.exit(0)'; echo $?
2024 # 0
2014 # 0
2025 # > python -c'import sys;sys.exit()'; echo $?
2015 # > python -c'import sys;sys.exit()'; echo $?
2026 # 0
2016 # 0
2027 # For other exit status, we show the exception unless
2017 # For other exit status, we show the exception unless
2028 # explicitly silenced, but only in short form.
2018 # explicitly silenced, but only in short form.
2029 if status.code not in (0, None) and not kw['exit_ignore']:
2019 if status.code not in (0, None) and not kw['exit_ignore']:
2030 self.showtraceback(exception_only=True)
2020 self.showtraceback(exception_only=True)
2031 except:
2021 except:
2032 self.showtraceback()
2022 self.showtraceback()
2033
2023
2034 def safe_execfile_ipy(self, fname):
2024 def safe_execfile_ipy(self, fname):
2035 """Like safe_execfile, but for .ipy files with IPython syntax.
2025 """Like safe_execfile, but for .ipy files with IPython syntax.
2036
2026
2037 Parameters
2027 Parameters
2038 ----------
2028 ----------
2039 fname : str
2029 fname : str
2040 The name of the file to execute. The filename must have a
2030 The name of the file to execute. The filename must have a
2041 .ipy extension.
2031 .ipy extension.
2042 """
2032 """
2043 fname = os.path.abspath(os.path.expanduser(fname))
2033 fname = os.path.abspath(os.path.expanduser(fname))
2044
2034
2045 # Make sure we have a .py file
2035 # Make sure we have a .py file
2046 if not fname.endswith('.ipy'):
2036 if not fname.endswith('.ipy'):
2047 warn('File must end with .py to be run using execfile: <%s>' % fname)
2037 warn('File must end with .py to be run using execfile: <%s>' % fname)
2048
2038
2049 # Make sure we can open the file
2039 # Make sure we can open the file
2050 try:
2040 try:
2051 with open(fname) as thefile:
2041 with open(fname) as thefile:
2052 pass
2042 pass
2053 except:
2043 except:
2054 warn('Could not open file <%s> for safe execution.' % fname)
2044 warn('Could not open file <%s> for safe execution.' % fname)
2055 return
2045 return
2056
2046
2057 # Find things also in current directory. This is needed to mimic the
2047 # Find things also in current directory. This is needed to mimic the
2058 # behavior of running a script from the system command line, where
2048 # behavior of running a script from the system command line, where
2059 # Python inserts the script's directory into sys.path
2049 # Python inserts the script's directory into sys.path
2060 dname = os.path.dirname(fname)
2050 dname = os.path.dirname(fname)
2061
2051
2062 with prepended_to_syspath(dname):
2052 with prepended_to_syspath(dname):
2063 try:
2053 try:
2064 with open(fname) as thefile:
2054 with open(fname) as thefile:
2065 # self.run_cell currently captures all exceptions
2055 # self.run_cell currently captures all exceptions
2066 # raised in user code. It would be nice if there were
2056 # raised in user code. It would be nice if there were
2067 # versions of runlines, execfile that did raise, so
2057 # versions of runlines, execfile that did raise, so
2068 # we could catch the errors.
2058 # we could catch the errors.
2069 self.run_cell(thefile.read())
2059 self.run_cell(thefile.read())
2070 except:
2060 except:
2071 self.showtraceback()
2061 self.showtraceback()
2072 warn('Unknown failure executing file: <%s>' % fname)
2062 warn('Unknown failure executing file: <%s>' % fname)
2073
2063
2074 def run_cell(self, cell):
2064 def run_cell(self, cell, store_history=True):
2075 """Run the contents of an entire multiline 'cell' of code.
2065 """Run the contents of an entire multiline 'cell' of code, and store it
2066 in the history.
2076
2067
2077 The cell is split into separate blocks which can be executed
2068 The cell is split into separate blocks which can be executed
2078 individually. Then, based on how many blocks there are, they are
2069 individually. Then, based on how many blocks there are, they are
2079 executed as follows:
2070 executed as follows:
2080
2071
2081 - A single block: 'single' mode.
2072 - A single block: 'single' mode. If it is also a single line, dynamic
2073 transformations, including automagic and macros, will be applied.
2082
2074
2083 If there's more than one block, it depends:
2075 If there's more than one block, it depends:
2084
2076
2085 - if the last one is no more than two lines long, run all but the last
2077 - 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
2078 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. -
2079 easy to type simple expressions at the end to see computed values. -
2088 otherwise (last one is also multiline), run all in 'exec' mode
2080 otherwise (last one is also multiline), run all in 'exec' mode
2089
2081
2090 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2082 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2091 results are displayed and output prompts are computed. In 'exec' mode,
2083 results are displayed and output prompts are computed. In 'exec' mode,
2092 no results are displayed unless :func:`print` is called explicitly;
2084 no results are displayed unless :func:`print` is called explicitly;
2093 this mode is more akin to running a script.
2085 this mode is more akin to running a script.
2094
2086
2095 Parameters
2087 Parameters
2096 ----------
2088 ----------
2097 cell : str
2089 cell : str
2098 A single or multiline string.
2090 A single or multiline string.
2099 """
2091 """
2092 # Store the untransformed code
2093 raw_cell = cell
2094
2095 # We only do dynamic transforms on a single line. We need to do this
2096 # first, because a macro can be expanded to several lines, which then
2097 # need to be split into blocks again.
2098 if len(cell.splitlines()) <= 1:
2099 temp = self.input_splitter.split_blocks(cell)
2100 cell = self.prefilter_manager.prefilter_line(temp[0])
2100
2101
2101 # We need to break up the input into executable blocks that can be run
2102 # We need to break up the input into executable blocks that can be run
2102 # in 'single' mode, to provide comfortable user behavior.
2103 # in 'single' mode, to provide comfortable user behavior.
2103 blocks = self.input_splitter.split_blocks(cell)
2104 blocks = self.input_splitter.split_blocks(cell)
2104
2105
2105 if not blocks:
2106 if not blocks:
2106 return
2107 return
2107
2108
2108 # Store the 'ipython' version of the cell as well, since that's what
2109 # 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
2110 # needs to go into the translated history and get executed (the
2110 # original cell may contain non-python syntax).
2111 # original cell may contain non-python syntax).
2111 ipy_cell = ''.join(blocks)
2112 cell = ''.join(blocks)
2112
2113
2113 # Store raw and processed history
2114 # Store raw and processed history
2114 self.history_manager.store_inputs(ipy_cell, cell)
2115 if store_history:
2116 self.history_manager.store_inputs(self.execution_count,
2117 cell, raw_cell)
2115
2118
2116 self.logger.log(ipy_cell, cell)
2119 self.logger.log(cell, raw_cell)
2117
2120
2118 # All user code execution must happen with our context managers active
2121 # All user code execution must happen with our context managers active
2119 with nested(self.builtin_trap, self.display_trap):
2122 with nested(self.builtin_trap, self.display_trap):
2120
2123
2121 # Single-block input should behave like an interactive prompt
2124 # Single-block input should behave like an interactive prompt
2122 if len(blocks) == 1:
2125 if len(blocks) == 1:
2123 # since we return here, we need to update the execution count
2126 out = self.run_source(blocks[0])
2124 out = self.run_one_block(blocks[0])
2127 # Write output to the database. Does nothing unless
2125 self.execution_count += 1
2128 # history output logging is enabled.
2129 if store_history:
2130 self.history_manager.store_output(self.execution_count)
2131 # since we return here, we need to update the execution count
2132 self.execution_count += 1
2126 return out
2133 return out
2127
2134
2128 # In multi-block input, if the last block is a simple (one-two
2135 # In multi-block input, if the last block is a simple (one-two
2129 # lines) expression, run it in single mode so it produces output.
2136 # lines) expression, run it in single mode so it produces output.
2130 # Otherwise just feed the whole thing to run_code. This seems like
2137 # Otherwise just run it all in 'exec' mode. This seems like a
2131 # a reasonable usability design.
2138 # reasonable usability design.
2132 last = blocks[-1]
2139 last = blocks[-1]
2133 last_nlines = len(last.splitlines())
2140 last_nlines = len(last.splitlines())
2134
2141
2135 # Note: below, whenever we call run_code, we must sync history
2136 # ourselves, because run_code is NOT meant to manage history at all.
2137 if last_nlines < 2:
2142 if last_nlines < 2:
2138 # Here we consider the cell split between 'body' and 'last',
2143 # Here we consider the cell split between 'body' and 'last',
2139 # store all history and execute 'body', and if successful, then
2144 # store all history and execute 'body', and if successful, then
2140 # proceed to execute 'last'.
2145 # proceed to execute 'last'.
2141
2146
2142 # Get the main body to run as a cell
2147 # Get the main body to run as a cell
2143 ipy_body = ''.join(blocks[:-1])
2148 ipy_body = ''.join(blocks[:-1])
2144 retcode = self.run_source(ipy_body, symbol='exec',
2149 retcode = self.run_source(ipy_body, symbol='exec',
2145 post_execute=False)
2150 post_execute=False)
2146 if retcode==0:
2151 if retcode==0:
2147 # And the last expression via runlines so it produces output
2152 # Last expression compiled as 'single' so it produces output
2148 self.run_one_block(last)
2153 self.run_source(last)
2149 else:
2154 else:
2150 # Run the whole cell as one entity, storing both raw and
2155 # Run the whole cell as one entity, storing both raw and
2151 # processed input in history
2156 # processed input in history
2152 self.run_source(ipy_cell, symbol='exec')
2157 self.run_source(ipy_cell, symbol='exec')
2153
2158
2154 # Each cell is a *single* input, regardless of how many lines it has
2159 # Write output to the database. Does nothing unless
2155 self.execution_count += 1
2160 # history output logging is enabled.
2156
2161 if store_history:
2157 def run_one_block(self, block):
2162 self.history_manager.store_output(self.execution_count)
2158 """Run a single interactive block of source code.
2163 # Each cell is a *single* input, regardless of how many lines it has
2159
2164 self.execution_count += 1
2160 If the block is single-line, dynamic transformations are applied to it
2161 (like automagics, autocall and alias recognition).
2162
2163 If the block is multi-line, it must consist of valid Python code only.
2164
2165 Parameters
2166 ----------
2167 block : string
2168 A (possibly multiline) string of code to be executed.
2169
2170 Returns
2171 -------
2172 The output of the underlying execution method used, be it
2173 :meth:`run_source` or :meth:`run_single_line`.
2174 """
2175 if len(block.splitlines()) <= 1:
2176 out = self.run_single_line(block)
2177 else:
2178 # Call run_source, which correctly compiles the input cell.
2179 # run_code must only be called when we know we have a code object,
2180 # as it does a naked exec and the compilation mode may not be what
2181 # we wanted.
2182 out = self.run_source(block)
2183 return out
2184
2185 def run_single_line(self, line):
2186 """Run a single-line interactive statement.
2187
2188 This assumes the input has been transformed to IPython syntax by
2189 applying all static transformations (those with an explicit prefix like
2190 % or !), but it will further try to apply the dynamic ones.
2191
2192 It does not update history.
2193 """
2194 tline = self.prefilter_manager.prefilter_line(line)
2195 return self.run_source(tline)
2196
2165
2197 # PENDING REMOVAL: this method is slated for deletion, once our new
2166 # PENDING REMOVAL: this method is slated for deletion, once our new
2198 # input logic has been 100% moved to frontends and is stable.
2167 # input logic has been 100% moved to frontends and is stable.
2199 def runlines(self, lines, clean=False):
2168 def runlines(self, lines, clean=False):
2200 """Run a string of one or more lines of source.
2169 """Run a string of one or more lines of source.
2201
2170
2202 This method is capable of running a string containing multiple source
2171 This method is capable of running a string containing multiple source
2203 lines, as if they had been entered at the IPython prompt. Since it
2172 lines, as if they had been entered at the IPython prompt. Since it
2204 exposes IPython's processing machinery, the given strings can contain
2173 exposes IPython's processing machinery, the given strings can contain
2205 magic calls (%magic), special shell access (!cmd), etc.
2174 magic calls (%magic), special shell access (!cmd), etc.
2206 """
2175 """
2207
2176
2208 if isinstance(lines, (list, tuple)):
2177 if not isinstance(lines, (list, tuple)):
2209 lines = '\n'.join(lines)
2178 lines = lines.splitlines()
2210
2179
2211 if clean:
2180 if clean:
2212 lines = self._cleanup_ipy_script(lines)
2181 lines = self._cleanup_ipy_script(lines)
2213
2182
2214 # We must start with a clean buffer, in case this is run from an
2183 # We must start with a clean buffer, in case this is run from an
2215 # interactive IPython session (via a magic, for example).
2184 # interactive IPython session (via a magic, for example).
2216 self.reset_buffer()
2185 self.reset_buffer()
2217 lines = lines.splitlines()
2218
2186
2219 # Since we will prefilter all lines, store the user's raw input too
2187 # Since we will prefilter all lines, store the user's raw input too
2220 # before we apply any transformations
2188 # before we apply any transformations
2221 self.buffer_raw[:] = [ l+'\n' for l in lines]
2189 self.buffer_raw[:] = [ l+'\n' for l in lines]
2222
2190
2223 more = False
2191 more = False
2224 prefilter_lines = self.prefilter_manager.prefilter_lines
2192 prefilter_lines = self.prefilter_manager.prefilter_lines
2225 with nested(self.builtin_trap, self.display_trap):
2193 with nested(self.builtin_trap, self.display_trap):
2226 for line in lines:
2194 for line in lines:
2227 # skip blank lines so we don't mess up the prompt counter, but
2195 # skip blank lines so we don't mess up the prompt counter, but
2228 # do NOT skip even a blank line if we are in a code block (more
2196 # do NOT skip even a blank line if we are in a code block (more
2229 # is true)
2197 # is true)
2230
2198
2231 if line or more:
2199 if line or more:
2232 more = self.push_line(prefilter_lines(line, more))
2200 more = self.push_line(prefilter_lines(line, more))
2233 # IPython's run_source returns None if there was an error
2201 # IPython's run_source returns None if there was an error
2234 # compiling the code. This allows us to stop processing
2202 # compiling the code. This allows us to stop processing
2235 # right away, so the user gets the error message at the
2203 # right away, so the user gets the error message at the
2236 # right place.
2204 # right place.
2237 if more is None:
2205 if more is None:
2238 break
2206 break
2239 # final newline in case the input didn't have it, so that the code
2207 # final newline in case the input didn't have it, so that the code
2240 # actually does get executed
2208 # actually does get executed
2241 if more:
2209 if more:
2242 self.push_line('\n')
2210 self.push_line('\n')
2243
2211
2244 def run_source(self, source, filename=None,
2212 def run_source(self, source, filename=None,
2245 symbol='single', post_execute=True):
2213 symbol='single', post_execute=True):
2246 """Compile and run some source in the interpreter.
2214 """Compile and run some source in the interpreter.
2247
2215
2248 Arguments are as for compile_command().
2216 Arguments are as for compile_command().
2249
2217
2250 One several things can happen:
2218 One several things can happen:
2251
2219
2252 1) The input is incorrect; compile_command() raised an
2220 1) The input is incorrect; compile_command() raised an
2253 exception (SyntaxError or OverflowError). A syntax traceback
2221 exception (SyntaxError or OverflowError). A syntax traceback
2254 will be printed by calling the showsyntaxerror() method.
2222 will be printed by calling the showsyntaxerror() method.
2255
2223
2256 2) The input is incomplete, and more input is required;
2224 2) The input is incomplete, and more input is required;
2257 compile_command() returned None. Nothing happens.
2225 compile_command() returned None. Nothing happens.
2258
2226
2259 3) The input is complete; compile_command() returned a code
2227 3) The input is complete; compile_command() returned a code
2260 object. The code is executed by calling self.run_code() (which
2228 object. The code is executed by calling self.run_code() (which
2261 also handles run-time exceptions, except for SystemExit).
2229 also handles run-time exceptions, except for SystemExit).
2262
2230
2263 The return value is:
2231 The return value is:
2264
2232
2265 - True in case 2
2233 - True in case 2
2266
2234
2267 - False in the other cases, unless an exception is raised, where
2235 - False in the other cases, unless an exception is raised, where
2268 None is returned instead. This can be used by external callers to
2236 None is returned instead. This can be used by external callers to
2269 know whether to continue feeding input or not.
2237 know whether to continue feeding input or not.
2270
2238
2271 The return value can be used to decide whether to use sys.ps1 or
2239 The return value can be used to decide whether to use sys.ps1 or
2272 sys.ps2 to prompt the next line."""
2240 sys.ps2 to prompt the next line."""
2273
2241
2274 # We need to ensure that the source is unicode from here on.
2242 # We need to ensure that the source is unicode from here on.
2275 if type(source)==str:
2243 if type(source)==str:
2276 usource = source.decode(self.stdin_encoding)
2244 usource = source.decode(self.stdin_encoding)
2277 else:
2245 else:
2278 usource = source
2246 usource = source
2279
2247
2280 if 0: # dbg
2248 if 0: # dbg
2281 print 'Source:', repr(source) # dbg
2249 print 'Source:', repr(source) # dbg
2282 print 'USource:', repr(usource) # dbg
2250 print 'USource:', repr(usource) # dbg
2283 print 'type:', type(source) # dbg
2251 print 'type:', type(source) # dbg
2284 print 'encoding', self.stdin_encoding # dbg
2252 print 'encoding', self.stdin_encoding # dbg
2285
2253
2286 try:
2254 try:
2287 code = self.compile(usource, symbol, self.execution_count)
2255 code = self.compile(usource, symbol, self.execution_count)
2288 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2256 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2289 # Case 1
2257 # Case 1
2290 self.showsyntaxerror(filename)
2258 self.showsyntaxerror(filename)
2291 return None
2259 return None
2292
2260
2293 if code is None:
2261 if code is None:
2294 # Case 2
2262 # Case 2
2295 return True
2263 return True
2296
2264
2297 # Case 3
2265 # Case 3
2298 # We store the code object so that threaded shells and
2266 # We store the code object so that threaded shells and
2299 # custom exception handlers can access all this info if needed.
2267 # custom exception handlers can access all this info if needed.
2300 # The source corresponding to this can be obtained from the
2268 # The source corresponding to this can be obtained from the
2301 # buffer attribute as '\n'.join(self.buffer).
2269 # buffer attribute as '\n'.join(self.buffer).
2302 self.code_to_run = code
2270 self.code_to_run = code
2303 # now actually execute the code object
2271 # now actually execute the code object
2304 if self.run_code(code, post_execute) == 0:
2272 if self.run_code(code, post_execute) == 0:
2305 return False
2273 return False
2306 else:
2274 else:
2307 return None
2275 return None
2308
2276
2309 # For backwards compatibility
2277 # For backwards compatibility
2310 runsource = run_source
2278 runsource = run_source
2311
2279
2312 def run_code(self, code_obj, post_execute=True):
2280 def run_code(self, code_obj, post_execute=True):
2313 """Execute a code object.
2281 """Execute a code object.
2314
2282
2315 When an exception occurs, self.showtraceback() is called to display a
2283 When an exception occurs, self.showtraceback() is called to display a
2316 traceback.
2284 traceback.
2317
2285
2318 Return value: a flag indicating whether the code to be run completed
2286 Return value: a flag indicating whether the code to be run completed
2319 successfully:
2287 successfully:
2320
2288
2321 - 0: successful execution.
2289 - 0: successful execution.
2322 - 1: an error occurred.
2290 - 1: an error occurred.
2323 """
2291 """
2324
2292
2325 # Set our own excepthook in case the user code tries to call it
2293 # Set our own excepthook in case the user code tries to call it
2326 # directly, so that the IPython crash handler doesn't get triggered
2294 # directly, so that the IPython crash handler doesn't get triggered
2327 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2295 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2328
2296
2329 # we save the original sys.excepthook in the instance, in case config
2297 # we save the original sys.excepthook in the instance, in case config
2330 # code (such as magics) needs access to it.
2298 # code (such as magics) needs access to it.
2331 self.sys_excepthook = old_excepthook
2299 self.sys_excepthook = old_excepthook
2332 outflag = 1 # happens in more places, so it's easier as default
2300 outflag = 1 # happens in more places, so it's easier as default
2333 try:
2301 try:
2334 try:
2302 try:
2335 self.hooks.pre_run_code_hook()
2303 self.hooks.pre_run_code_hook()
2336 #rprint('Running code', repr(code_obj)) # dbg
2304 #rprint('Running code', repr(code_obj)) # dbg
2337 exec code_obj in self.user_global_ns, self.user_ns
2305 exec code_obj in self.user_global_ns, self.user_ns
2338 finally:
2306 finally:
2339 # Reset our crash handler in place
2307 # Reset our crash handler in place
2340 sys.excepthook = old_excepthook
2308 sys.excepthook = old_excepthook
2341 except SystemExit:
2309 except SystemExit:
2342 self.reset_buffer()
2310 self.reset_buffer()
2343 self.showtraceback(exception_only=True)
2311 self.showtraceback(exception_only=True)
2344 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2312 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2345 except self.custom_exceptions:
2313 except self.custom_exceptions:
2346 etype,value,tb = sys.exc_info()
2314 etype,value,tb = sys.exc_info()
2347 self.CustomTB(etype,value,tb)
2315 self.CustomTB(etype,value,tb)
2348 except:
2316 except:
2349 self.showtraceback()
2317 self.showtraceback()
2350 else:
2318 else:
2351 outflag = 0
2319 outflag = 0
2352 if softspace(sys.stdout, 0):
2320 if softspace(sys.stdout, 0):
2353 print
2321 print
2354
2322
2355 # Execute any registered post-execution functions. Here, any errors
2323 # Execute any registered post-execution functions. Here, any errors
2356 # are reported only minimally and just on the terminal, because the
2324 # are reported only minimally and just on the terminal, because the
2357 # main exception channel may be occupied with a user traceback.
2325 # main exception channel may be occupied with a user traceback.
2358 # FIXME: we need to think this mechanism a little more carefully.
2326 # FIXME: we need to think this mechanism a little more carefully.
2359 if post_execute:
2327 if post_execute:
2360 for func in self._post_execute:
2328 for func in self._post_execute:
2361 try:
2329 try:
2362 func()
2330 func()
2363 except:
2331 except:
2364 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2332 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2365 func
2333 func
2366 print >> io.Term.cout, head
2334 print >> io.Term.cout, head
2367 print >> io.Term.cout, self._simple_error()
2335 print >> io.Term.cout, self._simple_error()
2368 print >> io.Term.cout, 'Removing from post_execute'
2336 print >> io.Term.cout, 'Removing from post_execute'
2369 self._post_execute.remove(func)
2337 self._post_execute.remove(func)
2370
2338
2371 # Flush out code object which has been run (and source)
2339 # Flush out code object which has been run (and source)
2372 self.code_to_run = None
2340 self.code_to_run = None
2373 return outflag
2341 return outflag
2374
2342
2375 # For backwards compatibility
2343 # For backwards compatibility
2376 runcode = run_code
2344 runcode = run_code
2377
2345
2378 # PENDING REMOVAL: this method is slated for deletion, once our new
2346 # PENDING REMOVAL: this method is slated for deletion, once our new
2379 # input logic has been 100% moved to frontends and is stable.
2347 # input logic has been 100% moved to frontends and is stable.
2380 def push_line(self, line):
2348 def push_line(self, line):
2381 """Push a line to the interpreter.
2349 """Push a line to the interpreter.
2382
2350
2383 The line should not have a trailing newline; it may have
2351 The line should not have a trailing newline; it may have
2384 internal newlines. The line is appended to a buffer and the
2352 internal newlines. The line is appended to a buffer and the
2385 interpreter's run_source() method is called with the
2353 interpreter's run_source() method is called with the
2386 concatenated contents of the buffer as source. If this
2354 concatenated contents of the buffer as source. If this
2387 indicates that the command was executed or invalid, the buffer
2355 indicates that the command was executed or invalid, the buffer
2388 is reset; otherwise, the command is incomplete, and the buffer
2356 is reset; otherwise, the command is incomplete, and the buffer
2389 is left as it was after the line was appended. The return
2357 is left as it was after the line was appended. The return
2390 value is 1 if more input is required, 0 if the line was dealt
2358 value is 1 if more input is required, 0 if the line was dealt
2391 with in some way (this is the same as run_source()).
2359 with in some way (this is the same as run_source()).
2392 """
2360 """
2393
2361
2394 # autoindent management should be done here, and not in the
2362 # autoindent management should be done here, and not in the
2395 # interactive loop, since that one is only seen by keyboard input. We
2363 # interactive loop, since that one is only seen by keyboard input. We
2396 # need this done correctly even for code run via runlines (which uses
2364 # need this done correctly even for code run via runlines (which uses
2397 # push).
2365 # push).
2398
2366
2399 #print 'push line: <%s>' % line # dbg
2367 #print 'push line: <%s>' % line # dbg
2400 self.buffer.append(line)
2368 self.buffer.append(line)
2401 full_source = '\n'.join(self.buffer)
2369 full_source = '\n'.join(self.buffer)
2402 more = self.run_source(full_source, self.filename)
2370 more = self.run_source(full_source, self.filename)
2403 if not more:
2371 if not more:
2404 self.history_manager.store_inputs('\n'.join(self.buffer_raw),
2372 self.history_manager.store_inputs(self.execution_count,
2405 full_source)
2373 '\n'.join(self.buffer_raw), full_source)
2406 self.reset_buffer()
2374 self.reset_buffer()
2407 self.execution_count += 1
2375 self.execution_count += 1
2408 return more
2376 return more
2409
2377
2410 def reset_buffer(self):
2378 def reset_buffer(self):
2411 """Reset the input buffer."""
2379 """Reset the input buffer."""
2412 self.buffer[:] = []
2380 self.buffer[:] = []
2413 self.buffer_raw[:] = []
2381 self.buffer_raw[:] = []
2414 self.input_splitter.reset()
2382 self.input_splitter.reset()
2415
2383
2416 # For backwards compatibility
2384 # For backwards compatibility
2417 resetbuffer = reset_buffer
2385 resetbuffer = reset_buffer
2418
2386
2419 def _is_secondary_block_start(self, s):
2387 def _is_secondary_block_start(self, s):
2420 if not s.endswith(':'):
2388 if not s.endswith(':'):
2421 return False
2389 return False
2422 if (s.startswith('elif') or
2390 if (s.startswith('elif') or
2423 s.startswith('else') or
2391 s.startswith('else') or
2424 s.startswith('except') or
2392 s.startswith('except') or
2425 s.startswith('finally')):
2393 s.startswith('finally')):
2426 return True
2394 return True
2427
2395
2428 def _cleanup_ipy_script(self, script):
2396 def _cleanup_ipy_script(self, script):
2429 """Make a script safe for self.runlines()
2397 """Make a script safe for self.runlines()
2430
2398
2431 Currently, IPython is lines based, with blocks being detected by
2399 Currently, IPython is lines based, with blocks being detected by
2432 empty lines. This is a problem for block based scripts that may
2400 empty lines. This is a problem for block based scripts that may
2433 not have empty lines after blocks. This script adds those empty
2401 not have empty lines after blocks. This script adds those empty
2434 lines to make scripts safe for running in the current line based
2402 lines to make scripts safe for running in the current line based
2435 IPython.
2403 IPython.
2436 """
2404 """
2437 res = []
2405 res = []
2438 lines = script.splitlines()
2406 lines = script.splitlines()
2439 level = 0
2407 level = 0
2440
2408
2441 for l in lines:
2409 for l in lines:
2442 lstripped = l.lstrip()
2410 lstripped = l.lstrip()
2443 stripped = l.strip()
2411 stripped = l.strip()
2444 if not stripped:
2412 if not stripped:
2445 continue
2413 continue
2446 newlevel = len(l) - len(lstripped)
2414 newlevel = len(l) - len(lstripped)
2447 if level > 0 and newlevel == 0 and \
2415 if level > 0 and newlevel == 0 and \
2448 not self._is_secondary_block_start(stripped):
2416 not self._is_secondary_block_start(stripped):
2449 # add empty line
2417 # add empty line
2450 res.append('')
2418 res.append('')
2451 res.append(l)
2419 res.append(l)
2452 level = newlevel
2420 level = newlevel
2453
2421
2454 return '\n'.join(res) + '\n'
2422 return '\n'.join(res) + '\n'
2455
2423
2456 #-------------------------------------------------------------------------
2424 #-------------------------------------------------------------------------
2457 # Things related to GUI support and pylab
2425 # Things related to GUI support and pylab
2458 #-------------------------------------------------------------------------
2426 #-------------------------------------------------------------------------
2459
2427
2460 def enable_pylab(self, gui=None):
2428 def enable_pylab(self, gui=None):
2461 raise NotImplementedError('Implement enable_pylab in a subclass')
2429 raise NotImplementedError('Implement enable_pylab in a subclass')
2462
2430
2463 #-------------------------------------------------------------------------
2431 #-------------------------------------------------------------------------
2464 # Utilities
2432 # Utilities
2465 #-------------------------------------------------------------------------
2433 #-------------------------------------------------------------------------
2466
2434
2467 def var_expand(self,cmd,depth=0):
2435 def var_expand(self,cmd,depth=0):
2468 """Expand python variables in a string.
2436 """Expand python variables in a string.
2469
2437
2470 The depth argument indicates how many frames above the caller should
2438 The depth argument indicates how many frames above the caller should
2471 be walked to look for the local namespace where to expand variables.
2439 be walked to look for the local namespace where to expand variables.
2472
2440
2473 The global namespace for expansion is always the user's interactive
2441 The global namespace for expansion is always the user's interactive
2474 namespace.
2442 namespace.
2475 """
2443 """
2476
2444
2477 return str(ItplNS(cmd,
2445 return str(ItplNS(cmd,
2478 self.user_ns, # globals
2446 self.user_ns, # globals
2479 # Skip our own frame in searching for locals:
2447 # Skip our own frame in searching for locals:
2480 sys._getframe(depth+1).f_locals # locals
2448 sys._getframe(depth+1).f_locals # locals
2481 ))
2449 ))
2482
2450
2483 def mktempfile(self, data=None, prefix='ipython_edit_'):
2451 def mktempfile(self, data=None, prefix='ipython_edit_'):
2484 """Make a new tempfile and return its filename.
2452 """Make a new tempfile and return its filename.
2485
2453
2486 This makes a call to tempfile.mktemp, but it registers the created
2454 This makes a call to tempfile.mktemp, but it registers the created
2487 filename internally so ipython cleans it up at exit time.
2455 filename internally so ipython cleans it up at exit time.
2488
2456
2489 Optional inputs:
2457 Optional inputs:
2490
2458
2491 - data(None): if data is given, it gets written out to the temp file
2459 - data(None): if data is given, it gets written out to the temp file
2492 immediately, and the file is closed again."""
2460 immediately, and the file is closed again."""
2493
2461
2494 filename = tempfile.mktemp('.py', prefix)
2462 filename = tempfile.mktemp('.py', prefix)
2495 self.tempfiles.append(filename)
2463 self.tempfiles.append(filename)
2496
2464
2497 if data:
2465 if data:
2498 tmp_file = open(filename,'w')
2466 tmp_file = open(filename,'w')
2499 tmp_file.write(data)
2467 tmp_file.write(data)
2500 tmp_file.close()
2468 tmp_file.close()
2501 return filename
2469 return filename
2502
2470
2503 # TODO: This should be removed when Term is refactored.
2471 # TODO: This should be removed when Term is refactored.
2504 def write(self,data):
2472 def write(self,data):
2505 """Write a string to the default output"""
2473 """Write a string to the default output"""
2506 io.Term.cout.write(data)
2474 io.Term.cout.write(data)
2507
2475
2508 # TODO: This should be removed when Term is refactored.
2476 # TODO: This should be removed when Term is refactored.
2509 def write_err(self,data):
2477 def write_err(self,data):
2510 """Write a string to the default error output"""
2478 """Write a string to the default error output"""
2511 io.Term.cerr.write(data)
2479 io.Term.cerr.write(data)
2512
2480
2513 def ask_yes_no(self,prompt,default=True):
2481 def ask_yes_no(self,prompt,default=True):
2514 if self.quiet:
2482 if self.quiet:
2515 return True
2483 return True
2516 return ask_yes_no(prompt,default)
2484 return ask_yes_no(prompt,default)
2517
2485
2518 def show_usage(self):
2486 def show_usage(self):
2519 """Show a usage message"""
2487 """Show a usage message"""
2520 page.page(IPython.core.usage.interactive_usage)
2488 page.page(IPython.core.usage.interactive_usage)
2521
2489
2522 #-------------------------------------------------------------------------
2490 #-------------------------------------------------------------------------
2523 # Things related to IPython exiting
2491 # Things related to IPython exiting
2524 #-------------------------------------------------------------------------
2492 #-------------------------------------------------------------------------
2525 def atexit_operations(self):
2493 def atexit_operations(self):
2526 """This will be executed at the time of exit.
2494 """This will be executed at the time of exit.
2527
2495
2528 Cleanup operations and saving of persistent data that is done
2496 Cleanup operations and saving of persistent data that is done
2529 unconditionally by IPython should be performed here.
2497 unconditionally by IPython should be performed here.
2530
2498
2531 For things that may depend on startup flags or platform specifics (such
2499 For things that may depend on startup flags or platform specifics (such
2532 as having readline or not), register a separate atexit function in the
2500 as having readline or not), register a separate atexit function in the
2533 code that has the appropriate information, rather than trying to
2501 code that has the appropriate information, rather than trying to
2534 clutter
2502 clutter
2535 """
2503 """
2536 # Cleanup all tempfiles left around
2504 # Cleanup all tempfiles left around
2537 for tfile in self.tempfiles:
2505 for tfile in self.tempfiles:
2538 try:
2506 try:
2539 os.unlink(tfile)
2507 os.unlink(tfile)
2540 except OSError:
2508 except OSError:
2541 pass
2509 pass
2542
2510
2543 self.save_history()
2511 # Close the history session (this stores the end time and line count)
2544
2512 self.history_manager.end_session()
2513
2545 # Clear all user namespaces to release all references cleanly.
2514 # Clear all user namespaces to release all references cleanly.
2546 self.reset()
2515 self.reset(new_session=False)
2547
2516
2548 # Run user hooks
2517 # Run user hooks
2549 self.hooks.shutdown_hook()
2518 self.hooks.shutdown_hook()
2550
2519
2551 def cleanup(self):
2520 def cleanup(self):
2552 self.restore_sys_module_state()
2521 self.restore_sys_module_state()
2553
2522
2554
2523
2555 class InteractiveShellABC(object):
2524 class InteractiveShellABC(object):
2556 """An abstract base class for InteractiveShell."""
2525 """An abstract base class for InteractiveShell."""
2557 __metaclass__ = abc.ABCMeta
2526 __metaclass__ = abc.ABCMeta
2558
2527
2559 InteractiveShellABC.register(InteractiveShell)
2528 InteractiveShellABC.register(InteractiveShell)
@@ -1,39 +1,33 b''
1 """Support for interactive macros in IPython"""
1 """Support for interactive macros in IPython"""
2
2
3 #*****************************************************************************
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
8 #*****************************************************************************
9
9
10 import IPython.utils.io
10 import IPython.utils.io
11 from IPython.core.autocall import IPyAutocall
12
11
13 class Macro(IPyAutocall):
12 class Macro(object):
14 """Simple class to store the value of macros as strings.
13 """Simple class to store the value of macros as strings.
15
14
16 Macro is just a callable that executes a string of IPython
15 Macro is just a callable that executes a string of IPython
17 input when called.
16 input when called.
18
17
19 Args to macro are available in _margv list if you need them.
18 Args to macro are available in _margv list if you need them.
20 """
19 """
21
20
22 def __init__(self,data):
21 def __init__(self,code):
23 """store the macro value, as a single string which can be executed"""
22 """store the macro value, as a single string which can be executed"""
24 self.value = ''.join(data).rstrip()+'\n'
23 self.value = code.rstrip()+'\n'
25
24
26 def __str__(self):
25 def __str__(self):
27 return self.value
26 return self.value
28
27
29 def __repr__(self):
28 def __repr__(self):
30 return 'IPython.macro.Macro(%s)' % repr(self.value)
29 return 'IPython.macro.Macro(%s)' % repr(self.value)
31
30
32 def __call__(self,*args):
33 IPython.utils.io.Term.cout.flush()
34 self._ip.user_ns['_margv'] = args
35 self._ip.run_cell(self.value)
36
37 def __getstate__(self):
31 def __getstate__(self):
38 """ needed for safe pickling via %store """
32 """ needed for safe pickling via %store """
39 return {'value': self.value}
33 return {'value': self.value}
@@ -1,3510 +1,3450 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, 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_lines(self, range_str, 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 - range_str: the set of slices is given as a string, like
174 ['1','4:8','9'], since this function is for use by magic functions
174 "~5/6-~4/2 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. The number before the / is the
176 session number: ~n goes n back from the current session.
176
177
177 Optional inputs:
178 Optional inputs:
178
179
179 - raw(False): by default, the processed input is used. If this is
180 - raw(False): by default, the processed input is used. If this is
180 true, the raw input history is used instead.
181 true, the raw input history is used instead.
181
182
182 Note that slices can be called with two notations:
183 Note that slices can be called with two notations:
183
184
184 N:M -> standard python form, means including items N...(M-1).
185 N:M -> standard python form, means including items N...(M-1).
185
186
186 N-M -> include items N..M (closed endpoint)."""
187 N-M -> include items N..M (closed endpoint)."""
187
188 lines = self.shell.history_manager.\
188 if raw:
189 get_range_by_str(range_str, raw=raw)
189 hist = self.shell.history_manager.input_hist_raw
190 return "\n".join(x for _, _, x in lines)
190 else:
191 hist = self.shell.history_manager.input_hist_parsed
192
193 cmds = []
194 for chunk in slices:
195 if ':' in chunk:
196 ini,fin = map(int,chunk.split(':'))
197 elif '-' in chunk:
198 ini,fin = map(int,chunk.split('-'))
199 fin += 1
200 else:
201 ini = int(chunk)
202 fin = ini+1
203 cmds.append(''.join(hist[ini:fin]))
204 return cmds
205
191
206 def arg_err(self,func):
192 def arg_err(self,func):
207 """Print docstring if incorrect arguments were passed"""
193 """Print docstring if incorrect arguments were passed"""
208 print 'Error in arguments:'
194 print 'Error in arguments:'
209 print oinspect.getdoc(func)
195 print oinspect.getdoc(func)
210
196
211 def format_latex(self,strng):
197 def format_latex(self,strng):
212 """Format a string for latex inclusion."""
198 """Format a string for latex inclusion."""
213
199
214 # Characters that need to be escaped for latex:
200 # Characters that need to be escaped for latex:
215 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
201 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
216 # Magic command names as headers:
202 # Magic command names as headers:
217 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
203 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
218 re.MULTILINE)
204 re.MULTILINE)
219 # Magic commands
205 # Magic commands
220 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
206 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
221 re.MULTILINE)
207 re.MULTILINE)
222 # Paragraph continue
208 # Paragraph continue
223 par_re = re.compile(r'\\$',re.MULTILINE)
209 par_re = re.compile(r'\\$',re.MULTILINE)
224
210
225 # The "\n" symbol
211 # The "\n" symbol
226 newline_re = re.compile(r'\\n')
212 newline_re = re.compile(r'\\n')
227
213
228 # Now build the string for output:
214 # Now build the string for output:
229 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
215 #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}}:',
216 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
231 strng)
217 strng)
232 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
218 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
233 strng = par_re.sub(r'\\\\',strng)
219 strng = par_re.sub(r'\\\\',strng)
234 strng = escape_re.sub(r'\\\1',strng)
220 strng = escape_re.sub(r'\\\1',strng)
235 strng = newline_re.sub(r'\\textbackslash{}n',strng)
221 strng = newline_re.sub(r'\\textbackslash{}n',strng)
236 return strng
222 return strng
237
223
238 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
224 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
239 """Parse options passed to an argument string.
225 """Parse options passed to an argument string.
240
226
241 The interface is similar to that of getopt(), but it returns back a
227 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
228 Struct with the options as keys and the stripped argument string still
243 as a string.
229 as a string.
244
230
245 arg_str is quoted as a true sys.argv vector by using shlex.split.
231 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
232 This allows us to easily expand variables, glob files, quote
247 arguments, etc.
233 arguments, etc.
248
234
249 Options:
235 Options:
250 -mode: default 'string'. If given as 'list', the argument string is
236 -mode: default 'string'. If given as 'list', the argument string is
251 returned as a list (split on whitespace) instead of a string.
237 returned as a list (split on whitespace) instead of a string.
252
238
253 -list_all: put all option values in lists. Normally only options
239 -list_all: put all option values in lists. Normally only options
254 appearing more than once are put in a list.
240 appearing more than once are put in a list.
255
241
256 -posix (True): whether to split the input line in POSIX mode or not,
242 -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
243 as per the conventions outlined in the shlex module from the
258 standard library."""
244 standard library."""
259
245
260 # inject default options at the beginning of the input line
246 # inject default options at the beginning of the input line
261 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
247 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
262 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
248 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
263
249
264 mode = kw.get('mode','string')
250 mode = kw.get('mode','string')
265 if mode not in ['string','list']:
251 if mode not in ['string','list']:
266 raise ValueError,'incorrect mode given: %s' % mode
252 raise ValueError,'incorrect mode given: %s' % mode
267 # Get options
253 # Get options
268 list_all = kw.get('list_all',0)
254 list_all = kw.get('list_all',0)
269 posix = kw.get('posix', os.name == 'posix')
255 posix = kw.get('posix', os.name == 'posix')
270
256
271 # Check if we have more than one argument to warrant extra processing:
257 # Check if we have more than one argument to warrant extra processing:
272 odict = {} # Dictionary with options
258 odict = {} # Dictionary with options
273 args = arg_str.split()
259 args = arg_str.split()
274 if len(args) >= 1:
260 if len(args) >= 1:
275 # If the list of inputs only has 0 or 1 thing in it, there's no
261 # If the list of inputs only has 0 or 1 thing in it, there's no
276 # need to look for options
262 # need to look for options
277 argv = arg_split(arg_str,posix)
263 argv = arg_split(arg_str,posix)
278 # Do regular option processing
264 # Do regular option processing
279 try:
265 try:
280 opts,args = getopt(argv,opt_str,*long_opts)
266 opts,args = getopt(argv,opt_str,*long_opts)
281 except GetoptError,e:
267 except GetoptError,e:
282 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
268 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
283 " ".join(long_opts)))
269 " ".join(long_opts)))
284 for o,a in opts:
270 for o,a in opts:
285 if o.startswith('--'):
271 if o.startswith('--'):
286 o = o[2:]
272 o = o[2:]
287 else:
273 else:
288 o = o[1:]
274 o = o[1:]
289 try:
275 try:
290 odict[o].append(a)
276 odict[o].append(a)
291 except AttributeError:
277 except AttributeError:
292 odict[o] = [odict[o],a]
278 odict[o] = [odict[o],a]
293 except KeyError:
279 except KeyError:
294 if list_all:
280 if list_all:
295 odict[o] = [a]
281 odict[o] = [a]
296 else:
282 else:
297 odict[o] = a
283 odict[o] = a
298
284
299 # Prepare opts,args for return
285 # Prepare opts,args for return
300 opts = Struct(odict)
286 opts = Struct(odict)
301 if mode == 'string':
287 if mode == 'string':
302 args = ' '.join(args)
288 args = ' '.join(args)
303
289
304 return opts,args
290 return opts,args
305
291
306 #......................................................................
292 #......................................................................
307 # And now the actual magic functions
293 # And now the actual magic functions
308
294
309 # Functions for IPython shell work (vars,funcs, config, etc)
295 # Functions for IPython shell work (vars,funcs, config, etc)
310 def magic_lsmagic(self, parameter_s = ''):
296 def magic_lsmagic(self, parameter_s = ''):
311 """List currently available magic functions."""
297 """List currently available magic functions."""
312 mesc = ESC_MAGIC
298 mesc = ESC_MAGIC
313 print 'Available magic functions:\n'+mesc+\
299 print 'Available magic functions:\n'+mesc+\
314 (' '+mesc).join(self.lsmagic())
300 (' '+mesc).join(self.lsmagic())
315 print '\n' + Magic.auto_status[self.shell.automagic]
301 print '\n' + Magic.auto_status[self.shell.automagic]
316 return None
302 return None
317
303
318 def magic_magic(self, parameter_s = ''):
304 def magic_magic(self, parameter_s = ''):
319 """Print information about the magic function system.
305 """Print information about the magic function system.
320
306
321 Supported formats: -latex, -brief, -rest
307 Supported formats: -latex, -brief, -rest
322 """
308 """
323
309
324 mode = ''
310 mode = ''
325 try:
311 try:
326 if parameter_s.split()[0] == '-latex':
312 if parameter_s.split()[0] == '-latex':
327 mode = 'latex'
313 mode = 'latex'
328 if parameter_s.split()[0] == '-brief':
314 if parameter_s.split()[0] == '-brief':
329 mode = 'brief'
315 mode = 'brief'
330 if parameter_s.split()[0] == '-rest':
316 if parameter_s.split()[0] == '-rest':
331 mode = 'rest'
317 mode = 'rest'
332 rest_docs = []
318 rest_docs = []
333 except:
319 except:
334 pass
320 pass
335
321
336 magic_docs = []
322 magic_docs = []
337 for fname in self.lsmagic():
323 for fname in self.lsmagic():
338 mname = 'magic_' + fname
324 mname = 'magic_' + fname
339 for space in (Magic,self,self.__class__):
325 for space in (Magic,self,self.__class__):
340 try:
326 try:
341 fn = space.__dict__[mname]
327 fn = space.__dict__[mname]
342 except KeyError:
328 except KeyError:
343 pass
329 pass
344 else:
330 else:
345 break
331 break
346 if mode == 'brief':
332 if mode == 'brief':
347 # only first line
333 # only first line
348 if fn.__doc__:
334 if fn.__doc__:
349 fndoc = fn.__doc__.split('\n',1)[0]
335 fndoc = fn.__doc__.split('\n',1)[0]
350 else:
336 else:
351 fndoc = 'No documentation'
337 fndoc = 'No documentation'
352 else:
338 else:
353 if fn.__doc__:
339 if fn.__doc__:
354 fndoc = fn.__doc__.rstrip()
340 fndoc = fn.__doc__.rstrip()
355 else:
341 else:
356 fndoc = 'No documentation'
342 fndoc = 'No documentation'
357
343
358
344
359 if mode == 'rest':
345 if mode == 'rest':
360 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
346 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
361 fname,fndoc))
347 fname,fndoc))
362
348
363 else:
349 else:
364 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
350 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
365 fname,fndoc))
351 fname,fndoc))
366
352
367 magic_docs = ''.join(magic_docs)
353 magic_docs = ''.join(magic_docs)
368
354
369 if mode == 'rest':
355 if mode == 'rest':
370 return "".join(rest_docs)
356 return "".join(rest_docs)
371
357
372 if mode == 'latex':
358 if mode == 'latex':
373 print self.format_latex(magic_docs)
359 print self.format_latex(magic_docs)
374 return
360 return
375 else:
361 else:
376 magic_docs = format_screen(magic_docs)
362 magic_docs = format_screen(magic_docs)
377 if mode == 'brief':
363 if mode == 'brief':
378 return magic_docs
364 return magic_docs
379
365
380 outmsg = """
366 outmsg = """
381 IPython's 'magic' functions
367 IPython's 'magic' functions
382 ===========================
368 ===========================
383
369
384 The magic function system provides a series of functions which allow you to
370 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
371 control the behavior of IPython itself, plus a lot of system-type
386 features. All these functions are prefixed with a % character, but parameters
372 features. All these functions are prefixed with a % character, but parameters
387 are given without parentheses or quotes.
373 are given without parentheses or quotes.
388
374
389 NOTE: If you have 'automagic' enabled (via the command line option or with the
375 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,
376 %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.
377 IPython ships with automagic on, so you should only rarely need the % escape.
392
378
393 Example: typing '%cd mydir' (without the quotes) changes you working directory
379 Example: typing '%cd mydir' (without the quotes) changes you working directory
394 to 'mydir', if it exists.
380 to 'mydir', if it exists.
395
381
396 You can define your own magic functions to extend the system. See the supplied
382 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
383 ipythonrc and example-magic.py files for details (in your ipython
398 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
384 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
399
385
400 You can also define your own aliased names for magic functions. In your
386 You can also define your own aliased names for magic functions. In your
401 ipythonrc file, placing a line like:
387 ipythonrc file, placing a line like:
402
388
403 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
389 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
404
390
405 will define %pf as a new name for %profile.
391 will define %pf as a new name for %profile.
406
392
407 You can also call magics in code using the magic() function, which IPython
393 You can also call magics in code using the magic() function, which IPython
408 automatically adds to the builtin namespace. Type 'magic?' for details.
394 automatically adds to the builtin namespace. Type 'magic?' for details.
409
395
410 For a list of the available magic functions, use %lsmagic. For a description
396 For a list of the available magic functions, use %lsmagic. For a description
411 of any of them, type %magic_name?, e.g. '%cd?'.
397 of any of them, type %magic_name?, e.g. '%cd?'.
412
398
413 Currently the magic system has the following functions:\n"""
399 Currently the magic system has the following functions:\n"""
414
400
415 mesc = ESC_MAGIC
401 mesc = ESC_MAGIC
416 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
417 "\n\n%s%s\n\n%s" % (outmsg,
403 "\n\n%s%s\n\n%s" % (outmsg,
418 magic_docs,mesc,mesc,
404 magic_docs,mesc,mesc,
419 (' '+mesc).join(self.lsmagic()),
405 (' '+mesc).join(self.lsmagic()),
420 Magic.auto_status[self.shell.automagic] ) )
406 Magic.auto_status[self.shell.automagic] ) )
421 page.page(outmsg)
407 page.page(outmsg)
422
408
423 def magic_automagic(self, parameter_s = ''):
409 def magic_automagic(self, parameter_s = ''):
424 """Make magic functions callable without having to type the initial %.
410 """Make magic functions callable without having to type the initial %.
425
411
426 Without argumentsl toggles on/off (when off, you must call it as
412 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
413 %automagic, of course). With arguments it sets the value, and you can
428 use any of (case insensitive):
414 use any of (case insensitive):
429
415
430 - on,1,True: to activate
416 - on,1,True: to activate
431
417
432 - off,0,False: to deactivate.
418 - off,0,False: to deactivate.
433
419
434 Note that magic functions have lowest priority, so if there's a
420 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
421 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
422 work for that function (you get the variable instead). However, if you
437 delete the variable (del var), the previously shadowed magic function
423 delete the variable (del var), the previously shadowed magic function
438 becomes visible to automagic again."""
424 becomes visible to automagic again."""
439
425
440 arg = parameter_s.lower()
426 arg = parameter_s.lower()
441 if parameter_s in ('on','1','true'):
427 if parameter_s in ('on','1','true'):
442 self.shell.automagic = True
428 self.shell.automagic = True
443 elif parameter_s in ('off','0','false'):
429 elif parameter_s in ('off','0','false'):
444 self.shell.automagic = False
430 self.shell.automagic = False
445 else:
431 else:
446 self.shell.automagic = not self.shell.automagic
432 self.shell.automagic = not self.shell.automagic
447 print '\n' + Magic.auto_status[self.shell.automagic]
433 print '\n' + Magic.auto_status[self.shell.automagic]
448
434
449 @testdec.skip_doctest
435 @testdec.skip_doctest
450 def magic_autocall(self, parameter_s = ''):
436 def magic_autocall(self, parameter_s = ''):
451 """Make functions callable without having to type parentheses.
437 """Make functions callable without having to type parentheses.
452
438
453 Usage:
439 Usage:
454
440
455 %autocall [mode]
441 %autocall [mode]
456
442
457 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
443 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).
444 value is toggled on and off (remembering the previous state).
459
445
460 In more detail, these values mean:
446 In more detail, these values mean:
461
447
462 0 -> fully disabled
448 0 -> fully disabled
463
449
464 1 -> active, but do not apply if there are no arguments on the line.
450 1 -> active, but do not apply if there are no arguments on the line.
465
451
466 In this mode, you get:
452 In this mode, you get:
467
453
468 In [1]: callable
454 In [1]: callable
469 Out[1]: <built-in function callable>
455 Out[1]: <built-in function callable>
470
456
471 In [2]: callable 'hello'
457 In [2]: callable 'hello'
472 ------> callable('hello')
458 ------> callable('hello')
473 Out[2]: False
459 Out[2]: False
474
460
475 2 -> Active always. Even if no arguments are present, the callable
461 2 -> Active always. Even if no arguments are present, the callable
476 object is called:
462 object is called:
477
463
478 In [2]: float
464 In [2]: float
479 ------> float()
465 ------> float()
480 Out[2]: 0.0
466 Out[2]: 0.0
481
467
482 Note that even with autocall off, you can still use '/' at the start of
468 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
469 a line to treat the first argument on the command line as a function
484 and add parentheses to it:
470 and add parentheses to it:
485
471
486 In [8]: /str 43
472 In [8]: /str 43
487 ------> str(43)
473 ------> str(43)
488 Out[8]: '43'
474 Out[8]: '43'
489
475
490 # all-random (note for auto-testing)
476 # all-random (note for auto-testing)
491 """
477 """
492
478
493 if parameter_s:
479 if parameter_s:
494 arg = int(parameter_s)
480 arg = int(parameter_s)
495 else:
481 else:
496 arg = 'toggle'
482 arg = 'toggle'
497
483
498 if not arg in (0,1,2,'toggle'):
484 if not arg in (0,1,2,'toggle'):
499 error('Valid modes: (0->Off, 1->Smart, 2->Full')
485 error('Valid modes: (0->Off, 1->Smart, 2->Full')
500 return
486 return
501
487
502 if arg in (0,1,2):
488 if arg in (0,1,2):
503 self.shell.autocall = arg
489 self.shell.autocall = arg
504 else: # toggle
490 else: # toggle
505 if self.shell.autocall:
491 if self.shell.autocall:
506 self._magic_state.autocall_save = self.shell.autocall
492 self._magic_state.autocall_save = self.shell.autocall
507 self.shell.autocall = 0
493 self.shell.autocall = 0
508 else:
494 else:
509 try:
495 try:
510 self.shell.autocall = self._magic_state.autocall_save
496 self.shell.autocall = self._magic_state.autocall_save
511 except AttributeError:
497 except AttributeError:
512 self.shell.autocall = self._magic_state.autocall_save = 1
498 self.shell.autocall = self._magic_state.autocall_save = 1
513
499
514 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
500 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
515
501
516
502
517 def magic_page(self, parameter_s=''):
503 def magic_page(self, parameter_s=''):
518 """Pretty print the object and display it through a pager.
504 """Pretty print the object and display it through a pager.
519
505
520 %page [options] OBJECT
506 %page [options] OBJECT
521
507
522 If no object is given, use _ (last output).
508 If no object is given, use _ (last output).
523
509
524 Options:
510 Options:
525
511
526 -r: page str(object), don't pretty-print it."""
512 -r: page str(object), don't pretty-print it."""
527
513
528 # After a function contributed by Olivier Aubert, slightly modified.
514 # After a function contributed by Olivier Aubert, slightly modified.
529
515
530 # Process options/args
516 # Process options/args
531 opts,args = self.parse_options(parameter_s,'r')
517 opts,args = self.parse_options(parameter_s,'r')
532 raw = 'r' in opts
518 raw = 'r' in opts
533
519
534 oname = args and args or '_'
520 oname = args and args or '_'
535 info = self._ofind(oname)
521 info = self._ofind(oname)
536 if info['found']:
522 if info['found']:
537 txt = (raw and str or pformat)( info['obj'] )
523 txt = (raw and str or pformat)( info['obj'] )
538 page.page(txt)
524 page.page(txt)
539 else:
525 else:
540 print 'Object `%s` not found' % oname
526 print 'Object `%s` not found' % oname
541
527
542 def magic_profile(self, parameter_s=''):
528 def magic_profile(self, parameter_s=''):
543 """Print your currently active IPython profile."""
529 """Print your currently active IPython profile."""
544 if self.shell.profile:
530 if self.shell.profile:
545 printpl('Current IPython profile: $self.shell.profile.')
531 printpl('Current IPython profile: $self.shell.profile.')
546 else:
532 else:
547 print 'No profile active.'
533 print 'No profile active.'
548
534
549 def magic_pinfo(self, parameter_s='', namespaces=None):
535 def magic_pinfo(self, parameter_s='', namespaces=None):
550 """Provide detailed information about an object.
536 """Provide detailed information about an object.
551
537
552 '%pinfo object' is just a synonym for object? or ?object."""
538 '%pinfo object' is just a synonym for object? or ?object."""
553
539
554 #print 'pinfo par: <%s>' % parameter_s # dbg
540 #print 'pinfo par: <%s>' % parameter_s # dbg
555
541
556
542
557 # detail_level: 0 -> obj? , 1 -> obj??
543 # detail_level: 0 -> obj? , 1 -> obj??
558 detail_level = 0
544 detail_level = 0
559 # We need to detect if we got called as 'pinfo pinfo foo', which can
545 # 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.
546 # happen if the user types 'pinfo foo?' at the cmd line.
561 pinfo,qmark1,oname,qmark2 = \
547 pinfo,qmark1,oname,qmark2 = \
562 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
548 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
563 if pinfo or qmark1 or qmark2:
549 if pinfo or qmark1 or qmark2:
564 detail_level = 1
550 detail_level = 1
565 if "*" in oname:
551 if "*" in oname:
566 self.magic_psearch(oname)
552 self.magic_psearch(oname)
567 else:
553 else:
568 self.shell._inspect('pinfo', oname, detail_level=detail_level,
554 self.shell._inspect('pinfo', oname, detail_level=detail_level,
569 namespaces=namespaces)
555 namespaces=namespaces)
570
556
571 def magic_pinfo2(self, parameter_s='', namespaces=None):
557 def magic_pinfo2(self, parameter_s='', namespaces=None):
572 """Provide extra detailed information about an object.
558 """Provide extra detailed information about an object.
573
559
574 '%pinfo2 object' is just a synonym for object?? or ??object."""
560 '%pinfo2 object' is just a synonym for object?? or ??object."""
575 self.shell._inspect('pinfo', parameter_s, detail_level=1,
561 self.shell._inspect('pinfo', parameter_s, detail_level=1,
576 namespaces=namespaces)
562 namespaces=namespaces)
577
563
578 @testdec.skip_doctest
564 @testdec.skip_doctest
579 def magic_pdef(self, parameter_s='', namespaces=None):
565 def magic_pdef(self, parameter_s='', namespaces=None):
580 """Print the definition header for any callable object.
566 """Print the definition header for any callable object.
581
567
582 If the object is a class, print the constructor information.
568 If the object is a class, print the constructor information.
583
569
584 Examples
570 Examples
585 --------
571 --------
586 ::
572 ::
587
573
588 In [3]: %pdef urllib.urlopen
574 In [3]: %pdef urllib.urlopen
589 urllib.urlopen(url, data=None, proxies=None)
575 urllib.urlopen(url, data=None, proxies=None)
590 """
576 """
591 self._inspect('pdef',parameter_s, namespaces)
577 self._inspect('pdef',parameter_s, namespaces)
592
578
593 def magic_pdoc(self, parameter_s='', namespaces=None):
579 def magic_pdoc(self, parameter_s='', namespaces=None):
594 """Print the docstring for an object.
580 """Print the docstring for an object.
595
581
596 If the given object is a class, it will print both the class and the
582 If the given object is a class, it will print both the class and the
597 constructor docstrings."""
583 constructor docstrings."""
598 self._inspect('pdoc',parameter_s, namespaces)
584 self._inspect('pdoc',parameter_s, namespaces)
599
585
600 def magic_psource(self, parameter_s='', namespaces=None):
586 def magic_psource(self, parameter_s='', namespaces=None):
601 """Print (or run through pager) the source code for an object."""
587 """Print (or run through pager) the source code for an object."""
602 self._inspect('psource',parameter_s, namespaces)
588 self._inspect('psource',parameter_s, namespaces)
603
589
604 def magic_pfile(self, parameter_s=''):
590 def magic_pfile(self, parameter_s=''):
605 """Print (or run through pager) the file where an object is defined.
591 """Print (or run through pager) the file where an object is defined.
606
592
607 The file opens at the line where the object definition begins. IPython
593 The file opens at the line where the object definition begins. IPython
608 will honor the environment variable PAGER if set, and otherwise will
594 will honor the environment variable PAGER if set, and otherwise will
609 do its best to print the file in a convenient form.
595 do its best to print the file in a convenient form.
610
596
611 If the given argument is not an object currently defined, IPython will
597 If the given argument is not an object currently defined, IPython will
612 try to interpret it as a filename (automatically adding a .py extension
598 try to interpret it as a filename (automatically adding a .py extension
613 if needed). You can thus use %pfile as a syntax highlighting code
599 if needed). You can thus use %pfile as a syntax highlighting code
614 viewer."""
600 viewer."""
615
601
616 # first interpret argument as an object name
602 # first interpret argument as an object name
617 out = self._inspect('pfile',parameter_s)
603 out = self._inspect('pfile',parameter_s)
618 # if not, try the input as a filename
604 # if not, try the input as a filename
619 if out == 'not found':
605 if out == 'not found':
620 try:
606 try:
621 filename = get_py_filename(parameter_s)
607 filename = get_py_filename(parameter_s)
622 except IOError,msg:
608 except IOError,msg:
623 print msg
609 print msg
624 return
610 return
625 page.page(self.shell.inspector.format(file(filename).read()))
611 page.page(self.shell.inspector.format(file(filename).read()))
626
612
627 def magic_psearch(self, parameter_s=''):
613 def magic_psearch(self, parameter_s=''):
628 """Search for object in namespaces by wildcard.
614 """Search for object in namespaces by wildcard.
629
615
630 %psearch [options] PATTERN [OBJECT TYPE]
616 %psearch [options] PATTERN [OBJECT TYPE]
631
617
632 Note: ? can be used as a synonym for %psearch, at the beginning or at
618 Note: ? can be used as a synonym for %psearch, at the beginning or at
633 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
619 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
634 rest of the command line must be unchanged (options come first), so
620 rest of the command line must be unchanged (options come first), so
635 for example the following forms are equivalent
621 for example the following forms are equivalent
636
622
637 %psearch -i a* function
623 %psearch -i a* function
638 -i a* function?
624 -i a* function?
639 ?-i a* function
625 ?-i a* function
640
626
641 Arguments:
627 Arguments:
642
628
643 PATTERN
629 PATTERN
644
630
645 where PATTERN is a string containing * as a wildcard similar to its
631 where PATTERN is a string containing * as a wildcard similar to its
646 use in a shell. The pattern is matched in all namespaces on the
632 use in a shell. The pattern is matched in all namespaces on the
647 search path. By default objects starting with a single _ are not
633 search path. By default objects starting with a single _ are not
648 matched, many IPython generated objects have a single
634 matched, many IPython generated objects have a single
649 underscore. The default is case insensitive matching. Matching is
635 underscore. The default is case insensitive matching. Matching is
650 also done on the attributes of objects and not only on the objects
636 also done on the attributes of objects and not only on the objects
651 in a module.
637 in a module.
652
638
653 [OBJECT TYPE]
639 [OBJECT TYPE]
654
640
655 Is the name of a python type from the types module. The name is
641 Is the name of a python type from the types module. The name is
656 given in lowercase without the ending type, ex. StringType is
642 given in lowercase without the ending type, ex. StringType is
657 written string. By adding a type here only objects matching the
643 written string. By adding a type here only objects matching the
658 given type are matched. Using all here makes the pattern match all
644 given type are matched. Using all here makes the pattern match all
659 types (this is the default).
645 types (this is the default).
660
646
661 Options:
647 Options:
662
648
663 -a: makes the pattern match even objects whose names start with a
649 -a: makes the pattern match even objects whose names start with a
664 single underscore. These names are normally ommitted from the
650 single underscore. These names are normally ommitted from the
665 search.
651 search.
666
652
667 -i/-c: make the pattern case insensitive/sensitive. If neither of
653 -i/-c: make the pattern case insensitive/sensitive. If neither of
668 these options is given, the default is read from your ipythonrc
654 these options is given, the default is read from your ipythonrc
669 file. The option name which sets this value is
655 file. The option name which sets this value is
670 'wildcards_case_sensitive'. If this option is not specified in your
656 'wildcards_case_sensitive'. If this option is not specified in your
671 ipythonrc file, IPython's internal default is to do a case sensitive
657 ipythonrc file, IPython's internal default is to do a case sensitive
672 search.
658 search.
673
659
674 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
660 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
675 specifiy can be searched in any of the following namespaces:
661 specifiy can be searched in any of the following namespaces:
676 'builtin', 'user', 'user_global','internal', 'alias', where
662 'builtin', 'user', 'user_global','internal', 'alias', where
677 'builtin' and 'user' are the search defaults. Note that you should
663 'builtin' and 'user' are the search defaults. Note that you should
678 not use quotes when specifying namespaces.
664 not use quotes when specifying namespaces.
679
665
680 'Builtin' contains the python module builtin, 'user' contains all
666 'Builtin' contains the python module builtin, 'user' contains all
681 user data, 'alias' only contain the shell aliases and no python
667 user data, 'alias' only contain the shell aliases and no python
682 objects, 'internal' contains objects used by IPython. The
668 objects, 'internal' contains objects used by IPython. The
683 'user_global' namespace is only used by embedded IPython instances,
669 'user_global' namespace is only used by embedded IPython instances,
684 and it contains module-level globals. You can add namespaces to the
670 and it contains module-level globals. You can add namespaces to the
685 search with -s or exclude them with -e (these options can be given
671 search with -s or exclude them with -e (these options can be given
686 more than once).
672 more than once).
687
673
688 Examples:
674 Examples:
689
675
690 %psearch a* -> objects beginning with an a
676 %psearch a* -> objects beginning with an a
691 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
677 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
692 %psearch a* function -> all functions beginning with an a
678 %psearch a* function -> all functions beginning with an a
693 %psearch re.e* -> objects beginning with an e in module re
679 %psearch re.e* -> objects beginning with an e in module re
694 %psearch r*.e* -> objects that start with e in modules starting in r
680 %psearch r*.e* -> objects that start with e in modules starting in r
695 %psearch r*.* string -> all strings in modules beginning with r
681 %psearch r*.* string -> all strings in modules beginning with r
696
682
697 Case sensitve search:
683 Case sensitve search:
698
684
699 %psearch -c a* list all object beginning with lower case a
685 %psearch -c a* list all object beginning with lower case a
700
686
701 Show objects beginning with a single _:
687 Show objects beginning with a single _:
702
688
703 %psearch -a _* list objects beginning with a single underscore"""
689 %psearch -a _* list objects beginning with a single underscore"""
704 try:
690 try:
705 parameter_s = parameter_s.encode('ascii')
691 parameter_s = parameter_s.encode('ascii')
706 except UnicodeEncodeError:
692 except UnicodeEncodeError:
707 print 'Python identifiers can only contain ascii characters.'
693 print 'Python identifiers can only contain ascii characters.'
708 return
694 return
709
695
710 # default namespaces to be searched
696 # default namespaces to be searched
711 def_search = ['user','builtin']
697 def_search = ['user','builtin']
712
698
713 # Process options/args
699 # Process options/args
714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
700 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
715 opt = opts.get
701 opt = opts.get
716 shell = self.shell
702 shell = self.shell
717 psearch = shell.inspector.psearch
703 psearch = shell.inspector.psearch
718
704
719 # select case options
705 # select case options
720 if opts.has_key('i'):
706 if opts.has_key('i'):
721 ignore_case = True
707 ignore_case = True
722 elif opts.has_key('c'):
708 elif opts.has_key('c'):
723 ignore_case = False
709 ignore_case = False
724 else:
710 else:
725 ignore_case = not shell.wildcards_case_sensitive
711 ignore_case = not shell.wildcards_case_sensitive
726
712
727 # Build list of namespaces to search from user options
713 # Build list of namespaces to search from user options
728 def_search.extend(opt('s',[]))
714 def_search.extend(opt('s',[]))
729 ns_exclude = ns_exclude=opt('e',[])
715 ns_exclude = ns_exclude=opt('e',[])
730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
716 ns_search = [nm for nm in def_search if nm not in ns_exclude]
731
717
732 # Call the actual search
718 # Call the actual search
733 try:
719 try:
734 psearch(args,shell.ns_table,ns_search,
720 psearch(args,shell.ns_table,ns_search,
735 show_all=opt('a'),ignore_case=ignore_case)
721 show_all=opt('a'),ignore_case=ignore_case)
736 except:
722 except:
737 shell.showtraceback()
723 shell.showtraceback()
738
724
739 @testdec.skip_doctest
725 @testdec.skip_doctest
740 def magic_who_ls(self, parameter_s=''):
726 def magic_who_ls(self, parameter_s=''):
741 """Return a sorted list of all interactive variables.
727 """Return a sorted list of all interactive variables.
742
728
743 If arguments are given, only variables of types matching these
729 If arguments are given, only variables of types matching these
744 arguments are returned.
730 arguments are returned.
745
731
746 Examples
732 Examples
747 --------
733 --------
748
734
749 Define two variables and list them with who_ls::
735 Define two variables and list them with who_ls::
750
736
751 In [1]: alpha = 123
737 In [1]: alpha = 123
752
738
753 In [2]: beta = 'test'
739 In [2]: beta = 'test'
754
740
755 In [3]: %who_ls
741 In [3]: %who_ls
756 Out[3]: ['alpha', 'beta']
742 Out[3]: ['alpha', 'beta']
757
743
758 In [4]: %who_ls int
744 In [4]: %who_ls int
759 Out[4]: ['alpha']
745 Out[4]: ['alpha']
760
746
761 In [5]: %who_ls str
747 In [5]: %who_ls str
762 Out[5]: ['beta']
748 Out[5]: ['beta']
763 """
749 """
764
750
765 user_ns = self.shell.user_ns
751 user_ns = self.shell.user_ns
766 internal_ns = self.shell.internal_ns
752 internal_ns = self.shell.internal_ns
767 user_ns_hidden = self.shell.user_ns_hidden
753 user_ns_hidden = self.shell.user_ns_hidden
768 out = [ i for i in user_ns
754 out = [ i for i in user_ns
769 if not i.startswith('_') \
755 if not i.startswith('_') \
770 and not (i in internal_ns or i in user_ns_hidden) ]
756 and not (i in internal_ns or i in user_ns_hidden) ]
771
757
772 typelist = parameter_s.split()
758 typelist = parameter_s.split()
773 if typelist:
759 if typelist:
774 typeset = set(typelist)
760 typeset = set(typelist)
775 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
761 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
776
762
777 out.sort()
763 out.sort()
778 return out
764 return out
779
765
780 @testdec.skip_doctest
766 @testdec.skip_doctest
781 def magic_who(self, parameter_s=''):
767 def magic_who(self, parameter_s=''):
782 """Print all interactive variables, with some minimal formatting.
768 """Print all interactive variables, with some minimal formatting.
783
769
784 If any arguments are given, only variables whose type matches one of
770 If any arguments are given, only variables whose type matches one of
785 these are printed. For example:
771 these are printed. For example:
786
772
787 %who function str
773 %who function str
788
774
789 will only list functions and strings, excluding all other types of
775 will only list functions and strings, excluding all other types of
790 variables. To find the proper type names, simply use type(var) at a
776 variables. To find the proper type names, simply use type(var) at a
791 command line to see how python prints type names. For example:
777 command line to see how python prints type names. For example:
792
778
793 In [1]: type('hello')\\
779 In [1]: type('hello')\\
794 Out[1]: <type 'str'>
780 Out[1]: <type 'str'>
795
781
796 indicates that the type name for strings is 'str'.
782 indicates that the type name for strings is 'str'.
797
783
798 %who always excludes executed names loaded through your configuration
784 %who always excludes executed names loaded through your configuration
799 file and things which are internal to IPython.
785 file and things which are internal to IPython.
800
786
801 This is deliberate, as typically you may load many modules and the
787 This is deliberate, as typically you may load many modules and the
802 purpose of %who is to show you only what you've manually defined.
788 purpose of %who is to show you only what you've manually defined.
803
789
804 Examples
790 Examples
805 --------
791 --------
806
792
807 Define two variables and list them with who::
793 Define two variables and list them with who::
808
794
809 In [1]: alpha = 123
795 In [1]: alpha = 123
810
796
811 In [2]: beta = 'test'
797 In [2]: beta = 'test'
812
798
813 In [3]: %who
799 In [3]: %who
814 alpha beta
800 alpha beta
815
801
816 In [4]: %who int
802 In [4]: %who int
817 alpha
803 alpha
818
804
819 In [5]: %who str
805 In [5]: %who str
820 beta
806 beta
821 """
807 """
822
808
823 varlist = self.magic_who_ls(parameter_s)
809 varlist = self.magic_who_ls(parameter_s)
824 if not varlist:
810 if not varlist:
825 if parameter_s:
811 if parameter_s:
826 print 'No variables match your requested type.'
812 print 'No variables match your requested type.'
827 else:
813 else:
828 print 'Interactive namespace is empty.'
814 print 'Interactive namespace is empty.'
829 return
815 return
830
816
831 # if we have variables, move on...
817 # if we have variables, move on...
832 count = 0
818 count = 0
833 for i in varlist:
819 for i in varlist:
834 print i+'\t',
820 print i+'\t',
835 count += 1
821 count += 1
836 if count > 8:
822 if count > 8:
837 count = 0
823 count = 0
838 print
824 print
839 print
825 print
840
826
841 @testdec.skip_doctest
827 @testdec.skip_doctest
842 def magic_whos(self, parameter_s=''):
828 def magic_whos(self, parameter_s=''):
843 """Like %who, but gives some extra information about each variable.
829 """Like %who, but gives some extra information about each variable.
844
830
845 The same type filtering of %who can be applied here.
831 The same type filtering of %who can be applied here.
846
832
847 For all variables, the type is printed. Additionally it prints:
833 For all variables, the type is printed. Additionally it prints:
848
834
849 - For {},[],(): their length.
835 - For {},[],(): their length.
850
836
851 - For numpy and Numeric arrays, a summary with shape, number of
837 - For numpy and Numeric arrays, a summary with shape, number of
852 elements, typecode and size in memory.
838 elements, typecode and size in memory.
853
839
854 - Everything else: a string representation, snipping their middle if
840 - Everything else: a string representation, snipping their middle if
855 too long.
841 too long.
856
842
857 Examples
843 Examples
858 --------
844 --------
859
845
860 Define two variables and list them with whos::
846 Define two variables and list them with whos::
861
847
862 In [1]: alpha = 123
848 In [1]: alpha = 123
863
849
864 In [2]: beta = 'test'
850 In [2]: beta = 'test'
865
851
866 In [3]: %whos
852 In [3]: %whos
867 Variable Type Data/Info
853 Variable Type Data/Info
868 --------------------------------
854 --------------------------------
869 alpha int 123
855 alpha int 123
870 beta str test
856 beta str test
871 """
857 """
872
858
873 varnames = self.magic_who_ls(parameter_s)
859 varnames = self.magic_who_ls(parameter_s)
874 if not varnames:
860 if not varnames:
875 if parameter_s:
861 if parameter_s:
876 print 'No variables match your requested type.'
862 print 'No variables match your requested type.'
877 else:
863 else:
878 print 'Interactive namespace is empty.'
864 print 'Interactive namespace is empty.'
879 return
865 return
880
866
881 # if we have variables, move on...
867 # if we have variables, move on...
882
868
883 # for these types, show len() instead of data:
869 # for these types, show len() instead of data:
884 seq_types = [types.DictType,types.ListType,types.TupleType]
870 seq_types = [types.DictType,types.ListType,types.TupleType]
885
871
886 # for numpy/Numeric arrays, display summary info
872 # for numpy/Numeric arrays, display summary info
887 try:
873 try:
888 import numpy
874 import numpy
889 except ImportError:
875 except ImportError:
890 ndarray_type = None
876 ndarray_type = None
891 else:
877 else:
892 ndarray_type = numpy.ndarray.__name__
878 ndarray_type = numpy.ndarray.__name__
893 try:
879 try:
894 import Numeric
880 import Numeric
895 except ImportError:
881 except ImportError:
896 array_type = None
882 array_type = None
897 else:
883 else:
898 array_type = Numeric.ArrayType.__name__
884 array_type = Numeric.ArrayType.__name__
899
885
900 # Find all variable names and types so we can figure out column sizes
886 # Find all variable names and types so we can figure out column sizes
901 def get_vars(i):
887 def get_vars(i):
902 return self.shell.user_ns[i]
888 return self.shell.user_ns[i]
903
889
904 # some types are well known and can be shorter
890 # some types are well known and can be shorter
905 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
891 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
906 def type_name(v):
892 def type_name(v):
907 tn = type(v).__name__
893 tn = type(v).__name__
908 return abbrevs.get(tn,tn)
894 return abbrevs.get(tn,tn)
909
895
910 varlist = map(get_vars,varnames)
896 varlist = map(get_vars,varnames)
911
897
912 typelist = []
898 typelist = []
913 for vv in varlist:
899 for vv in varlist:
914 tt = type_name(vv)
900 tt = type_name(vv)
915
901
916 if tt=='instance':
902 if tt=='instance':
917 typelist.append( abbrevs.get(str(vv.__class__),
903 typelist.append( abbrevs.get(str(vv.__class__),
918 str(vv.__class__)))
904 str(vv.__class__)))
919 else:
905 else:
920 typelist.append(tt)
906 typelist.append(tt)
921
907
922 # column labels and # of spaces as separator
908 # column labels and # of spaces as separator
923 varlabel = 'Variable'
909 varlabel = 'Variable'
924 typelabel = 'Type'
910 typelabel = 'Type'
925 datalabel = 'Data/Info'
911 datalabel = 'Data/Info'
926 colsep = 3
912 colsep = 3
927 # variable format strings
913 # variable format strings
928 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
914 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
929 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
915 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
930 aformat = "%s: %s elems, type `%s`, %s bytes"
916 aformat = "%s: %s elems, type `%s`, %s bytes"
931 # find the size of the columns to format the output nicely
917 # find the size of the columns to format the output nicely
932 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
918 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
933 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
919 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
934 # table header
920 # table header
935 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
921 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
936 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
922 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
937 # and the table itself
923 # and the table itself
938 kb = 1024
924 kb = 1024
939 Mb = 1048576 # kb**2
925 Mb = 1048576 # kb**2
940 for vname,var,vtype in zip(varnames,varlist,typelist):
926 for vname,var,vtype in zip(varnames,varlist,typelist):
941 print itpl(vformat),
927 print itpl(vformat),
942 if vtype in seq_types:
928 if vtype in seq_types:
943 print len(var)
929 print len(var)
944 elif vtype in [array_type,ndarray_type]:
930 elif vtype in [array_type,ndarray_type]:
945 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
931 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
946 if vtype==ndarray_type:
932 if vtype==ndarray_type:
947 # numpy
933 # numpy
948 vsize = var.size
934 vsize = var.size
949 vbytes = vsize*var.itemsize
935 vbytes = vsize*var.itemsize
950 vdtype = var.dtype
936 vdtype = var.dtype
951 else:
937 else:
952 # Numeric
938 # Numeric
953 vsize = Numeric.size(var)
939 vsize = Numeric.size(var)
954 vbytes = vsize*var.itemsize()
940 vbytes = vsize*var.itemsize()
955 vdtype = var.typecode()
941 vdtype = var.typecode()
956
942
957 if vbytes < 100000:
943 if vbytes < 100000:
958 print aformat % (vshape,vsize,vdtype,vbytes)
944 print aformat % (vshape,vsize,vdtype,vbytes)
959 else:
945 else:
960 print aformat % (vshape,vsize,vdtype,vbytes),
946 print aformat % (vshape,vsize,vdtype,vbytes),
961 if vbytes < Mb:
947 if vbytes < Mb:
962 print '(%s kb)' % (vbytes/kb,)
948 print '(%s kb)' % (vbytes/kb,)
963 else:
949 else:
964 print '(%s Mb)' % (vbytes/Mb,)
950 print '(%s Mb)' % (vbytes/Mb,)
965 else:
951 else:
966 try:
952 try:
967 vstr = str(var)
953 vstr = str(var)
968 except UnicodeEncodeError:
954 except UnicodeEncodeError:
969 vstr = unicode(var).encode(sys.getdefaultencoding(),
955 vstr = unicode(var).encode(sys.getdefaultencoding(),
970 'backslashreplace')
956 'backslashreplace')
971 vstr = vstr.replace('\n','\\n')
957 vstr = vstr.replace('\n','\\n')
972 if len(vstr) < 50:
958 if len(vstr) < 50:
973 print vstr
959 print vstr
974 else:
960 else:
975 printpl(vfmt_short)
961 printpl(vfmt_short)
976
962
977 def magic_reset(self, parameter_s=''):
963 def magic_reset(self, parameter_s=''):
978 """Resets the namespace by removing all names defined by the user.
964 """Resets the namespace by removing all names defined by the user.
979
965
980 Input/Output history are left around in case you need them.
966 Input/Output history are left around in case you need them.
981
967
982 Parameters
968 Parameters
983 ----------
969 ----------
984 -f : force reset without asking for confirmation.
970 -f : force reset without asking for confirmation.
985
971
986 Examples
972 Examples
987 --------
973 --------
988 In [6]: a = 1
974 In [6]: a = 1
989
975
990 In [7]: a
976 In [7]: a
991 Out[7]: 1
977 Out[7]: 1
992
978
993 In [8]: 'a' in _ip.user_ns
979 In [8]: 'a' in _ip.user_ns
994 Out[8]: True
980 Out[8]: True
995
981
996 In [9]: %reset -f
982 In [9]: %reset -f
997
983
998 In [10]: 'a' in _ip.user_ns
984 In [10]: 'a' in _ip.user_ns
999 Out[10]: False
985 Out[10]: False
1000 """
986 """
1001
987
1002 if parameter_s == '-f':
988 if parameter_s == '-f':
1003 ans = True
989 ans = True
1004 else:
990 else:
1005 ans = self.shell.ask_yes_no(
991 ans = self.shell.ask_yes_no(
1006 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
992 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1007 if not ans:
993 if not ans:
1008 print 'Nothing done.'
994 print 'Nothing done.'
1009 return
995 return
1010 user_ns = self.shell.user_ns
996 user_ns = self.shell.user_ns
1011 for i in self.magic_who_ls():
997 for i in self.magic_who_ls():
1012 del(user_ns[i])
998 del(user_ns[i])
1013
999
1014 # Also flush the private list of module references kept for script
1000 # Also flush the private list of module references kept for script
1015 # execution protection
1001 # execution protection
1016 self.shell.clear_main_mod_cache()
1002 self.shell.clear_main_mod_cache()
1017
1003
1018 def magic_reset_selective(self, parameter_s=''):
1004 def magic_reset_selective(self, parameter_s=''):
1019 """Resets the namespace by removing names defined by the user.
1005 """Resets the namespace by removing names defined by the user.
1020
1006
1021 Input/Output history are left around in case you need them.
1007 Input/Output history are left around in case you need them.
1022
1008
1023 %reset_selective [-f] regex
1009 %reset_selective [-f] regex
1024
1010
1025 No action is taken if regex is not included
1011 No action is taken if regex is not included
1026
1012
1027 Options
1013 Options
1028 -f : force reset without asking for confirmation.
1014 -f : force reset without asking for confirmation.
1029
1015
1030 Examples
1016 Examples
1031 --------
1017 --------
1032
1018
1033 We first fully reset the namespace so your output looks identical to
1019 We first fully reset the namespace so your output looks identical to
1034 this example for pedagogical reasons; in practice you do not need a
1020 this example for pedagogical reasons; in practice you do not need a
1035 full reset.
1021 full reset.
1036
1022
1037 In [1]: %reset -f
1023 In [1]: %reset -f
1038
1024
1039 Now, with a clean namespace we can make a few variables and use
1025 Now, with a clean namespace we can make a few variables and use
1040 %reset_selective to only delete names that match our regexp:
1026 %reset_selective to only delete names that match our regexp:
1041
1027
1042 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1028 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1043
1029
1044 In [3]: who_ls
1030 In [3]: who_ls
1045 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1031 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1046
1032
1047 In [4]: %reset_selective -f b[2-3]m
1033 In [4]: %reset_selective -f b[2-3]m
1048
1034
1049 In [5]: who_ls
1035 In [5]: who_ls
1050 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1036 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1051
1037
1052 In [6]: %reset_selective -f d
1038 In [6]: %reset_selective -f d
1053
1039
1054 In [7]: who_ls
1040 In [7]: who_ls
1055 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1041 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1056
1042
1057 In [8]: %reset_selective -f c
1043 In [8]: %reset_selective -f c
1058
1044
1059 In [9]: who_ls
1045 In [9]: who_ls
1060 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1046 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1061
1047
1062 In [10]: %reset_selective -f b
1048 In [10]: %reset_selective -f b
1063
1049
1064 In [11]: who_ls
1050 In [11]: who_ls
1065 Out[11]: ['a']
1051 Out[11]: ['a']
1066 """
1052 """
1067
1053
1068 opts, regex = self.parse_options(parameter_s,'f')
1054 opts, regex = self.parse_options(parameter_s,'f')
1069
1055
1070 if opts.has_key('f'):
1056 if opts.has_key('f'):
1071 ans = True
1057 ans = True
1072 else:
1058 else:
1073 ans = self.shell.ask_yes_no(
1059 ans = self.shell.ask_yes_no(
1074 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1060 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1075 if not ans:
1061 if not ans:
1076 print 'Nothing done.'
1062 print 'Nothing done.'
1077 return
1063 return
1078 user_ns = self.shell.user_ns
1064 user_ns = self.shell.user_ns
1079 if not regex:
1065 if not regex:
1080 print 'No regex pattern specified. Nothing done.'
1066 print 'No regex pattern specified. Nothing done.'
1081 return
1067 return
1082 else:
1068 else:
1083 try:
1069 try:
1084 m = re.compile(regex)
1070 m = re.compile(regex)
1085 except TypeError:
1071 except TypeError:
1086 raise TypeError('regex must be a string or compiled pattern')
1072 raise TypeError('regex must be a string or compiled pattern')
1087 for i in self.magic_who_ls():
1073 for i in self.magic_who_ls():
1088 if m.search(i):
1074 if m.search(i):
1089 del(user_ns[i])
1075 del(user_ns[i])
1090
1076
1091 def magic_logstart(self,parameter_s=''):
1077 def magic_logstart(self,parameter_s=''):
1092 """Start logging anywhere in a session.
1078 """Start logging anywhere in a session.
1093
1079
1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1080 %logstart [-o|-r|-t] [log_name [log_mode]]
1095
1081
1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1082 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 current directory, in 'rotate' mode (see below).
1083 current directory, in 'rotate' mode (see below).
1098
1084
1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1085 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 history up to that point and then continues logging.
1086 history up to that point and then continues logging.
1101
1087
1102 %logstart takes a second optional parameter: logging mode. This can be one
1088 %logstart takes a second optional parameter: logging mode. This can be one
1103 of (note that the modes are given unquoted):\\
1089 of (note that the modes are given unquoted):\\
1104 append: well, that says it.\\
1090 append: well, that says it.\\
1105 backup: rename (if exists) to name~ and start name.\\
1091 backup: rename (if exists) to name~ and start name.\\
1106 global: single logfile in your home dir, appended to.\\
1092 global: single logfile in your home dir, appended to.\\
1107 over : overwrite existing log.\\
1093 over : overwrite existing log.\\
1108 rotate: create rotating logs name.1~, name.2~, etc.
1094 rotate: create rotating logs name.1~, name.2~, etc.
1109
1095
1110 Options:
1096 Options:
1111
1097
1112 -o: log also IPython's output. In this mode, all commands which
1098 -o: log also IPython's output. In this mode, all commands which
1113 generate an Out[NN] prompt are recorded to the logfile, right after
1099 generate an Out[NN] prompt are recorded to the logfile, right after
1114 their corresponding input line. The output lines are always
1100 their corresponding input line. The output lines are always
1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1101 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 Python code.
1102 Python code.
1117
1103
1118 Since this marker is always the same, filtering only the output from
1104 Since this marker is always the same, filtering only the output from
1119 a log is very easy, using for example a simple awk call:
1105 a log is very easy, using for example a simple awk call:
1120
1106
1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1107 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122
1108
1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1109 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 input, so that user lines are logged in their final form, converted
1110 input, so that user lines are logged in their final form, converted
1125 into valid Python. For example, %Exit is logged as
1111 into valid Python. For example, %Exit is logged as
1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1112 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 exactly as typed, with no transformations applied.
1113 exactly as typed, with no transformations applied.
1128
1114
1129 -t: put timestamps before each input line logged (these are put in
1115 -t: put timestamps before each input line logged (these are put in
1130 comments)."""
1116 comments)."""
1131
1117
1132 opts,par = self.parse_options(parameter_s,'ort')
1118 opts,par = self.parse_options(parameter_s,'ort')
1133 log_output = 'o' in opts
1119 log_output = 'o' in opts
1134 log_raw_input = 'r' in opts
1120 log_raw_input = 'r' in opts
1135 timestamp = 't' in opts
1121 timestamp = 't' in opts
1136
1122
1137 logger = self.shell.logger
1123 logger = self.shell.logger
1138
1124
1139 # if no args are given, the defaults set in the logger constructor by
1125 # if no args are given, the defaults set in the logger constructor by
1140 # ipytohn remain valid
1126 # ipytohn remain valid
1141 if par:
1127 if par:
1142 try:
1128 try:
1143 logfname,logmode = par.split()
1129 logfname,logmode = par.split()
1144 except:
1130 except:
1145 logfname = par
1131 logfname = par
1146 logmode = 'backup'
1132 logmode = 'backup'
1147 else:
1133 else:
1148 logfname = logger.logfname
1134 logfname = logger.logfname
1149 logmode = logger.logmode
1135 logmode = logger.logmode
1150 # put logfname into rc struct as if it had been called on the command
1136 # put logfname into rc struct as if it had been called on the command
1151 # line, so it ends up saved in the log header Save it in case we need
1137 # line, so it ends up saved in the log header Save it in case we need
1152 # to restore it...
1138 # to restore it...
1153 old_logfile = self.shell.logfile
1139 old_logfile = self.shell.logfile
1154 if logfname:
1140 if logfname:
1155 logfname = os.path.expanduser(logfname)
1141 logfname = os.path.expanduser(logfname)
1156 self.shell.logfile = logfname
1142 self.shell.logfile = logfname
1157
1143
1158 loghead = '# IPython log file\n\n'
1144 loghead = '# IPython log file\n\n'
1159 try:
1145 try:
1160 started = logger.logstart(logfname,loghead,logmode,
1146 started = logger.logstart(logfname,loghead,logmode,
1161 log_output,timestamp,log_raw_input)
1147 log_output,timestamp,log_raw_input)
1162 except:
1148 except:
1163 self.shell.logfile = old_logfile
1149 self.shell.logfile = old_logfile
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1150 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 else:
1151 else:
1166 # log input history up to this point, optionally interleaving
1152 # log input history up to this point, optionally interleaving
1167 # output if requested
1153 # output if requested
1168
1154
1169 if timestamp:
1155 if timestamp:
1170 # disable timestamping for the previous history, since we've
1156 # disable timestamping for the previous history, since we've
1171 # lost those already (no time machine here).
1157 # lost those already (no time machine here).
1172 logger.timestamp = False
1158 logger.timestamp = False
1173
1159
1174 if log_raw_input:
1160 if log_raw_input:
1175 input_hist = self.shell.history_manager.input_hist_raw
1161 input_hist = self.shell.history_manager.input_hist_raw
1176 else:
1162 else:
1177 input_hist = self.shell.history_manager.input_hist_parsed
1163 input_hist = self.shell.history_manager.input_hist_parsed
1178
1164
1179 if log_output:
1165 if log_output:
1180 log_write = logger.log_write
1166 log_write = logger.log_write
1181 output_hist = self.shell.history_manager.output_hist
1167 output_hist = self.shell.history_manager.output_hist
1182 for n in range(1,len(input_hist)-1):
1168 for n in range(1,len(input_hist)-1):
1183 log_write(input_hist[n].rstrip())
1169 log_write(input_hist[n].rstrip())
1184 if n in output_hist:
1170 if n in output_hist:
1185 log_write(repr(output_hist[n]),'output')
1171 log_write(repr(output_hist[n]),'output')
1186 else:
1172 else:
1187 logger.log_write(''.join(input_hist[1:]))
1173 logger.log_write(''.join(input_hist[1:]))
1188 if timestamp:
1174 if timestamp:
1189 # re-enable timestamping
1175 # re-enable timestamping
1190 logger.timestamp = True
1176 logger.timestamp = True
1191
1177
1192 print ('Activating auto-logging. '
1178 print ('Activating auto-logging. '
1193 'Current session state plus future input saved.')
1179 'Current session state plus future input saved.')
1194 logger.logstate()
1180 logger.logstate()
1195
1181
1196 def magic_logstop(self,parameter_s=''):
1182 def magic_logstop(self,parameter_s=''):
1197 """Fully stop logging and close log file.
1183 """Fully stop logging and close log file.
1198
1184
1199 In order to start logging again, a new %logstart call needs to be made,
1185 In order to start logging again, a new %logstart call needs to be made,
1200 possibly (though not necessarily) with a new filename, mode and other
1186 possibly (though not necessarily) with a new filename, mode and other
1201 options."""
1187 options."""
1202 self.logger.logstop()
1188 self.logger.logstop()
1203
1189
1204 def magic_logoff(self,parameter_s=''):
1190 def magic_logoff(self,parameter_s=''):
1205 """Temporarily stop logging.
1191 """Temporarily stop logging.
1206
1192
1207 You must have previously started logging."""
1193 You must have previously started logging."""
1208 self.shell.logger.switch_log(0)
1194 self.shell.logger.switch_log(0)
1209
1195
1210 def magic_logon(self,parameter_s=''):
1196 def magic_logon(self,parameter_s=''):
1211 """Restart logging.
1197 """Restart logging.
1212
1198
1213 This function is for restarting logging which you've temporarily
1199 This function is for restarting logging which you've temporarily
1214 stopped with %logoff. For starting logging for the first time, you
1200 stopped with %logoff. For starting logging for the first time, you
1215 must use the %logstart function, which allows you to specify an
1201 must use the %logstart function, which allows you to specify an
1216 optional log filename."""
1202 optional log filename."""
1217
1203
1218 self.shell.logger.switch_log(1)
1204 self.shell.logger.switch_log(1)
1219
1205
1220 def magic_logstate(self,parameter_s=''):
1206 def magic_logstate(self,parameter_s=''):
1221 """Print the status of the logging system."""
1207 """Print the status of the logging system."""
1222
1208
1223 self.shell.logger.logstate()
1209 self.shell.logger.logstate()
1224
1210
1225 def magic_pdb(self, parameter_s=''):
1211 def magic_pdb(self, parameter_s=''):
1226 """Control the automatic calling of the pdb interactive debugger.
1212 """Control the automatic calling of the pdb interactive debugger.
1227
1213
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1214 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 argument it works as a toggle.
1215 argument it works as a toggle.
1230
1216
1231 When an exception is triggered, IPython can optionally call the
1217 When an exception is triggered, IPython can optionally call the
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1218 interactive pdb debugger after the traceback printout. %pdb toggles
1233 this feature on and off.
1219 this feature on and off.
1234
1220
1235 The initial state of this feature is set in your ipythonrc
1221 The initial state of this feature is set in your ipythonrc
1236 configuration file (the variable is called 'pdb').
1222 configuration file (the variable is called 'pdb').
1237
1223
1238 If you want to just activate the debugger AFTER an exception has fired,
1224 If you want to just activate the debugger AFTER an exception has fired,
1239 without having to type '%pdb on' and rerunning your code, you can use
1225 without having to type '%pdb on' and rerunning your code, you can use
1240 the %debug magic."""
1226 the %debug magic."""
1241
1227
1242 par = parameter_s.strip().lower()
1228 par = parameter_s.strip().lower()
1243
1229
1244 if par:
1230 if par:
1245 try:
1231 try:
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1232 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 except KeyError:
1233 except KeyError:
1248 print ('Incorrect argument. Use on/1, off/0, '
1234 print ('Incorrect argument. Use on/1, off/0, '
1249 'or nothing for a toggle.')
1235 'or nothing for a toggle.')
1250 return
1236 return
1251 else:
1237 else:
1252 # toggle
1238 # toggle
1253 new_pdb = not self.shell.call_pdb
1239 new_pdb = not self.shell.call_pdb
1254
1240
1255 # set on the shell
1241 # set on the shell
1256 self.shell.call_pdb = new_pdb
1242 self.shell.call_pdb = new_pdb
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1243 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258
1244
1259 def magic_debug(self, parameter_s=''):
1245 def magic_debug(self, parameter_s=''):
1260 """Activate the interactive debugger in post-mortem mode.
1246 """Activate the interactive debugger in post-mortem mode.
1261
1247
1262 If an exception has just occurred, this lets you inspect its stack
1248 If an exception has just occurred, this lets you inspect its stack
1263 frames interactively. Note that this will always work only on the last
1249 frames interactively. Note that this will always work only on the last
1264 traceback that occurred, so you must call this quickly after an
1250 traceback that occurred, so you must call this quickly after an
1265 exception that you wish to inspect has fired, because if another one
1251 exception that you wish to inspect has fired, because if another one
1266 occurs, it clobbers the previous one.
1252 occurs, it clobbers the previous one.
1267
1253
1268 If you want IPython to automatically do this on every exception, see
1254 If you want IPython to automatically do this on every exception, see
1269 the %pdb magic for more details.
1255 the %pdb magic for more details.
1270 """
1256 """
1271 self.shell.debugger(force=True)
1257 self.shell.debugger(force=True)
1272
1258
1273 @testdec.skip_doctest
1259 @testdec.skip_doctest
1274 def magic_prun(self, parameter_s ='',user_mode=1,
1260 def magic_prun(self, parameter_s ='',user_mode=1,
1275 opts=None,arg_lst=None,prog_ns=None):
1261 opts=None,arg_lst=None,prog_ns=None):
1276
1262
1277 """Run a statement through the python code profiler.
1263 """Run a statement through the python code profiler.
1278
1264
1279 Usage:
1265 Usage:
1280 %prun [options] statement
1266 %prun [options] statement
1281
1267
1282 The given statement (which doesn't require quote marks) is run via the
1268 The given statement (which doesn't require quote marks) is run via the
1283 python profiler in a manner similar to the profile.run() function.
1269 python profiler in a manner similar to the profile.run() function.
1284 Namespaces are internally managed to work correctly; profile.run
1270 Namespaces are internally managed to work correctly; profile.run
1285 cannot be used in IPython because it makes certain assumptions about
1271 cannot be used in IPython because it makes certain assumptions about
1286 namespaces which do not hold under IPython.
1272 namespaces which do not hold under IPython.
1287
1273
1288 Options:
1274 Options:
1289
1275
1290 -l <limit>: you can place restrictions on what or how much of the
1276 -l <limit>: you can place restrictions on what or how much of the
1291 profile gets printed. The limit value can be:
1277 profile gets printed. The limit value can be:
1292
1278
1293 * A string: only information for function names containing this string
1279 * A string: only information for function names containing this string
1294 is printed.
1280 is printed.
1295
1281
1296 * An integer: only these many lines are printed.
1282 * An integer: only these many lines are printed.
1297
1283
1298 * A float (between 0 and 1): this fraction of the report is printed
1284 * A float (between 0 and 1): this fraction of the report is printed
1299 (for example, use a limit of 0.4 to see the topmost 40% only).
1285 (for example, use a limit of 0.4 to see the topmost 40% only).
1300
1286
1301 You can combine several limits with repeated use of the option. For
1287 You can combine several limits with repeated use of the option. For
1302 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1288 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 information about class constructors.
1289 information about class constructors.
1304
1290
1305 -r: return the pstats.Stats object generated by the profiling. This
1291 -r: return the pstats.Stats object generated by the profiling. This
1306 object has all the information about the profile in it, and you can
1292 object has all the information about the profile in it, and you can
1307 later use it for further analysis or in other functions.
1293 later use it for further analysis or in other functions.
1308
1294
1309 -s <key>: sort profile by given key. You can provide more than one key
1295 -s <key>: sort profile by given key. You can provide more than one key
1310 by using the option several times: '-s key1 -s key2 -s key3...'. The
1296 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 default sorting key is 'time'.
1297 default sorting key is 'time'.
1312
1298
1313 The following is copied verbatim from the profile documentation
1299 The following is copied verbatim from the profile documentation
1314 referenced below:
1300 referenced below:
1315
1301
1316 When more than one key is provided, additional keys are used as
1302 When more than one key is provided, additional keys are used as
1317 secondary criteria when the there is equality in all keys selected
1303 secondary criteria when the there is equality in all keys selected
1318 before them.
1304 before them.
1319
1305
1320 Abbreviations can be used for any key names, as long as the
1306 Abbreviations can be used for any key names, as long as the
1321 abbreviation is unambiguous. The following are the keys currently
1307 abbreviation is unambiguous. The following are the keys currently
1322 defined:
1308 defined:
1323
1309
1324 Valid Arg Meaning
1310 Valid Arg Meaning
1325 "calls" call count
1311 "calls" call count
1326 "cumulative" cumulative time
1312 "cumulative" cumulative time
1327 "file" file name
1313 "file" file name
1328 "module" file name
1314 "module" file name
1329 "pcalls" primitive call count
1315 "pcalls" primitive call count
1330 "line" line number
1316 "line" line number
1331 "name" function name
1317 "name" function name
1332 "nfl" name/file/line
1318 "nfl" name/file/line
1333 "stdname" standard name
1319 "stdname" standard name
1334 "time" internal time
1320 "time" internal time
1335
1321
1336 Note that all sorts on statistics are in descending order (placing
1322 Note that all sorts on statistics are in descending order (placing
1337 most time consuming items first), where as name, file, and line number
1323 most time consuming items first), where as name, file, and line number
1338 searches are in ascending order (i.e., alphabetical). The subtle
1324 searches are in ascending order (i.e., alphabetical). The subtle
1339 distinction between "nfl" and "stdname" is that the standard name is a
1325 distinction between "nfl" and "stdname" is that the standard name is a
1340 sort of the name as printed, which means that the embedded line
1326 sort of the name as printed, which means that the embedded line
1341 numbers get compared in an odd way. For example, lines 3, 20, and 40
1327 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 would (if the file names were the same) appear in the string order
1328 would (if the file names were the same) appear in the string order
1343 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1329 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 line numbers. In fact, sort_stats("nfl") is the same as
1330 line numbers. In fact, sort_stats("nfl") is the same as
1345 sort_stats("name", "file", "line").
1331 sort_stats("name", "file", "line").
1346
1332
1347 -T <filename>: save profile results as shown on screen to a text
1333 -T <filename>: save profile results as shown on screen to a text
1348 file. The profile is still shown on screen.
1334 file. The profile is still shown on screen.
1349
1335
1350 -D <filename>: save (via dump_stats) profile statistics to given
1336 -D <filename>: save (via dump_stats) profile statistics to given
1351 filename. This data is in a format understod by the pstats module, and
1337 filename. This data is in a format understod by the pstats module, and
1352 is generated by a call to the dump_stats() method of profile
1338 is generated by a call to the dump_stats() method of profile
1353 objects. The profile is still shown on screen.
1339 objects. The profile is still shown on screen.
1354
1340
1355 If you want to run complete programs under the profiler's control, use
1341 If you want to run complete programs under the profiler's control, use
1356 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1342 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 contains profiler specific options as described here.
1343 contains profiler specific options as described here.
1358
1344
1359 You can read the complete documentation for the profile module with::
1345 You can read the complete documentation for the profile module with::
1360
1346
1361 In [1]: import profile; profile.help()
1347 In [1]: import profile; profile.help()
1362 """
1348 """
1363
1349
1364 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1350 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 # protect user quote marks
1351 # protect user quote marks
1366 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1352 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367
1353
1368 if user_mode: # regular user call
1354 if user_mode: # regular user call
1369 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1355 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 list_all=1)
1356 list_all=1)
1371 namespace = self.shell.user_ns
1357 namespace = self.shell.user_ns
1372 else: # called to run a program by %run -p
1358 else: # called to run a program by %run -p
1373 try:
1359 try:
1374 filename = get_py_filename(arg_lst[0])
1360 filename = get_py_filename(arg_lst[0])
1375 except IOError,msg:
1361 except IOError,msg:
1376 error(msg)
1362 error(msg)
1377 return
1363 return
1378
1364
1379 arg_str = 'execfile(filename,prog_ns)'
1365 arg_str = 'execfile(filename,prog_ns)'
1380 namespace = locals()
1366 namespace = locals()
1381
1367
1382 opts.merge(opts_def)
1368 opts.merge(opts_def)
1383
1369
1384 prof = profile.Profile()
1370 prof = profile.Profile()
1385 try:
1371 try:
1386 prof = prof.runctx(arg_str,namespace,namespace)
1372 prof = prof.runctx(arg_str,namespace,namespace)
1387 sys_exit = ''
1373 sys_exit = ''
1388 except SystemExit:
1374 except SystemExit:
1389 sys_exit = """*** SystemExit exception caught in code being profiled."""
1375 sys_exit = """*** SystemExit exception caught in code being profiled."""
1390
1376
1391 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1377 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1392
1378
1393 lims = opts.l
1379 lims = opts.l
1394 if lims:
1380 if lims:
1395 lims = [] # rebuild lims with ints/floats/strings
1381 lims = [] # rebuild lims with ints/floats/strings
1396 for lim in opts.l:
1382 for lim in opts.l:
1397 try:
1383 try:
1398 lims.append(int(lim))
1384 lims.append(int(lim))
1399 except ValueError:
1385 except ValueError:
1400 try:
1386 try:
1401 lims.append(float(lim))
1387 lims.append(float(lim))
1402 except ValueError:
1388 except ValueError:
1403 lims.append(lim)
1389 lims.append(lim)
1404
1390
1405 # Trap output.
1391 # Trap output.
1406 stdout_trap = StringIO()
1392 stdout_trap = StringIO()
1407
1393
1408 if hasattr(stats,'stream'):
1394 if hasattr(stats,'stream'):
1409 # In newer versions of python, the stats object has a 'stream'
1395 # In newer versions of python, the stats object has a 'stream'
1410 # attribute to write into.
1396 # attribute to write into.
1411 stats.stream = stdout_trap
1397 stats.stream = stdout_trap
1412 stats.print_stats(*lims)
1398 stats.print_stats(*lims)
1413 else:
1399 else:
1414 # For older versions, we manually redirect stdout during printing
1400 # For older versions, we manually redirect stdout during printing
1415 sys_stdout = sys.stdout
1401 sys_stdout = sys.stdout
1416 try:
1402 try:
1417 sys.stdout = stdout_trap
1403 sys.stdout = stdout_trap
1418 stats.print_stats(*lims)
1404 stats.print_stats(*lims)
1419 finally:
1405 finally:
1420 sys.stdout = sys_stdout
1406 sys.stdout = sys_stdout
1421
1407
1422 output = stdout_trap.getvalue()
1408 output = stdout_trap.getvalue()
1423 output = output.rstrip()
1409 output = output.rstrip()
1424
1410
1425 page.page(output)
1411 page.page(output)
1426 print sys_exit,
1412 print sys_exit,
1427
1413
1428 dump_file = opts.D[0]
1414 dump_file = opts.D[0]
1429 text_file = opts.T[0]
1415 text_file = opts.T[0]
1430 if dump_file:
1416 if dump_file:
1431 prof.dump_stats(dump_file)
1417 prof.dump_stats(dump_file)
1432 print '\n*** Profile stats marshalled to file',\
1418 print '\n*** Profile stats marshalled to file',\
1433 `dump_file`+'.',sys_exit
1419 `dump_file`+'.',sys_exit
1434 if text_file:
1420 if text_file:
1435 pfile = file(text_file,'w')
1421 pfile = file(text_file,'w')
1436 pfile.write(output)
1422 pfile.write(output)
1437 pfile.close()
1423 pfile.close()
1438 print '\n*** Profile printout saved to text file',\
1424 print '\n*** Profile printout saved to text file',\
1439 `text_file`+'.',sys_exit
1425 `text_file`+'.',sys_exit
1440
1426
1441 if opts.has_key('r'):
1427 if opts.has_key('r'):
1442 return stats
1428 return stats
1443 else:
1429 else:
1444 return None
1430 return None
1445
1431
1446 @testdec.skip_doctest
1432 @testdec.skip_doctest
1447 def magic_run(self, parameter_s ='',runner=None,
1433 def magic_run(self, parameter_s ='',runner=None,
1448 file_finder=get_py_filename):
1434 file_finder=get_py_filename):
1449 """Run the named file inside IPython as a program.
1435 """Run the named file inside IPython as a program.
1450
1436
1451 Usage:\\
1437 Usage:\\
1452 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1438 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1453
1439
1454 Parameters after the filename are passed as command-line arguments to
1440 Parameters after the filename are passed as command-line arguments to
1455 the program (put in sys.argv). Then, control returns to IPython's
1441 the program (put in sys.argv). Then, control returns to IPython's
1456 prompt.
1442 prompt.
1457
1443
1458 This is similar to running at a system prompt:\\
1444 This is similar to running at a system prompt:\\
1459 $ python file args\\
1445 $ python file args\\
1460 but with the advantage of giving you IPython's tracebacks, and of
1446 but with the advantage of giving you IPython's tracebacks, and of
1461 loading all variables into your interactive namespace for further use
1447 loading all variables into your interactive namespace for further use
1462 (unless -p is used, see below).
1448 (unless -p is used, see below).
1463
1449
1464 The file is executed in a namespace initially consisting only of
1450 The file is executed in a namespace initially consisting only of
1465 __name__=='__main__' and sys.argv constructed as indicated. It thus
1451 __name__=='__main__' and sys.argv constructed as indicated. It thus
1466 sees its environment as if it were being run as a stand-alone program
1452 sees its environment as if it were being run as a stand-alone program
1467 (except for sharing global objects such as previously imported
1453 (except for sharing global objects such as previously imported
1468 modules). But after execution, the IPython interactive namespace gets
1454 modules). But after execution, the IPython interactive namespace gets
1469 updated with all variables defined in the program (except for __name__
1455 updated with all variables defined in the program (except for __name__
1470 and sys.argv). This allows for very convenient loading of code for
1456 and sys.argv). This allows for very convenient loading of code for
1471 interactive work, while giving each program a 'clean sheet' to run in.
1457 interactive work, while giving each program a 'clean sheet' to run in.
1472
1458
1473 Options:
1459 Options:
1474
1460
1475 -n: __name__ is NOT set to '__main__', but to the running file's name
1461 -n: __name__ is NOT set to '__main__', but to the running file's name
1476 without extension (as python does under import). This allows running
1462 without extension (as python does under import). This allows running
1477 scripts and reloading the definitions in them without calling code
1463 scripts and reloading the definitions in them without calling code
1478 protected by an ' if __name__ == "__main__" ' clause.
1464 protected by an ' if __name__ == "__main__" ' clause.
1479
1465
1480 -i: run the file in IPython's namespace instead of an empty one. This
1466 -i: run the file in IPython's namespace instead of an empty one. This
1481 is useful if you are experimenting with code written in a text editor
1467 is useful if you are experimenting with code written in a text editor
1482 which depends on variables defined interactively.
1468 which depends on variables defined interactively.
1483
1469
1484 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1470 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1485 being run. This is particularly useful if IPython is being used to
1471 being run. This is particularly useful if IPython is being used to
1486 run unittests, which always exit with a sys.exit() call. In such
1472 run unittests, which always exit with a sys.exit() call. In such
1487 cases you are interested in the output of the test results, not in
1473 cases you are interested in the output of the test results, not in
1488 seeing a traceback of the unittest module.
1474 seeing a traceback of the unittest module.
1489
1475
1490 -t: print timing information at the end of the run. IPython will give
1476 -t: print timing information at the end of the run. IPython will give
1491 you an estimated CPU time consumption for your script, which under
1477 you an estimated CPU time consumption for your script, which under
1492 Unix uses the resource module to avoid the wraparound problems of
1478 Unix uses the resource module to avoid the wraparound problems of
1493 time.clock(). Under Unix, an estimate of time spent on system tasks
1479 time.clock(). Under Unix, an estimate of time spent on system tasks
1494 is also given (for Windows platforms this is reported as 0.0).
1480 is also given (for Windows platforms this is reported as 0.0).
1495
1481
1496 If -t is given, an additional -N<N> option can be given, where <N>
1482 If -t is given, an additional -N<N> option can be given, where <N>
1497 must be an integer indicating how many times you want the script to
1483 must be an integer indicating how many times you want the script to
1498 run. The final timing report will include total and per run results.
1484 run. The final timing report will include total and per run results.
1499
1485
1500 For example (testing the script uniq_stable.py):
1486 For example (testing the script uniq_stable.py):
1501
1487
1502 In [1]: run -t uniq_stable
1488 In [1]: run -t uniq_stable
1503
1489
1504 IPython CPU timings (estimated):\\
1490 IPython CPU timings (estimated):\\
1505 User : 0.19597 s.\\
1491 User : 0.19597 s.\\
1506 System: 0.0 s.\\
1492 System: 0.0 s.\\
1507
1493
1508 In [2]: run -t -N5 uniq_stable
1494 In [2]: run -t -N5 uniq_stable
1509
1495
1510 IPython CPU timings (estimated):\\
1496 IPython CPU timings (estimated):\\
1511 Total runs performed: 5\\
1497 Total runs performed: 5\\
1512 Times : Total Per run\\
1498 Times : Total Per run\\
1513 User : 0.910862 s, 0.1821724 s.\\
1499 User : 0.910862 s, 0.1821724 s.\\
1514 System: 0.0 s, 0.0 s.
1500 System: 0.0 s, 0.0 s.
1515
1501
1516 -d: run your program under the control of pdb, the Python debugger.
1502 -d: run your program under the control of pdb, the Python debugger.
1517 This allows you to execute your program step by step, watch variables,
1503 This allows you to execute your program step by step, watch variables,
1518 etc. Internally, what IPython does is similar to calling:
1504 etc. Internally, what IPython does is similar to calling:
1519
1505
1520 pdb.run('execfile("YOURFILENAME")')
1506 pdb.run('execfile("YOURFILENAME")')
1521
1507
1522 with a breakpoint set on line 1 of your file. You can change the line
1508 with a breakpoint set on line 1 of your file. You can change the line
1523 number for this automatic breakpoint to be <N> by using the -bN option
1509 number for this automatic breakpoint to be <N> by using the -bN option
1524 (where N must be an integer). For example:
1510 (where N must be an integer). For example:
1525
1511
1526 %run -d -b40 myscript
1512 %run -d -b40 myscript
1527
1513
1528 will set the first breakpoint at line 40 in myscript.py. Note that
1514 will set the first breakpoint at line 40 in myscript.py. Note that
1529 the first breakpoint must be set on a line which actually does
1515 the first breakpoint must be set on a line which actually does
1530 something (not a comment or docstring) for it to stop execution.
1516 something (not a comment or docstring) for it to stop execution.
1531
1517
1532 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1518 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1533 first enter 'c' (without qoutes) to start execution up to the first
1519 first enter 'c' (without qoutes) to start execution up to the first
1534 breakpoint.
1520 breakpoint.
1535
1521
1536 Entering 'help' gives information about the use of the debugger. You
1522 Entering 'help' gives information about the use of the debugger. You
1537 can easily see pdb's full documentation with "import pdb;pdb.help()"
1523 can easily see pdb's full documentation with "import pdb;pdb.help()"
1538 at a prompt.
1524 at a prompt.
1539
1525
1540 -p: run program under the control of the Python profiler module (which
1526 -p: run program under the control of the Python profiler module (which
1541 prints a detailed report of execution times, function calls, etc).
1527 prints a detailed report of execution times, function calls, etc).
1542
1528
1543 You can pass other options after -p which affect the behavior of the
1529 You can pass other options after -p which affect the behavior of the
1544 profiler itself. See the docs for %prun for details.
1530 profiler itself. See the docs for %prun for details.
1545
1531
1546 In this mode, the program's variables do NOT propagate back to the
1532 In this mode, the program's variables do NOT propagate back to the
1547 IPython interactive namespace (because they remain in the namespace
1533 IPython interactive namespace (because they remain in the namespace
1548 where the profiler executes them).
1534 where the profiler executes them).
1549
1535
1550 Internally this triggers a call to %prun, see its documentation for
1536 Internally this triggers a call to %prun, see its documentation for
1551 details on the options available specifically for profiling.
1537 details on the options available specifically for profiling.
1552
1538
1553 There is one special usage for which the text above doesn't apply:
1539 There is one special usage for which the text above doesn't apply:
1554 if the filename ends with .ipy, the file is run as ipython script,
1540 if the filename ends with .ipy, the file is run as ipython script,
1555 just as if the commands were written on IPython prompt.
1541 just as if the commands were written on IPython prompt.
1556 """
1542 """
1557
1543
1558 # get arguments and set sys.argv for program to be run.
1544 # get arguments and set sys.argv for program to be run.
1559 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1545 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1560 mode='list',list_all=1)
1546 mode='list',list_all=1)
1561
1547
1562 try:
1548 try:
1563 filename = file_finder(arg_lst[0])
1549 filename = file_finder(arg_lst[0])
1564 except IndexError:
1550 except IndexError:
1565 warn('you must provide at least a filename.')
1551 warn('you must provide at least a filename.')
1566 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1552 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1567 return
1553 return
1568 except IOError,msg:
1554 except IOError,msg:
1569 error(msg)
1555 error(msg)
1570 return
1556 return
1571
1557
1572 if filename.lower().endswith('.ipy'):
1558 if filename.lower().endswith('.ipy'):
1573 self.shell.safe_execfile_ipy(filename)
1559 self.shell.safe_execfile_ipy(filename)
1574 return
1560 return
1575
1561
1576 # Control the response to exit() calls made by the script being run
1562 # Control the response to exit() calls made by the script being run
1577 exit_ignore = opts.has_key('e')
1563 exit_ignore = opts.has_key('e')
1578
1564
1579 # Make sure that the running script gets a proper sys.argv as if it
1565 # Make sure that the running script gets a proper sys.argv as if it
1580 # were run from a system shell.
1566 # were run from a system shell.
1581 save_argv = sys.argv # save it for later restoring
1567 save_argv = sys.argv # save it for later restoring
1582 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1568 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1583
1569
1584 if opts.has_key('i'):
1570 if opts.has_key('i'):
1585 # Run in user's interactive namespace
1571 # Run in user's interactive namespace
1586 prog_ns = self.shell.user_ns
1572 prog_ns = self.shell.user_ns
1587 __name__save = self.shell.user_ns['__name__']
1573 __name__save = self.shell.user_ns['__name__']
1588 prog_ns['__name__'] = '__main__'
1574 prog_ns['__name__'] = '__main__'
1589 main_mod = self.shell.new_main_mod(prog_ns)
1575 main_mod = self.shell.new_main_mod(prog_ns)
1590 else:
1576 else:
1591 # Run in a fresh, empty namespace
1577 # Run in a fresh, empty namespace
1592 if opts.has_key('n'):
1578 if opts.has_key('n'):
1593 name = os.path.splitext(os.path.basename(filename))[0]
1579 name = os.path.splitext(os.path.basename(filename))[0]
1594 else:
1580 else:
1595 name = '__main__'
1581 name = '__main__'
1596
1582
1597 main_mod = self.shell.new_main_mod()
1583 main_mod = self.shell.new_main_mod()
1598 prog_ns = main_mod.__dict__
1584 prog_ns = main_mod.__dict__
1599 prog_ns['__name__'] = name
1585 prog_ns['__name__'] = name
1600
1586
1601 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1587 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 # set the __file__ global in the script's namespace
1588 # set the __file__ global in the script's namespace
1603 prog_ns['__file__'] = filename
1589 prog_ns['__file__'] = filename
1604
1590
1605 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1591 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1606 # that, if we overwrite __main__, we replace it at the end
1592 # that, if we overwrite __main__, we replace it at the end
1607 main_mod_name = prog_ns['__name__']
1593 main_mod_name = prog_ns['__name__']
1608
1594
1609 if main_mod_name == '__main__':
1595 if main_mod_name == '__main__':
1610 restore_main = sys.modules['__main__']
1596 restore_main = sys.modules['__main__']
1611 else:
1597 else:
1612 restore_main = False
1598 restore_main = False
1613
1599
1614 # This needs to be undone at the end to prevent holding references to
1600 # This needs to be undone at the end to prevent holding references to
1615 # every single object ever created.
1601 # every single object ever created.
1616 sys.modules[main_mod_name] = main_mod
1602 sys.modules[main_mod_name] = main_mod
1617
1603
1618 stats = None
1604 stats = None
1619 try:
1605 try:
1620 self.shell.save_history()
1606 #self.shell.save_history()
1621
1607
1622 if opts.has_key('p'):
1608 if opts.has_key('p'):
1623 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1609 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 else:
1610 else:
1625 if opts.has_key('d'):
1611 if opts.has_key('d'):
1626 deb = debugger.Pdb(self.shell.colors)
1612 deb = debugger.Pdb(self.shell.colors)
1627 # reset Breakpoint state, which is moronically kept
1613 # reset Breakpoint state, which is moronically kept
1628 # in a class
1614 # in a class
1629 bdb.Breakpoint.next = 1
1615 bdb.Breakpoint.next = 1
1630 bdb.Breakpoint.bplist = {}
1616 bdb.Breakpoint.bplist = {}
1631 bdb.Breakpoint.bpbynumber = [None]
1617 bdb.Breakpoint.bpbynumber = [None]
1632 # Set an initial breakpoint to stop execution
1618 # Set an initial breakpoint to stop execution
1633 maxtries = 10
1619 maxtries = 10
1634 bp = int(opts.get('b',[1])[0])
1620 bp = int(opts.get('b',[1])[0])
1635 checkline = deb.checkline(filename,bp)
1621 checkline = deb.checkline(filename,bp)
1636 if not checkline:
1622 if not checkline:
1637 for bp in range(bp+1,bp+maxtries+1):
1623 for bp in range(bp+1,bp+maxtries+1):
1638 if deb.checkline(filename,bp):
1624 if deb.checkline(filename,bp):
1639 break
1625 break
1640 else:
1626 else:
1641 msg = ("\nI failed to find a valid line to set "
1627 msg = ("\nI failed to find a valid line to set "
1642 "a breakpoint\n"
1628 "a breakpoint\n"
1643 "after trying up to line: %s.\n"
1629 "after trying up to line: %s.\n"
1644 "Please set a valid breakpoint manually "
1630 "Please set a valid breakpoint manually "
1645 "with the -b option." % bp)
1631 "with the -b option." % bp)
1646 error(msg)
1632 error(msg)
1647 return
1633 return
1648 # if we find a good linenumber, set the breakpoint
1634 # if we find a good linenumber, set the breakpoint
1649 deb.do_break('%s:%s' % (filename,bp))
1635 deb.do_break('%s:%s' % (filename,bp))
1650 # Start file run
1636 # Start file run
1651 print "NOTE: Enter 'c' at the",
1637 print "NOTE: Enter 'c' at the",
1652 print "%s prompt to start your script." % deb.prompt
1638 print "%s prompt to start your script." % deb.prompt
1653 try:
1639 try:
1654 deb.run('execfile("%s")' % filename,prog_ns)
1640 deb.run('execfile("%s")' % filename,prog_ns)
1655
1641
1656 except:
1642 except:
1657 etype, value, tb = sys.exc_info()
1643 etype, value, tb = sys.exc_info()
1658 # Skip three frames in the traceback: the %run one,
1644 # Skip three frames in the traceback: the %run one,
1659 # one inside bdb.py, and the command-line typed by the
1645 # one inside bdb.py, and the command-line typed by the
1660 # user (run by exec in pdb itself).
1646 # user (run by exec in pdb itself).
1661 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1647 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 else:
1648 else:
1663 if runner is None:
1649 if runner is None:
1664 runner = self.shell.safe_execfile
1650 runner = self.shell.safe_execfile
1665 if opts.has_key('t'):
1651 if opts.has_key('t'):
1666 # timed execution
1652 # timed execution
1667 try:
1653 try:
1668 nruns = int(opts['N'][0])
1654 nruns = int(opts['N'][0])
1669 if nruns < 1:
1655 if nruns < 1:
1670 error('Number of runs must be >=1')
1656 error('Number of runs must be >=1')
1671 return
1657 return
1672 except (KeyError):
1658 except (KeyError):
1673 nruns = 1
1659 nruns = 1
1674 if nruns == 1:
1660 if nruns == 1:
1675 t0 = clock2()
1661 t0 = clock2()
1676 runner(filename,prog_ns,prog_ns,
1662 runner(filename,prog_ns,prog_ns,
1677 exit_ignore=exit_ignore)
1663 exit_ignore=exit_ignore)
1678 t1 = clock2()
1664 t1 = clock2()
1679 t_usr = t1[0]-t0[0]
1665 t_usr = t1[0]-t0[0]
1680 t_sys = t1[1]-t0[1]
1666 t_sys = t1[1]-t0[1]
1681 print "\nIPython CPU timings (estimated):"
1667 print "\nIPython CPU timings (estimated):"
1682 print " User : %10s s." % t_usr
1668 print " User : %10s s." % t_usr
1683 print " System: %10s s." % t_sys
1669 print " System: %10s s." % t_sys
1684 else:
1670 else:
1685 runs = range(nruns)
1671 runs = range(nruns)
1686 t0 = clock2()
1672 t0 = clock2()
1687 for nr in runs:
1673 for nr in runs:
1688 runner(filename,prog_ns,prog_ns,
1674 runner(filename,prog_ns,prog_ns,
1689 exit_ignore=exit_ignore)
1675 exit_ignore=exit_ignore)
1690 t1 = clock2()
1676 t1 = clock2()
1691 t_usr = t1[0]-t0[0]
1677 t_usr = t1[0]-t0[0]
1692 t_sys = t1[1]-t0[1]
1678 t_sys = t1[1]-t0[1]
1693 print "\nIPython CPU timings (estimated):"
1679 print "\nIPython CPU timings (estimated):"
1694 print "Total runs performed:",nruns
1680 print "Total runs performed:",nruns
1695 print " Times : %10s %10s" % ('Total','Per run')
1681 print " Times : %10s %10s" % ('Total','Per run')
1696 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1682 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1683 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698
1684
1699 else:
1685 else:
1700 # regular execution
1686 # regular execution
1701 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1687 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702
1688
1703 if opts.has_key('i'):
1689 if opts.has_key('i'):
1704 self.shell.user_ns['__name__'] = __name__save
1690 self.shell.user_ns['__name__'] = __name__save
1705 else:
1691 else:
1706 # The shell MUST hold a reference to prog_ns so after %run
1692 # The shell MUST hold a reference to prog_ns so after %run
1707 # exits, the python deletion mechanism doesn't zero it out
1693 # exits, the python deletion mechanism doesn't zero it out
1708 # (leaving dangling references).
1694 # (leaving dangling references).
1709 self.shell.cache_main_mod(prog_ns,filename)
1695 self.shell.cache_main_mod(prog_ns,filename)
1710 # update IPython interactive namespace
1696 # update IPython interactive namespace
1711
1697
1712 # Some forms of read errors on the file may mean the
1698 # Some forms of read errors on the file may mean the
1713 # __name__ key was never set; using pop we don't have to
1699 # __name__ key was never set; using pop we don't have to
1714 # worry about a possible KeyError.
1700 # worry about a possible KeyError.
1715 prog_ns.pop('__name__', None)
1701 prog_ns.pop('__name__', None)
1716
1702
1717 self.shell.user_ns.update(prog_ns)
1703 self.shell.user_ns.update(prog_ns)
1718 finally:
1704 finally:
1719 # It's a bit of a mystery why, but __builtins__ can change from
1705 # It's a bit of a mystery why, but __builtins__ can change from
1720 # being a module to becoming a dict missing some key data after
1706 # being a module to becoming a dict missing some key data after
1721 # %run. As best I can see, this is NOT something IPython is doing
1707 # %run. As best I can see, this is NOT something IPython is doing
1722 # at all, and similar problems have been reported before:
1708 # at all, and similar problems have been reported before:
1723 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1709 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1724 # Since this seems to be done by the interpreter itself, the best
1710 # Since this seems to be done by the interpreter itself, the best
1725 # we can do is to at least restore __builtins__ for the user on
1711 # we can do is to at least restore __builtins__ for the user on
1726 # exit.
1712 # exit.
1727 self.shell.user_ns['__builtins__'] = __builtin__
1713 self.shell.user_ns['__builtins__'] = __builtin__
1728
1714
1729 # Ensure key global structures are restored
1715 # Ensure key global structures are restored
1730 sys.argv = save_argv
1716 sys.argv = save_argv
1731 if restore_main:
1717 if restore_main:
1732 sys.modules['__main__'] = restore_main
1718 sys.modules['__main__'] = restore_main
1733 else:
1719 else:
1734 # Remove from sys.modules the reference to main_mod we'd
1720 # Remove from sys.modules the reference to main_mod we'd
1735 # added. Otherwise it will trap references to objects
1721 # added. Otherwise it will trap references to objects
1736 # contained therein.
1722 # contained therein.
1737 del sys.modules[main_mod_name]
1723 del sys.modules[main_mod_name]
1738
1724
1739 self.shell.reload_history()
1725 #self.shell.reload_history()
1740
1726
1741 return stats
1727 return stats
1742
1728
1743 @testdec.skip_doctest
1729 @testdec.skip_doctest
1744 def magic_timeit(self, parameter_s =''):
1730 def magic_timeit(self, parameter_s =''):
1745 """Time execution of a Python statement or expression
1731 """Time execution of a Python statement or expression
1746
1732
1747 Usage:\\
1733 Usage:\\
1748 %timeit [-n<N> -r<R> [-t|-c]] statement
1734 %timeit [-n<N> -r<R> [-t|-c]] statement
1749
1735
1750 Time execution of a Python statement or expression using the timeit
1736 Time execution of a Python statement or expression using the timeit
1751 module.
1737 module.
1752
1738
1753 Options:
1739 Options:
1754 -n<N>: execute the given statement <N> times in a loop. If this value
1740 -n<N>: execute the given statement <N> times in a loop. If this value
1755 is not given, a fitting value is chosen.
1741 is not given, a fitting value is chosen.
1756
1742
1757 -r<R>: repeat the loop iteration <R> times and take the best result.
1743 -r<R>: repeat the loop iteration <R> times and take the best result.
1758 Default: 3
1744 Default: 3
1759
1745
1760 -t: use time.time to measure the time, which is the default on Unix.
1746 -t: use time.time to measure the time, which is the default on Unix.
1761 This function measures wall time.
1747 This function measures wall time.
1762
1748
1763 -c: use time.clock to measure the time, which is the default on
1749 -c: use time.clock to measure the time, which is the default on
1764 Windows and measures wall time. On Unix, resource.getrusage is used
1750 Windows and measures wall time. On Unix, resource.getrusage is used
1765 instead and returns the CPU user time.
1751 instead and returns the CPU user time.
1766
1752
1767 -p<P>: use a precision of <P> digits to display the timing result.
1753 -p<P>: use a precision of <P> digits to display the timing result.
1768 Default: 3
1754 Default: 3
1769
1755
1770
1756
1771 Examples:
1757 Examples:
1772
1758
1773 In [1]: %timeit pass
1759 In [1]: %timeit pass
1774 10000000 loops, best of 3: 53.3 ns per loop
1760 10000000 loops, best of 3: 53.3 ns per loop
1775
1761
1776 In [2]: u = None
1762 In [2]: u = None
1777
1763
1778 In [3]: %timeit u is None
1764 In [3]: %timeit u is None
1779 10000000 loops, best of 3: 184 ns per loop
1765 10000000 loops, best of 3: 184 ns per loop
1780
1766
1781 In [4]: %timeit -r 4 u == None
1767 In [4]: %timeit -r 4 u == None
1782 1000000 loops, best of 4: 242 ns per loop
1768 1000000 loops, best of 4: 242 ns per loop
1783
1769
1784 In [5]: import time
1770 In [5]: import time
1785
1771
1786 In [6]: %timeit -n1 time.sleep(2)
1772 In [6]: %timeit -n1 time.sleep(2)
1787 1 loops, best of 3: 2 s per loop
1773 1 loops, best of 3: 2 s per loop
1788
1774
1789
1775
1790 The times reported by %timeit will be slightly higher than those
1776 The times reported by %timeit will be slightly higher than those
1791 reported by the timeit.py script when variables are accessed. This is
1777 reported by the timeit.py script when variables are accessed. This is
1792 due to the fact that %timeit executes the statement in the namespace
1778 due to the fact that %timeit executes the statement in the namespace
1793 of the shell, compared with timeit.py, which uses a single setup
1779 of the shell, compared with timeit.py, which uses a single setup
1794 statement to import function or create variables. Generally, the bias
1780 statement to import function or create variables. Generally, the bias
1795 does not matter as long as results from timeit.py are not mixed with
1781 does not matter as long as results from timeit.py are not mixed with
1796 those from %timeit."""
1782 those from %timeit."""
1797
1783
1798 import timeit
1784 import timeit
1799 import math
1785 import math
1800
1786
1801 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1787 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1802 # certain terminals. Until we figure out a robust way of
1788 # certain terminals. Until we figure out a robust way of
1803 # auto-detecting if the terminal can deal with it, use plain 'us' for
1789 # auto-detecting if the terminal can deal with it, use plain 'us' for
1804 # microseconds. I am really NOT happy about disabling the proper
1790 # microseconds. I am really NOT happy about disabling the proper
1805 # 'micro' prefix, but crashing is worse... If anyone knows what the
1791 # 'micro' prefix, but crashing is worse... If anyone knows what the
1806 # right solution for this is, I'm all ears...
1792 # right solution for this is, I'm all ears...
1807 #
1793 #
1808 # Note: using
1794 # Note: using
1809 #
1795 #
1810 # s = u'\xb5'
1796 # s = u'\xb5'
1811 # s.encode(sys.getdefaultencoding())
1797 # s.encode(sys.getdefaultencoding())
1812 #
1798 #
1813 # is not sufficient, as I've seen terminals where that fails but
1799 # is not sufficient, as I've seen terminals where that fails but
1814 # print s
1800 # print s
1815 #
1801 #
1816 # succeeds
1802 # succeeds
1817 #
1803 #
1818 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1804 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1819
1805
1820 #units = [u"s", u"ms",u'\xb5',"ns"]
1806 #units = [u"s", u"ms",u'\xb5',"ns"]
1821 units = [u"s", u"ms",u'us',"ns"]
1807 units = [u"s", u"ms",u'us',"ns"]
1822
1808
1823 scaling = [1, 1e3, 1e6, 1e9]
1809 scaling = [1, 1e3, 1e6, 1e9]
1824
1810
1825 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1811 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1826 posix=False)
1812 posix=False)
1827 if stmt == "":
1813 if stmt == "":
1828 return
1814 return
1829 timefunc = timeit.default_timer
1815 timefunc = timeit.default_timer
1830 number = int(getattr(opts, "n", 0))
1816 number = int(getattr(opts, "n", 0))
1831 repeat = int(getattr(opts, "r", timeit.default_repeat))
1817 repeat = int(getattr(opts, "r", timeit.default_repeat))
1832 precision = int(getattr(opts, "p", 3))
1818 precision = int(getattr(opts, "p", 3))
1833 if hasattr(opts, "t"):
1819 if hasattr(opts, "t"):
1834 timefunc = time.time
1820 timefunc = time.time
1835 if hasattr(opts, "c"):
1821 if hasattr(opts, "c"):
1836 timefunc = clock
1822 timefunc = clock
1837
1823
1838 timer = timeit.Timer(timer=timefunc)
1824 timer = timeit.Timer(timer=timefunc)
1839 # this code has tight coupling to the inner workings of timeit.Timer,
1825 # this code has tight coupling to the inner workings of timeit.Timer,
1840 # but is there a better way to achieve that the code stmt has access
1826 # but is there a better way to achieve that the code stmt has access
1841 # to the shell namespace?
1827 # to the shell namespace?
1842
1828
1843 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1829 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1844 'setup': "pass"}
1830 'setup': "pass"}
1845 # Track compilation time so it can be reported if too long
1831 # Track compilation time so it can be reported if too long
1846 # Minimum time above which compilation time will be reported
1832 # Minimum time above which compilation time will be reported
1847 tc_min = 0.1
1833 tc_min = 0.1
1848
1834
1849 t0 = clock()
1835 t0 = clock()
1850 code = compile(src, "<magic-timeit>", "exec")
1836 code = compile(src, "<magic-timeit>", "exec")
1851 tc = clock()-t0
1837 tc = clock()-t0
1852
1838
1853 ns = {}
1839 ns = {}
1854 exec code in self.shell.user_ns, ns
1840 exec code in self.shell.user_ns, ns
1855 timer.inner = ns["inner"]
1841 timer.inner = ns["inner"]
1856
1842
1857 if number == 0:
1843 if number == 0:
1858 # determine number so that 0.2 <= total time < 2.0
1844 # determine number so that 0.2 <= total time < 2.0
1859 number = 1
1845 number = 1
1860 for i in range(1, 10):
1846 for i in range(1, 10):
1861 if timer.timeit(number) >= 0.2:
1847 if timer.timeit(number) >= 0.2:
1862 break
1848 break
1863 number *= 10
1849 number *= 10
1864
1850
1865 best = min(timer.repeat(repeat, number)) / number
1851 best = min(timer.repeat(repeat, number)) / number
1866
1852
1867 if best > 0.0 and best < 1000.0:
1853 if best > 0.0 and best < 1000.0:
1868 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1854 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1869 elif best >= 1000.0:
1855 elif best >= 1000.0:
1870 order = 0
1856 order = 0
1871 else:
1857 else:
1872 order = 3
1858 order = 3
1873 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1859 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1874 precision,
1860 precision,
1875 best * scaling[order],
1861 best * scaling[order],
1876 units[order])
1862 units[order])
1877 if tc > tc_min:
1863 if tc > tc_min:
1878 print "Compiler time: %.2f s" % tc
1864 print "Compiler time: %.2f s" % tc
1879
1865
1880 @testdec.skip_doctest
1866 @testdec.skip_doctest
1881 def magic_time(self,parameter_s = ''):
1867 def magic_time(self,parameter_s = ''):
1882 """Time execution of a Python statement or expression.
1868 """Time execution of a Python statement or expression.
1883
1869
1884 The CPU and wall clock times are printed, and the value of the
1870 The CPU and wall clock times are printed, and the value of the
1885 expression (if any) is returned. Note that under Win32, system time
1871 expression (if any) is returned. Note that under Win32, system time
1886 is always reported as 0, since it can not be measured.
1872 is always reported as 0, since it can not be measured.
1887
1873
1888 This function provides very basic timing functionality. In Python
1874 This function provides very basic timing functionality. In Python
1889 2.3, the timeit module offers more control and sophistication, so this
1875 2.3, the timeit module offers more control and sophistication, so this
1890 could be rewritten to use it (patches welcome).
1876 could be rewritten to use it (patches welcome).
1891
1877
1892 Some examples:
1878 Some examples:
1893
1879
1894 In [1]: time 2**128
1880 In [1]: time 2**128
1895 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1881 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 Wall time: 0.00
1882 Wall time: 0.00
1897 Out[1]: 340282366920938463463374607431768211456L
1883 Out[1]: 340282366920938463463374607431768211456L
1898
1884
1899 In [2]: n = 1000000
1885 In [2]: n = 1000000
1900
1886
1901 In [3]: time sum(range(n))
1887 In [3]: time sum(range(n))
1902 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1888 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1903 Wall time: 1.37
1889 Wall time: 1.37
1904 Out[3]: 499999500000L
1890 Out[3]: 499999500000L
1905
1891
1906 In [4]: time print 'hello world'
1892 In [4]: time print 'hello world'
1907 hello world
1893 hello world
1908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1909 Wall time: 0.00
1895 Wall time: 0.00
1910
1896
1911 Note that the time needed by Python to compile the given expression
1897 Note that the time needed by Python to compile the given expression
1912 will be reported if it is more than 0.1s. In this example, the
1898 will be reported if it is more than 0.1s. In this example, the
1913 actual exponentiation is done by Python at compilation time, so while
1899 actual exponentiation is done by Python at compilation time, so while
1914 the expression can take a noticeable amount of time to compute, that
1900 the expression can take a noticeable amount of time to compute, that
1915 time is purely due to the compilation:
1901 time is purely due to the compilation:
1916
1902
1917 In [5]: time 3**9999;
1903 In [5]: time 3**9999;
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1904 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 Wall time: 0.00 s
1905 Wall time: 0.00 s
1920
1906
1921 In [6]: time 3**999999;
1907 In [6]: time 3**999999;
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 Wall time: 0.00 s
1909 Wall time: 0.00 s
1924 Compiler : 0.78 s
1910 Compiler : 0.78 s
1925 """
1911 """
1926
1912
1927 # fail immediately if the given expression can't be compiled
1913 # fail immediately if the given expression can't be compiled
1928
1914
1929 expr = self.shell.prefilter(parameter_s,False)
1915 expr = self.shell.prefilter(parameter_s,False)
1930
1916
1931 # Minimum time above which compilation time will be reported
1917 # Minimum time above which compilation time will be reported
1932 tc_min = 0.1
1918 tc_min = 0.1
1933
1919
1934 try:
1920 try:
1935 mode = 'eval'
1921 mode = 'eval'
1936 t0 = clock()
1922 t0 = clock()
1937 code = compile(expr,'<timed eval>',mode)
1923 code = compile(expr,'<timed eval>',mode)
1938 tc = clock()-t0
1924 tc = clock()-t0
1939 except SyntaxError:
1925 except SyntaxError:
1940 mode = 'exec'
1926 mode = 'exec'
1941 t0 = clock()
1927 t0 = clock()
1942 code = compile(expr,'<timed exec>',mode)
1928 code = compile(expr,'<timed exec>',mode)
1943 tc = clock()-t0
1929 tc = clock()-t0
1944 # skew measurement as little as possible
1930 # skew measurement as little as possible
1945 glob = self.shell.user_ns
1931 glob = self.shell.user_ns
1946 clk = clock2
1932 clk = clock2
1947 wtime = time.time
1933 wtime = time.time
1948 # time execution
1934 # time execution
1949 wall_st = wtime()
1935 wall_st = wtime()
1950 if mode=='eval':
1936 if mode=='eval':
1951 st = clk()
1937 st = clk()
1952 out = eval(code,glob)
1938 out = eval(code,glob)
1953 end = clk()
1939 end = clk()
1954 else:
1940 else:
1955 st = clk()
1941 st = clk()
1956 exec code in glob
1942 exec code in glob
1957 end = clk()
1943 end = clk()
1958 out = None
1944 out = None
1959 wall_end = wtime()
1945 wall_end = wtime()
1960 # Compute actual times and report
1946 # Compute actual times and report
1961 wall_time = wall_end-wall_st
1947 wall_time = wall_end-wall_st
1962 cpu_user = end[0]-st[0]
1948 cpu_user = end[0]-st[0]
1963 cpu_sys = end[1]-st[1]
1949 cpu_sys = end[1]-st[1]
1964 cpu_tot = cpu_user+cpu_sys
1950 cpu_tot = cpu_user+cpu_sys
1965 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1951 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1966 (cpu_user,cpu_sys,cpu_tot)
1952 (cpu_user,cpu_sys,cpu_tot)
1967 print "Wall time: %.2f s" % wall_time
1953 print "Wall time: %.2f s" % wall_time
1968 if tc > tc_min:
1954 if tc > tc_min:
1969 print "Compiler : %.2f s" % tc
1955 print "Compiler : %.2f s" % tc
1970 return out
1956 return out
1971
1957
1972 @testdec.skip_doctest
1958 @testdec.skip_doctest
1973 def magic_macro(self,parameter_s = ''):
1959 def magic_macro(self,parameter_s = ''):
1974 """Define a set of input lines as a macro for future re-execution.
1960 """Define a set of input lines as a macro for future re-execution.
1975
1961
1976 Usage:\\
1962 Usage:\\
1977 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1963 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1978
1964
1979 Options:
1965 Options:
1980
1966
1981 -r: use 'raw' input. By default, the 'processed' history is used,
1967 -r: use 'raw' input. By default, the 'processed' history is used,
1982 so that magics are loaded in their transformed version to valid
1968 so that magics are loaded in their transformed version to valid
1983 Python. If this option is given, the raw input as typed as the
1969 Python. If this option is given, the raw input as typed as the
1984 command line is used instead.
1970 command line is used instead.
1985
1971
1986 This will define a global variable called `name` which is a string
1972 This will define a global variable called `name` which is a string
1987 made of joining the slices and lines you specify (n1,n2,... numbers
1973 made of joining the slices and lines you specify (n1,n2,... numbers
1988 above) from your input history into a single string. This variable
1974 above) from your input history into a single string. This variable
1989 acts like an automatic function which re-executes those lines as if
1975 acts like an automatic function which re-executes those lines as if
1990 you had typed them. You just type 'name' at the prompt and the code
1976 you had typed them. You just type 'name' at the prompt and the code
1991 executes.
1977 executes.
1992
1978
1993 The notation for indicating number ranges is: n1-n2 means 'use line
1979 The syntax for indicating input ranges is described in %history.
1994 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1995 using the lines numbered 5,6 and 7.
1996
1980
1997 Note: as a 'hidden' feature, you can also use traditional python slice
1981 Note: as a 'hidden' feature, you can also use traditional python slice
1998 notation, where N:M means numbers N through M-1.
1982 notation, where N:M means numbers N through M-1.
1999
1983
2000 For example, if your history contains (%hist prints it):
1984 For example, if your history contains (%hist prints it):
2001
1985
2002 44: x=1
1986 44: x=1
2003 45: y=3
1987 45: y=3
2004 46: z=x+y
1988 46: z=x+y
2005 47: print x
1989 47: print x
2006 48: a=5
1990 48: a=5
2007 49: print 'x',x,'y',y
1991 49: print 'x',x,'y',y
2008
1992
2009 you can create a macro with lines 44 through 47 (included) and line 49
1993 you can create a macro with lines 44 through 47 (included) and line 49
2010 called my_macro with:
1994 called my_macro with:
2011
1995
2012 In [55]: %macro my_macro 44-47 49
1996 In [55]: %macro my_macro 44-47 49
2013
1997
2014 Now, typing `my_macro` (without quotes) will re-execute all this code
1998 Now, typing `my_macro` (without quotes) will re-execute all this code
2015 in one pass.
1999 in one pass.
2016
2000
2017 You don't need to give the line-numbers in order, and any given line
2001 You don't need to give the line-numbers in order, and any given line
2018 number can appear multiple times. You can assemble macros with any
2002 number can appear multiple times. You can assemble macros with any
2019 lines from your input history in any order.
2003 lines from your input history in any order.
2020
2004
2021 The macro is a simple object which holds its value in an attribute,
2005 The macro is a simple object which holds its value in an attribute,
2022 but IPython's display system checks for macros and executes them as
2006 but IPython's display system checks for macros and executes them as
2023 code instead of printing them when you type their name.
2007 code instead of printing them when you type their name.
2024
2008
2025 You can view a macro's contents by explicitly printing it with:
2009 You can view a macro's contents by explicitly printing it with:
2026
2010
2027 'print macro_name'.
2011 'print macro_name'.
2028
2012
2029 For one-off cases which DON'T contain magic function calls in them you
2013 For one-off cases which DON'T contain magic function calls in them you
2030 can obtain similar results by explicitly executing slices from your
2014 can obtain similar results by explicitly executing slices from your
2031 input history with:
2015 input history with:
2032
2016
2033 In [60]: exec In[44:48]+In[49]"""
2017 In [60]: exec In[44:48]+In[49]"""
2034
2018
2035 opts,args = self.parse_options(parameter_s,'r',mode='list')
2019 opts,args = self.parse_options(parameter_s,'r',mode='list')
2036 if not args:
2020 if not args: # List existing macros
2037 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2021 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2038 macs.sort()
2022 isinstance(v, Macro))
2039 return macs
2040 if len(args) == 1:
2023 if len(args) == 1:
2041 raise UsageError(
2024 raise UsageError(
2042 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2025 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2043 name,ranges = args[0], args[1:]
2026 name, ranges = args[0], " ".join(args[1:])
2044
2027
2045 #print 'rng',ranges # dbg
2028 #print 'rng',ranges # dbg
2046 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2029 lines = self.extract_input_lines(ranges,'r' in opts)
2047 macro = Macro(lines)
2030 macro = Macro(lines)
2048 self.shell.define_macro(name, macro)
2031 self.shell.define_macro(name, macro)
2049 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2032 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2050 print 'Macro contents:'
2033 print 'Macro contents:'
2051 print macro,
2034 print macro,
2052
2035
2053 def magic_save(self,parameter_s = ''):
2036 def magic_save(self,parameter_s = ''):
2054 """Save a set of lines to a given filename.
2037 """Save a set of lines to a given filename.
2055
2038
2056 Usage:\\
2039 Usage:\\
2057 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2040 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2058
2041
2059 Options:
2042 Options:
2060
2043
2061 -r: use 'raw' input. By default, the 'processed' history is used,
2044 -r: use 'raw' input. By default, the 'processed' history is used,
2062 so that magics are loaded in their transformed version to valid
2045 so that magics are loaded in their transformed version to valid
2063 Python. If this option is given, the raw input as typed as the
2046 Python. If this option is given, the raw input as typed as the
2064 command line is used instead.
2047 command line is used instead.
2065
2048
2066 This function uses the same syntax as %macro for line extraction, but
2049 This function uses the same syntax as %history for input ranges,
2067 instead of creating a macro it saves the resulting string to the
2050 then saves the lines to the filename you specify.
2068 filename you specify.
2069
2051
2070 It adds a '.py' extension to the file if you don't do so yourself, and
2052 It adds a '.py' extension to the file if you don't do so yourself, and
2071 it asks for confirmation before overwriting existing files."""
2053 it asks for confirmation before overwriting existing files."""
2072
2054
2073 opts,args = self.parse_options(parameter_s,'r',mode='list')
2055 opts,args = self.parse_options(parameter_s,'r',mode='list')
2074 fname,ranges = args[0], args[1:]
2056 fname,ranges = args[0], " ".join(args[1:])
2075 if not fname.endswith('.py'):
2057 if not fname.endswith('.py'):
2076 fname += '.py'
2058 fname += '.py'
2077 if os.path.isfile(fname):
2059 if os.path.isfile(fname):
2078 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2060 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2079 if ans.lower() not in ['y','yes']:
2061 if ans.lower() not in ['y','yes']:
2080 print 'Operation cancelled.'
2062 print 'Operation cancelled.'
2081 return
2063 return
2082 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2064 cmds = self.extract_input_lines(ranges, 'r' in opts)
2083 f = file(fname,'w')
2065 with open(fname,'w') as f:
2084 f.write(cmds)
2066 f.write(cmds)
2085 f.close()
2086 print 'The following commands were written to file `%s`:' % fname
2067 print 'The following commands were written to file `%s`:' % fname
2087 print cmds
2068 print cmds
2088
2069
2089 def _edit_macro(self,mname,macro):
2070 def _edit_macro(self,mname,macro):
2090 """open an editor with the macro data in a file"""
2071 """open an editor with the macro data in a file"""
2091 filename = self.shell.mktempfile(macro.value)
2072 filename = self.shell.mktempfile(macro.value)
2092 self.shell.hooks.editor(filename)
2073 self.shell.hooks.editor(filename)
2093
2074
2094 # and make a new macro object, to replace the old one
2075 # and make a new macro object, to replace the old one
2095 mfile = open(filename)
2076 mfile = open(filename)
2096 mvalue = mfile.read()
2077 mvalue = mfile.read()
2097 mfile.close()
2078 mfile.close()
2098 self.shell.user_ns[mname] = Macro(mvalue)
2079 self.shell.user_ns[mname] = Macro(mvalue)
2099
2080
2100 def magic_ed(self,parameter_s=''):
2081 def magic_ed(self,parameter_s=''):
2101 """Alias to %edit."""
2082 """Alias to %edit."""
2102 return self.magic_edit(parameter_s)
2083 return self.magic_edit(parameter_s)
2103
2084
2104 @testdec.skip_doctest
2085 @testdec.skip_doctest
2105 def magic_edit(self,parameter_s='',last_call=['','']):
2086 def magic_edit(self,parameter_s='',last_call=['','']):
2106 """Bring up an editor and execute the resulting code.
2087 """Bring up an editor and execute the resulting code.
2107
2088
2108 Usage:
2089 Usage:
2109 %edit [options] [args]
2090 %edit [options] [args]
2110
2091
2111 %edit runs IPython's editor hook. The default version of this hook is
2092 %edit runs IPython's editor hook. The default version of this hook is
2112 set to call the __IPYTHON__.rc.editor command. This is read from your
2093 set to call the __IPYTHON__.rc.editor command. This is read from your
2113 environment variable $EDITOR. If this isn't found, it will default to
2094 environment variable $EDITOR. If this isn't found, it will default to
2114 vi under Linux/Unix and to notepad under Windows. See the end of this
2095 vi under Linux/Unix and to notepad under Windows. See the end of this
2115 docstring for how to change the editor hook.
2096 docstring for how to change the editor hook.
2116
2097
2117 You can also set the value of this editor via the command line option
2098 You can also set the value of this editor via the command line option
2118 '-editor' or in your ipythonrc file. This is useful if you wish to use
2099 '-editor' or in your ipythonrc file. This is useful if you wish to use
2119 specifically for IPython an editor different from your typical default
2100 specifically for IPython an editor different from your typical default
2120 (and for Windows users who typically don't set environment variables).
2101 (and for Windows users who typically don't set environment variables).
2121
2102
2122 This command allows you to conveniently edit multi-line code right in
2103 This command allows you to conveniently edit multi-line code right in
2123 your IPython session.
2104 your IPython session.
2124
2105
2125 If called without arguments, %edit opens up an empty editor with a
2106 If called without arguments, %edit opens up an empty editor with a
2126 temporary file and will execute the contents of this file when you
2107 temporary file and will execute the contents of this file when you
2127 close it (don't forget to save it!).
2108 close it (don't forget to save it!).
2128
2109
2129
2110
2130 Options:
2111 Options:
2131
2112
2132 -n <number>: open the editor at a specified line number. By default,
2113 -n <number>: open the editor at a specified line number. By default,
2133 the IPython editor hook uses the unix syntax 'editor +N filename', but
2114 the IPython editor hook uses the unix syntax 'editor +N filename', but
2134 you can configure this by providing your own modified hook if your
2115 you can configure this by providing your own modified hook if your
2135 favorite editor supports line-number specifications with a different
2116 favorite editor supports line-number specifications with a different
2136 syntax.
2117 syntax.
2137
2118
2138 -p: this will call the editor with the same data as the previous time
2119 -p: this will call the editor with the same data as the previous time
2139 it was used, regardless of how long ago (in your current session) it
2120 it was used, regardless of how long ago (in your current session) it
2140 was.
2121 was.
2141
2122
2142 -r: use 'raw' input. This option only applies to input taken from the
2123 -r: use 'raw' input. This option only applies to input taken from the
2143 user's history. By default, the 'processed' history is used, so that
2124 user's history. By default, the 'processed' history is used, so that
2144 magics are loaded in their transformed version to valid Python. If
2125 magics are loaded in their transformed version to valid Python. If
2145 this option is given, the raw input as typed as the command line is
2126 this option is given, the raw input as typed as the command line is
2146 used instead. When you exit the editor, it will be executed by
2127 used instead. When you exit the editor, it will be executed by
2147 IPython's own processor.
2128 IPython's own processor.
2148
2129
2149 -x: do not execute the edited code immediately upon exit. This is
2130 -x: do not execute the edited code immediately upon exit. This is
2150 mainly useful if you are editing programs which need to be called with
2131 mainly useful if you are editing programs which need to be called with
2151 command line arguments, which you can then do using %run.
2132 command line arguments, which you can then do using %run.
2152
2133
2153
2134
2154 Arguments:
2135 Arguments:
2155
2136
2156 If arguments are given, the following possibilites exist:
2137 If arguments are given, the following possibilites exist:
2138
2139 - If the argument is a filename, IPython will load that into the
2140 editor. It will execute its contents with execfile() when you exit,
2141 loading any code in the file into your interactive namespace.
2157
2142
2158 - The arguments are numbers or pairs of colon-separated numbers (like
2143 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2159 1 4:8 9). These are interpreted as lines of previous input to be
2144 The syntax is the same as in the %history magic.
2160 loaded into the editor. The syntax is the same of the %macro command.
2161
2145
2162 - If the argument doesn't start with a number, it is evaluated as a
2146 - If the argument is a string variable, its contents are loaded
2163 variable and its contents loaded into the editor. You can thus edit
2147 into the editor. You can thus edit any string which contains
2164 any string which contains python code (including the result of
2148 python code (including the result of previous edits).
2165 previous edits).
2166
2149
2167 - If the argument is the name of an object (other than a string),
2150 - If the argument is the name of an object (other than a string),
2168 IPython will try to locate the file where it was defined and open the
2151 IPython will try to locate the file where it was defined and open the
2169 editor at the point where it is defined. You can use `%edit function`
2152 editor at the point where it is defined. You can use `%edit function`
2170 to load an editor exactly at the point where 'function' is defined,
2153 to load an editor exactly at the point where 'function' is defined,
2171 edit it and have the file be executed automatically.
2154 edit it and have the file be executed automatically.
2172
2155
2173 If the object is a macro (see %macro for details), this opens up your
2156 If the object is a macro (see %macro for details), this opens up your
2174 specified editor with a temporary file containing the macro's data.
2157 specified editor with a temporary file containing the macro's data.
2175 Upon exit, the macro is reloaded with the contents of the file.
2158 Upon exit, the macro is reloaded with the contents of the file.
2176
2159
2177 Note: opening at an exact line is only supported under Unix, and some
2160 Note: opening at an exact line is only supported under Unix, and some
2178 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2161 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2179 '+NUMBER' parameter necessary for this feature. Good editors like
2162 '+NUMBER' parameter necessary for this feature. Good editors like
2180 (X)Emacs, vi, jed, pico and joe all do.
2163 (X)Emacs, vi, jed, pico and joe all do.
2181
2164
2182 - If the argument is not found as a variable, IPython will look for a
2183 file with that name (adding .py if necessary) and load it into the
2184 editor. It will execute its contents with execfile() when you exit,
2185 loading any code in the file into your interactive namespace.
2186
2187 After executing your code, %edit will return as output the code you
2165 After executing your code, %edit will return as output the code you
2188 typed in the editor (except when it was an existing file). This way
2166 typed in the editor (except when it was an existing file). This way
2189 you can reload the code in further invocations of %edit as a variable,
2167 you can reload the code in further invocations of %edit as a variable,
2190 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2168 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2191 the output.
2169 the output.
2192
2170
2193 Note that %edit is also available through the alias %ed.
2171 Note that %edit is also available through the alias %ed.
2194
2172
2195 This is an example of creating a simple function inside the editor and
2173 This is an example of creating a simple function inside the editor and
2196 then modifying it. First, start up the editor:
2174 then modifying it. First, start up the editor:
2197
2175
2198 In [1]: ed
2176 In [1]: ed
2199 Editing... done. Executing edited code...
2177 Editing... done. Executing edited code...
2200 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2178 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2201
2179
2202 We can then call the function foo():
2180 We can then call the function foo():
2203
2181
2204 In [2]: foo()
2182 In [2]: foo()
2205 foo() was defined in an editing session
2183 foo() was defined in an editing session
2206
2184
2207 Now we edit foo. IPython automatically loads the editor with the
2185 Now we edit foo. IPython automatically loads the editor with the
2208 (temporary) file where foo() was previously defined:
2186 (temporary) file where foo() was previously defined:
2209
2187
2210 In [3]: ed foo
2188 In [3]: ed foo
2211 Editing... done. Executing edited code...
2189 Editing... done. Executing edited code...
2212
2190
2213 And if we call foo() again we get the modified version:
2191 And if we call foo() again we get the modified version:
2214
2192
2215 In [4]: foo()
2193 In [4]: foo()
2216 foo() has now been changed!
2194 foo() has now been changed!
2217
2195
2218 Here is an example of how to edit a code snippet successive
2196 Here is an example of how to edit a code snippet successive
2219 times. First we call the editor:
2197 times. First we call the editor:
2220
2198
2221 In [5]: ed
2199 In [5]: ed
2222 Editing... done. Executing edited code...
2200 Editing... done. Executing edited code...
2223 hello
2201 hello
2224 Out[5]: "print 'hello'n"
2202 Out[5]: "print 'hello'n"
2225
2203
2226 Now we call it again with the previous output (stored in _):
2204 Now we call it again with the previous output (stored in _):
2227
2205
2228 In [6]: ed _
2206 In [6]: ed _
2229 Editing... done. Executing edited code...
2207 Editing... done. Executing edited code...
2230 hello world
2208 hello world
2231 Out[6]: "print 'hello world'n"
2209 Out[6]: "print 'hello world'n"
2232
2210
2233 Now we call it with the output #8 (stored in _8, also as Out[8]):
2211 Now we call it with the output #8 (stored in _8, also as Out[8]):
2234
2212
2235 In [7]: ed _8
2213 In [7]: ed _8
2236 Editing... done. Executing edited code...
2214 Editing... done. Executing edited code...
2237 hello again
2215 hello again
2238 Out[7]: "print 'hello again'n"
2216 Out[7]: "print 'hello again'n"
2239
2217
2240
2218
2241 Changing the default editor hook:
2219 Changing the default editor hook:
2242
2220
2243 If you wish to write your own editor hook, you can put it in a
2221 If you wish to write your own editor hook, you can put it in a
2244 configuration file which you load at startup time. The default hook
2222 configuration file which you load at startup time. The default hook
2245 is defined in the IPython.core.hooks module, and you can use that as a
2223 is defined in the IPython.core.hooks module, and you can use that as a
2246 starting example for further modifications. That file also has
2224 starting example for further modifications. That file also has
2247 general instructions on how to set a new hook for use once you've
2225 general instructions on how to set a new hook for use once you've
2248 defined it."""
2226 defined it."""
2249
2227
2250 # FIXME: This function has become a convoluted mess. It needs a
2228 # FIXME: This function has become a convoluted mess. It needs a
2251 # ground-up rewrite with clean, simple logic.
2229 # ground-up rewrite with clean, simple logic.
2252
2230
2253 def make_filename(arg):
2231 def make_filename(arg):
2254 "Make a filename from the given args"
2232 "Make a filename from the given args"
2255 try:
2233 try:
2256 filename = get_py_filename(arg)
2234 filename = get_py_filename(arg)
2257 except IOError:
2235 except IOError:
2258 if args.endswith('.py'):
2236 if args.endswith('.py'):
2259 filename = arg
2237 filename = arg
2260 else:
2238 else:
2261 filename = None
2239 filename = None
2262 return filename
2240 return filename
2263
2241
2264 # custom exceptions
2242 # custom exceptions
2265 class DataIsObject(Exception): pass
2243 class DataIsObject(Exception): pass
2266
2244
2267 opts,args = self.parse_options(parameter_s,'prxn:')
2245 opts,args = self.parse_options(parameter_s,'prxn:')
2268 # Set a few locals from the options for convenience:
2246 # Set a few locals from the options for convenience:
2269 opts_p = opts.has_key('p')
2247 opts_prev = 'p' in opts
2270 opts_r = opts.has_key('r')
2248 opts_raw = 'r' in opts
2271
2249
2272 # Default line number value
2250 # Default line number value
2273 lineno = opts.get('n',None)
2251 lineno = opts.get('n',None)
2274
2252
2275 if opts_p:
2253 if opts_prev:
2276 args = '_%s' % last_call[0]
2254 args = '_%s' % last_call[0]
2277 if not self.shell.user_ns.has_key(args):
2255 if not self.shell.user_ns.has_key(args):
2278 args = last_call[1]
2256 args = last_call[1]
2279
2257
2280 # use last_call to remember the state of the previous call, but don't
2258 # use last_call to remember the state of the previous call, but don't
2281 # let it be clobbered by successive '-p' calls.
2259 # let it be clobbered by successive '-p' calls.
2282 try:
2260 try:
2283 last_call[0] = self.shell.displayhook.prompt_count
2261 last_call[0] = self.shell.displayhook.prompt_count
2284 if not opts_p:
2262 if not opts_prev:
2285 last_call[1] = parameter_s
2263 last_call[1] = parameter_s
2286 except:
2264 except:
2287 pass
2265 pass
2288
2266
2289 # by default this is done with temp files, except when the given
2267 # by default this is done with temp files, except when the given
2290 # arg is a filename
2268 # arg is a filename
2291 use_temp = 1
2269 use_temp = True
2292
2270
2293 if re.match(r'\d',args):
2271 data = ''
2294 # Mode where user specifies ranges of lines, like in %macro.
2272 if args.endswith('.py'):
2295 # This means that you can't edit files whose names begin with
2296 # numbers this way. Tough.
2297 ranges = args.split()
2298 data = ''.join(self.extract_input_slices(ranges,opts_r))
2299 elif args.endswith('.py'):
2300 filename = make_filename(args)
2273 filename = make_filename(args)
2301 data = ''
2274 use_temp = False
2302 use_temp = 0
2303 elif args:
2275 elif args:
2304 try:
2276 # Mode where user specifies ranges of lines, like in %macro.
2305 # Load the parameter given as a variable. If not a string,
2277 data = self.extract_input_lines(args, opts_raw)
2306 # process it as an object instead (below)
2278 if not data:
2307
2279 try:
2308 #print '*** args',args,'type',type(args) # dbg
2280 # Load the parameter given as a variable. If not a string,
2309 data = eval(args,self.shell.user_ns)
2281 # process it as an object instead (below)
2310 if not type(data) in StringTypes:
2311 raise DataIsObject
2312
2313 except (NameError,SyntaxError):
2314 # given argument is not a variable, try as a filename
2315 filename = make_filename(args)
2316 if filename is None:
2317 warn("Argument given (%s) can't be found as a variable "
2318 "or as a filename." % args)
2319 return
2320
2282
2321 data = ''
2283 #print '*** args',args,'type',type(args) # dbg
2322 use_temp = 0
2284 data = eval(args, self.shell.user_ns)
2323 except DataIsObject:
2285 if not isinstance(data, basestring):
2286 raise DataIsObject
2324
2287
2325 # macros have a special edit function
2288 except (NameError,SyntaxError):
2326 if isinstance(data,Macro):
2289 # given argument is not a variable, try as a filename
2327 self._edit_macro(args,data)
2328 return
2329
2330 # For objects, try to edit the file where they are defined
2331 try:
2332 filename = inspect.getabsfile(data)
2333 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2334 # class created by %edit? Try to find source
2335 # by looking for method definitions instead, the
2336 # __module__ in those classes is FakeModule.
2337 attrs = [getattr(data, aname) for aname in dir(data)]
2338 for attr in attrs:
2339 if not inspect.ismethod(attr):
2340 continue
2341 filename = inspect.getabsfile(attr)
2342 if filename and 'fakemodule' not in filename.lower():
2343 # change the attribute to be the edit target instead
2344 data = attr
2345 break
2346
2347 datafile = 1
2348 except TypeError:
2349 filename = make_filename(args)
2290 filename = make_filename(args)
2350 datafile = 1
2291 if filename is None:
2351 warn('Could not find file where `%s` is defined.\n'
2292 warn("Argument given (%s) can't be found as a variable "
2352 'Opening a file named `%s`' % (args,filename))
2293 "or as a filename." % args)
2353 # Now, make sure we can actually read the source (if it was in
2294 return
2354 # a temp file it's gone by now).
2295 use_temp = False
2355 if datafile:
2296
2297 except DataIsObject:
2298 # macros have a special edit function
2299 if isinstance(data, Macro):
2300 self._edit_macro(args,data)
2301 return
2302
2303 # For objects, try to edit the file where they are defined
2356 try:
2304 try:
2357 if lineno is None:
2305 filename = inspect.getabsfile(data)
2358 lineno = inspect.getsourcelines(data)[1]
2306 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2359 except IOError:
2307 # class created by %edit? Try to find source
2308 # by looking for method definitions instead, the
2309 # __module__ in those classes is FakeModule.
2310 attrs = [getattr(data, aname) for aname in dir(data)]
2311 for attr in attrs:
2312 if not inspect.ismethod(attr):
2313 continue
2314 filename = inspect.getabsfile(attr)
2315 if filename and 'fakemodule' not in filename.lower():
2316 # change the attribute to be the edit target instead
2317 data = attr
2318 break
2319
2320 datafile = 1
2321 except TypeError:
2360 filename = make_filename(args)
2322 filename = make_filename(args)
2361 if filename is None:
2323 datafile = 1
2362 warn('The file `%s` where `%s` was defined cannot '
2324 warn('Could not find file where `%s` is defined.\n'
2363 'be read.' % (filename,data))
2325 'Opening a file named `%s`' % (args,filename))
2364 return
2326 # Now, make sure we can actually read the source (if it was in
2365 use_temp = 0
2327 # a temp file it's gone by now).
2366 else:
2328 if datafile:
2367 data = ''
2329 try:
2330 if lineno is None:
2331 lineno = inspect.getsourcelines(data)[1]
2332 except IOError:
2333 filename = make_filename(args)
2334 if filename is None:
2335 warn('The file `%s` where `%s` was defined cannot '
2336 'be read.' % (filename,data))
2337 return
2338 use_temp = False
2368
2339
2369 if use_temp:
2340 if use_temp:
2370 filename = self.shell.mktempfile(data)
2341 filename = self.shell.mktempfile(data)
2371 print 'IPython will make a temporary file named:',filename
2342 print 'IPython will make a temporary file named:',filename
2372
2343
2373 # do actual editing here
2344 # do actual editing here
2374 print 'Editing...',
2345 print 'Editing...',
2375 sys.stdout.flush()
2346 sys.stdout.flush()
2376 try:
2347 try:
2377 # Quote filenames that may have spaces in them
2348 # Quote filenames that may have spaces in them
2378 if ' ' in filename:
2349 if ' ' in filename:
2379 filename = "%s" % filename
2350 filename = "%s" % filename
2380 self.shell.hooks.editor(filename,lineno)
2351 self.shell.hooks.editor(filename,lineno)
2381 except TryNext:
2352 except TryNext:
2382 warn('Could not open editor')
2353 warn('Could not open editor')
2383 return
2354 return
2384
2355
2385 # XXX TODO: should this be generalized for all string vars?
2356 # XXX TODO: should this be generalized for all string vars?
2386 # For now, this is special-cased to blocks created by cpaste
2357 # For now, this is special-cased to blocks created by cpaste
2387 if args.strip() == 'pasted_block':
2358 if args.strip() == 'pasted_block':
2388 self.shell.user_ns['pasted_block'] = file_read(filename)
2359 self.shell.user_ns['pasted_block'] = file_read(filename)
2389
2360
2390 if opts.has_key('x'): # -x prevents actual execution
2361 if 'x' in opts: # -x prevents actual execution
2391 print
2362 print
2392 else:
2363 else:
2393 print 'done. Executing edited code...'
2364 print 'done. Executing edited code...'
2394 if opts_r:
2365 if opts_raw:
2395 self.shell.run_cell(file_read(filename))
2366 self.shell.run_cell(file_read(filename),
2367 store_history=False)
2396 else:
2368 else:
2397 self.shell.safe_execfile(filename,self.shell.user_ns,
2369 self.shell.safe_execfile(filename,self.shell.user_ns,
2398 self.shell.user_ns)
2370 self.shell.user_ns)
2399
2371
2400
2372
2401 if use_temp:
2373 if use_temp:
2402 try:
2374 try:
2403 return open(filename).read()
2375 return open(filename).read()
2404 except IOError,msg:
2376 except IOError,msg:
2405 if msg.filename == filename:
2377 if msg.filename == filename:
2406 warn('File not found. Did you forget to save?')
2378 warn('File not found. Did you forget to save?')
2407 return
2379 return
2408 else:
2380 else:
2409 self.shell.showtraceback()
2381 self.shell.showtraceback()
2410
2382
2411 def magic_xmode(self,parameter_s = ''):
2383 def magic_xmode(self,parameter_s = ''):
2412 """Switch modes for the exception handlers.
2384 """Switch modes for the exception handlers.
2413
2385
2414 Valid modes: Plain, Context and Verbose.
2386 Valid modes: Plain, Context and Verbose.
2415
2387
2416 If called without arguments, acts as a toggle."""
2388 If called without arguments, acts as a toggle."""
2417
2389
2418 def xmode_switch_err(name):
2390 def xmode_switch_err(name):
2419 warn('Error changing %s exception modes.\n%s' %
2391 warn('Error changing %s exception modes.\n%s' %
2420 (name,sys.exc_info()[1]))
2392 (name,sys.exc_info()[1]))
2421
2393
2422 shell = self.shell
2394 shell = self.shell
2423 new_mode = parameter_s.strip().capitalize()
2395 new_mode = parameter_s.strip().capitalize()
2424 try:
2396 try:
2425 shell.InteractiveTB.set_mode(mode=new_mode)
2397 shell.InteractiveTB.set_mode(mode=new_mode)
2426 print 'Exception reporting mode:',shell.InteractiveTB.mode
2398 print 'Exception reporting mode:',shell.InteractiveTB.mode
2427 except:
2399 except:
2428 xmode_switch_err('user')
2400 xmode_switch_err('user')
2429
2401
2430 def magic_colors(self,parameter_s = ''):
2402 def magic_colors(self,parameter_s = ''):
2431 """Switch color scheme for prompts, info system and exception handlers.
2403 """Switch color scheme for prompts, info system and exception handlers.
2432
2404
2433 Currently implemented schemes: NoColor, Linux, LightBG.
2405 Currently implemented schemes: NoColor, Linux, LightBG.
2434
2406
2435 Color scheme names are not case-sensitive.
2407 Color scheme names are not case-sensitive.
2436
2408
2437 Examples
2409 Examples
2438 --------
2410 --------
2439 To get a plain black and white terminal::
2411 To get a plain black and white terminal::
2440
2412
2441 %colors nocolor
2413 %colors nocolor
2442 """
2414 """
2443
2415
2444 def color_switch_err(name):
2416 def color_switch_err(name):
2445 warn('Error changing %s color schemes.\n%s' %
2417 warn('Error changing %s color schemes.\n%s' %
2446 (name,sys.exc_info()[1]))
2418 (name,sys.exc_info()[1]))
2447
2419
2448
2420
2449 new_scheme = parameter_s.strip()
2421 new_scheme = parameter_s.strip()
2450 if not new_scheme:
2422 if not new_scheme:
2451 raise UsageError(
2423 raise UsageError(
2452 "%colors: you must specify a color scheme. See '%colors?'")
2424 "%colors: you must specify a color scheme. See '%colors?'")
2453 return
2425 return
2454 # local shortcut
2426 # local shortcut
2455 shell = self.shell
2427 shell = self.shell
2456
2428
2457 import IPython.utils.rlineimpl as readline
2429 import IPython.utils.rlineimpl as readline
2458
2430
2459 if not readline.have_readline and sys.platform == "win32":
2431 if not readline.have_readline and sys.platform == "win32":
2460 msg = """\
2432 msg = """\
2461 Proper color support under MS Windows requires the pyreadline library.
2433 Proper color support under MS Windows requires the pyreadline library.
2462 You can find it at:
2434 You can find it at:
2463 http://ipython.scipy.org/moin/PyReadline/Intro
2435 http://ipython.scipy.org/moin/PyReadline/Intro
2464 Gary's readline needs the ctypes module, from:
2436 Gary's readline needs the ctypes module, from:
2465 http://starship.python.net/crew/theller/ctypes
2437 http://starship.python.net/crew/theller/ctypes
2466 (Note that ctypes is already part of Python versions 2.5 and newer).
2438 (Note that ctypes is already part of Python versions 2.5 and newer).
2467
2439
2468 Defaulting color scheme to 'NoColor'"""
2440 Defaulting color scheme to 'NoColor'"""
2469 new_scheme = 'NoColor'
2441 new_scheme = 'NoColor'
2470 warn(msg)
2442 warn(msg)
2471
2443
2472 # readline option is 0
2444 # readline option is 0
2473 if not shell.has_readline:
2445 if not shell.has_readline:
2474 new_scheme = 'NoColor'
2446 new_scheme = 'NoColor'
2475
2447
2476 # Set prompt colors
2448 # Set prompt colors
2477 try:
2449 try:
2478 shell.displayhook.set_colors(new_scheme)
2450 shell.displayhook.set_colors(new_scheme)
2479 except:
2451 except:
2480 color_switch_err('prompt')
2452 color_switch_err('prompt')
2481 else:
2453 else:
2482 shell.colors = \
2454 shell.colors = \
2483 shell.displayhook.color_table.active_scheme_name
2455 shell.displayhook.color_table.active_scheme_name
2484 # Set exception colors
2456 # Set exception colors
2485 try:
2457 try:
2486 shell.InteractiveTB.set_colors(scheme = new_scheme)
2458 shell.InteractiveTB.set_colors(scheme = new_scheme)
2487 shell.SyntaxTB.set_colors(scheme = new_scheme)
2459 shell.SyntaxTB.set_colors(scheme = new_scheme)
2488 except:
2460 except:
2489 color_switch_err('exception')
2461 color_switch_err('exception')
2490
2462
2491 # Set info (for 'object?') colors
2463 # Set info (for 'object?') colors
2492 if shell.color_info:
2464 if shell.color_info:
2493 try:
2465 try:
2494 shell.inspector.set_active_scheme(new_scheme)
2466 shell.inspector.set_active_scheme(new_scheme)
2495 except:
2467 except:
2496 color_switch_err('object inspector')
2468 color_switch_err('object inspector')
2497 else:
2469 else:
2498 shell.inspector.set_active_scheme('NoColor')
2470 shell.inspector.set_active_scheme('NoColor')
2499
2471
2500 def magic_pprint(self, parameter_s=''):
2472 def magic_pprint(self, parameter_s=''):
2501 """Toggle pretty printing on/off."""
2473 """Toggle pretty printing on/off."""
2502 ptformatter = self.shell.display_formatter.formatters['text/plain']
2474 ptformatter = self.shell.display_formatter.formatters['text/plain']
2503 ptformatter.pprint = bool(1 - ptformatter.pprint)
2475 ptformatter.pprint = bool(1 - ptformatter.pprint)
2504 print 'Pretty printing has been turned', \
2476 print 'Pretty printing has been turned', \
2505 ['OFF','ON'][ptformatter.pprint]
2477 ['OFF','ON'][ptformatter.pprint]
2506
2478
2507 def magic_Exit(self, parameter_s=''):
2479 def magic_Exit(self, parameter_s=''):
2508 """Exit IPython."""
2480 """Exit IPython."""
2509
2481
2510 self.shell.ask_exit()
2482 self.shell.ask_exit()
2511
2483
2512 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2484 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2513 magic_exit = magic_quit = magic_Quit = magic_Exit
2485 magic_exit = magic_quit = magic_Quit = magic_Exit
2514
2486
2515 #......................................................................
2487 #......................................................................
2516 # Functions to implement unix shell-type things
2488 # Functions to implement unix shell-type things
2517
2489
2518 @testdec.skip_doctest
2490 @testdec.skip_doctest
2519 def magic_alias(self, parameter_s = ''):
2491 def magic_alias(self, parameter_s = ''):
2520 """Define an alias for a system command.
2492 """Define an alias for a system command.
2521
2493
2522 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2494 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2523
2495
2524 Then, typing 'alias_name params' will execute the system command 'cmd
2496 Then, typing 'alias_name params' will execute the system command 'cmd
2525 params' (from your underlying operating system).
2497 params' (from your underlying operating system).
2526
2498
2527 Aliases have lower precedence than magic functions and Python normal
2499 Aliases have lower precedence than magic functions and Python normal
2528 variables, so if 'foo' is both a Python variable and an alias, the
2500 variables, so if 'foo' is both a Python variable and an alias, the
2529 alias can not be executed until 'del foo' removes the Python variable.
2501 alias can not be executed until 'del foo' removes the Python variable.
2530
2502
2531 You can use the %l specifier in an alias definition to represent the
2503 You can use the %l specifier in an alias definition to represent the
2532 whole line when the alias is called. For example:
2504 whole line when the alias is called. For example:
2533
2505
2534 In [2]: alias bracket echo "Input in brackets: <%l>"
2506 In [2]: alias bracket echo "Input in brackets: <%l>"
2535 In [3]: bracket hello world
2507 In [3]: bracket hello world
2536 Input in brackets: <hello world>
2508 Input in brackets: <hello world>
2537
2509
2538 You can also define aliases with parameters using %s specifiers (one
2510 You can also define aliases with parameters using %s specifiers (one
2539 per parameter):
2511 per parameter):
2540
2512
2541 In [1]: alias parts echo first %s second %s
2513 In [1]: alias parts echo first %s second %s
2542 In [2]: %parts A B
2514 In [2]: %parts A B
2543 first A second B
2515 first A second B
2544 In [3]: %parts A
2516 In [3]: %parts A
2545 Incorrect number of arguments: 2 expected.
2517 Incorrect number of arguments: 2 expected.
2546 parts is an alias to: 'echo first %s second %s'
2518 parts is an alias to: 'echo first %s second %s'
2547
2519
2548 Note that %l and %s are mutually exclusive. You can only use one or
2520 Note that %l and %s are mutually exclusive. You can only use one or
2549 the other in your aliases.
2521 the other in your aliases.
2550
2522
2551 Aliases expand Python variables just like system calls using ! or !!
2523 Aliases expand Python variables just like system calls using ! or !!
2552 do: all expressions prefixed with '$' get expanded. For details of
2524 do: all expressions prefixed with '$' get expanded. For details of
2553 the semantic rules, see PEP-215:
2525 the semantic rules, see PEP-215:
2554 http://www.python.org/peps/pep-0215.html. This is the library used by
2526 http://www.python.org/peps/pep-0215.html. This is the library used by
2555 IPython for variable expansion. If you want to access a true shell
2527 IPython for variable expansion. If you want to access a true shell
2556 variable, an extra $ is necessary to prevent its expansion by IPython:
2528 variable, an extra $ is necessary to prevent its expansion by IPython:
2557
2529
2558 In [6]: alias show echo
2530 In [6]: alias show echo
2559 In [7]: PATH='A Python string'
2531 In [7]: PATH='A Python string'
2560 In [8]: show $PATH
2532 In [8]: show $PATH
2561 A Python string
2533 A Python string
2562 In [9]: show $$PATH
2534 In [9]: show $$PATH
2563 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2535 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2564
2536
2565 You can use the alias facility to acess all of $PATH. See the %rehash
2537 You can use the alias facility to acess all of $PATH. See the %rehash
2566 and %rehashx functions, which automatically create aliases for the
2538 and %rehashx functions, which automatically create aliases for the
2567 contents of your $PATH.
2539 contents of your $PATH.
2568
2540
2569 If called with no parameters, %alias prints the current alias table."""
2541 If called with no parameters, %alias prints the current alias table."""
2570
2542
2571 par = parameter_s.strip()
2543 par = parameter_s.strip()
2572 if not par:
2544 if not par:
2573 stored = self.db.get('stored_aliases', {} )
2545 stored = self.db.get('stored_aliases', {} )
2574 aliases = sorted(self.shell.alias_manager.aliases)
2546 aliases = sorted(self.shell.alias_manager.aliases)
2575 # for k, v in stored:
2547 # for k, v in stored:
2576 # atab.append(k, v[0])
2548 # atab.append(k, v[0])
2577
2549
2578 print "Total number of aliases:", len(aliases)
2550 print "Total number of aliases:", len(aliases)
2579 sys.stdout.flush()
2551 sys.stdout.flush()
2580 return aliases
2552 return aliases
2581
2553
2582 # Now try to define a new one
2554 # Now try to define a new one
2583 try:
2555 try:
2584 alias,cmd = par.split(None, 1)
2556 alias,cmd = par.split(None, 1)
2585 except:
2557 except:
2586 print oinspect.getdoc(self.magic_alias)
2558 print oinspect.getdoc(self.magic_alias)
2587 else:
2559 else:
2588 self.shell.alias_manager.soft_define_alias(alias, cmd)
2560 self.shell.alias_manager.soft_define_alias(alias, cmd)
2589 # end magic_alias
2561 # end magic_alias
2590
2562
2591 def magic_unalias(self, parameter_s = ''):
2563 def magic_unalias(self, parameter_s = ''):
2592 """Remove an alias"""
2564 """Remove an alias"""
2593
2565
2594 aname = parameter_s.strip()
2566 aname = parameter_s.strip()
2595 self.shell.alias_manager.undefine_alias(aname)
2567 self.shell.alias_manager.undefine_alias(aname)
2596 stored = self.db.get('stored_aliases', {} )
2568 stored = self.db.get('stored_aliases', {} )
2597 if aname in stored:
2569 if aname in stored:
2598 print "Removing %stored alias",aname
2570 print "Removing %stored alias",aname
2599 del stored[aname]
2571 del stored[aname]
2600 self.db['stored_aliases'] = stored
2572 self.db['stored_aliases'] = stored
2601
2573
2602 def magic_rehashx(self, parameter_s = ''):
2574 def magic_rehashx(self, parameter_s = ''):
2603 """Update the alias table with all executable files in $PATH.
2575 """Update the alias table with all executable files in $PATH.
2604
2576
2605 This version explicitly checks that every entry in $PATH is a file
2577 This version explicitly checks that every entry in $PATH is a file
2606 with execute access (os.X_OK), so it is much slower than %rehash.
2578 with execute access (os.X_OK), so it is much slower than %rehash.
2607
2579
2608 Under Windows, it checks executability as a match agains a
2580 Under Windows, it checks executability as a match agains a
2609 '|'-separated string of extensions, stored in the IPython config
2581 '|'-separated string of extensions, stored in the IPython config
2610 variable win_exec_ext. This defaults to 'exe|com|bat'.
2582 variable win_exec_ext. This defaults to 'exe|com|bat'.
2611
2583
2612 This function also resets the root module cache of module completer,
2584 This function also resets the root module cache of module completer,
2613 used on slow filesystems.
2585 used on slow filesystems.
2614 """
2586 """
2615 from IPython.core.alias import InvalidAliasError
2587 from IPython.core.alias import InvalidAliasError
2616
2588
2617 # for the benefit of module completer in ipy_completers.py
2589 # for the benefit of module completer in ipy_completers.py
2618 del self.db['rootmodules']
2590 del self.db['rootmodules']
2619
2591
2620 path = [os.path.abspath(os.path.expanduser(p)) for p in
2592 path = [os.path.abspath(os.path.expanduser(p)) for p in
2621 os.environ.get('PATH','').split(os.pathsep)]
2593 os.environ.get('PATH','').split(os.pathsep)]
2622 path = filter(os.path.isdir,path)
2594 path = filter(os.path.isdir,path)
2623
2595
2624 syscmdlist = []
2596 syscmdlist = []
2625 # Now define isexec in a cross platform manner.
2597 # Now define isexec in a cross platform manner.
2626 if os.name == 'posix':
2598 if os.name == 'posix':
2627 isexec = lambda fname:os.path.isfile(fname) and \
2599 isexec = lambda fname:os.path.isfile(fname) and \
2628 os.access(fname,os.X_OK)
2600 os.access(fname,os.X_OK)
2629 else:
2601 else:
2630 try:
2602 try:
2631 winext = os.environ['pathext'].replace(';','|').replace('.','')
2603 winext = os.environ['pathext'].replace(';','|').replace('.','')
2632 except KeyError:
2604 except KeyError:
2633 winext = 'exe|com|bat|py'
2605 winext = 'exe|com|bat|py'
2634 if 'py' not in winext:
2606 if 'py' not in winext:
2635 winext += '|py'
2607 winext += '|py'
2636 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2608 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2637 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2609 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2638 savedir = os.getcwd()
2610 savedir = os.getcwd()
2639
2611
2640 # Now walk the paths looking for executables to alias.
2612 # Now walk the paths looking for executables to alias.
2641 try:
2613 try:
2642 # write the whole loop for posix/Windows so we don't have an if in
2614 # write the whole loop for posix/Windows so we don't have an if in
2643 # the innermost part
2615 # the innermost part
2644 if os.name == 'posix':
2616 if os.name == 'posix':
2645 for pdir in path:
2617 for pdir in path:
2646 os.chdir(pdir)
2618 os.chdir(pdir)
2647 for ff in os.listdir(pdir):
2619 for ff in os.listdir(pdir):
2648 if isexec(ff):
2620 if isexec(ff):
2649 try:
2621 try:
2650 # Removes dots from the name since ipython
2622 # Removes dots from the name since ipython
2651 # will assume names with dots to be python.
2623 # will assume names with dots to be python.
2652 self.shell.alias_manager.define_alias(
2624 self.shell.alias_manager.define_alias(
2653 ff.replace('.',''), ff)
2625 ff.replace('.',''), ff)
2654 except InvalidAliasError:
2626 except InvalidAliasError:
2655 pass
2627 pass
2656 else:
2628 else:
2657 syscmdlist.append(ff)
2629 syscmdlist.append(ff)
2658 else:
2630 else:
2659 no_alias = self.shell.alias_manager.no_alias
2631 no_alias = self.shell.alias_manager.no_alias
2660 for pdir in path:
2632 for pdir in path:
2661 os.chdir(pdir)
2633 os.chdir(pdir)
2662 for ff in os.listdir(pdir):
2634 for ff in os.listdir(pdir):
2663 base, ext = os.path.splitext(ff)
2635 base, ext = os.path.splitext(ff)
2664 if isexec(ff) and base.lower() not in no_alias:
2636 if isexec(ff) and base.lower() not in no_alias:
2665 if ext.lower() == '.exe':
2637 if ext.lower() == '.exe':
2666 ff = base
2638 ff = base
2667 try:
2639 try:
2668 # Removes dots from the name since ipython
2640 # Removes dots from the name since ipython
2669 # will assume names with dots to be python.
2641 # will assume names with dots to be python.
2670 self.shell.alias_manager.define_alias(
2642 self.shell.alias_manager.define_alias(
2671 base.lower().replace('.',''), ff)
2643 base.lower().replace('.',''), ff)
2672 except InvalidAliasError:
2644 except InvalidAliasError:
2673 pass
2645 pass
2674 syscmdlist.append(ff)
2646 syscmdlist.append(ff)
2675 db = self.db
2647 db = self.db
2676 db['syscmdlist'] = syscmdlist
2648 db['syscmdlist'] = syscmdlist
2677 finally:
2649 finally:
2678 os.chdir(savedir)
2650 os.chdir(savedir)
2679
2651
2680 @testdec.skip_doctest
2652 @testdec.skip_doctest
2681 def magic_pwd(self, parameter_s = ''):
2653 def magic_pwd(self, parameter_s = ''):
2682 """Return the current working directory path.
2654 """Return the current working directory path.
2683
2655
2684 Examples
2656 Examples
2685 --------
2657 --------
2686 ::
2658 ::
2687
2659
2688 In [9]: pwd
2660 In [9]: pwd
2689 Out[9]: '/home/tsuser/sprint/ipython'
2661 Out[9]: '/home/tsuser/sprint/ipython'
2690 """
2662 """
2691 return os.getcwd()
2663 return os.getcwd()
2692
2664
2693 @testdec.skip_doctest
2665 @testdec.skip_doctest
2694 def magic_cd(self, parameter_s=''):
2666 def magic_cd(self, parameter_s=''):
2695 """Change the current working directory.
2667 """Change the current working directory.
2696
2668
2697 This command automatically maintains an internal list of directories
2669 This command automatically maintains an internal list of directories
2698 you visit during your IPython session, in the variable _dh. The
2670 you visit during your IPython session, in the variable _dh. The
2699 command %dhist shows this history nicely formatted. You can also
2671 command %dhist shows this history nicely formatted. You can also
2700 do 'cd -<tab>' to see directory history conveniently.
2672 do 'cd -<tab>' to see directory history conveniently.
2701
2673
2702 Usage:
2674 Usage:
2703
2675
2704 cd 'dir': changes to directory 'dir'.
2676 cd 'dir': changes to directory 'dir'.
2705
2677
2706 cd -: changes to the last visited directory.
2678 cd -: changes to the last visited directory.
2707
2679
2708 cd -<n>: changes to the n-th directory in the directory history.
2680 cd -<n>: changes to the n-th directory in the directory history.
2709
2681
2710 cd --foo: change to directory that matches 'foo' in history
2682 cd --foo: change to directory that matches 'foo' in history
2711
2683
2712 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2684 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2713 (note: cd <bookmark_name> is enough if there is no
2685 (note: cd <bookmark_name> is enough if there is no
2714 directory <bookmark_name>, but a bookmark with the name exists.)
2686 directory <bookmark_name>, but a bookmark with the name exists.)
2715 'cd -b <tab>' allows you to tab-complete bookmark names.
2687 'cd -b <tab>' allows you to tab-complete bookmark names.
2716
2688
2717 Options:
2689 Options:
2718
2690
2719 -q: quiet. Do not print the working directory after the cd command is
2691 -q: quiet. Do not print the working directory after the cd command is
2720 executed. By default IPython's cd command does print this directory,
2692 executed. By default IPython's cd command does print this directory,
2721 since the default prompts do not display path information.
2693 since the default prompts do not display path information.
2722
2694
2723 Note that !cd doesn't work for this purpose because the shell where
2695 Note that !cd doesn't work for this purpose because the shell where
2724 !command runs is immediately discarded after executing 'command'.
2696 !command runs is immediately discarded after executing 'command'.
2725
2697
2726 Examples
2698 Examples
2727 --------
2699 --------
2728 ::
2700 ::
2729
2701
2730 In [10]: cd parent/child
2702 In [10]: cd parent/child
2731 /home/tsuser/parent/child
2703 /home/tsuser/parent/child
2732 """
2704 """
2733
2705
2734 parameter_s = parameter_s.strip()
2706 parameter_s = parameter_s.strip()
2735 #bkms = self.shell.persist.get("bookmarks",{})
2707 #bkms = self.shell.persist.get("bookmarks",{})
2736
2708
2737 oldcwd = os.getcwd()
2709 oldcwd = os.getcwd()
2738 numcd = re.match(r'(-)(\d+)$',parameter_s)
2710 numcd = re.match(r'(-)(\d+)$',parameter_s)
2739 # jump in directory history by number
2711 # jump in directory history by number
2740 if numcd:
2712 if numcd:
2741 nn = int(numcd.group(2))
2713 nn = int(numcd.group(2))
2742 try:
2714 try:
2743 ps = self.shell.user_ns['_dh'][nn]
2715 ps = self.shell.user_ns['_dh'][nn]
2744 except IndexError:
2716 except IndexError:
2745 print 'The requested directory does not exist in history.'
2717 print 'The requested directory does not exist in history.'
2746 return
2718 return
2747 else:
2719 else:
2748 opts = {}
2720 opts = {}
2749 elif parameter_s.startswith('--'):
2721 elif parameter_s.startswith('--'):
2750 ps = None
2722 ps = None
2751 fallback = None
2723 fallback = None
2752 pat = parameter_s[2:]
2724 pat = parameter_s[2:]
2753 dh = self.shell.user_ns['_dh']
2725 dh = self.shell.user_ns['_dh']
2754 # first search only by basename (last component)
2726 # first search only by basename (last component)
2755 for ent in reversed(dh):
2727 for ent in reversed(dh):
2756 if pat in os.path.basename(ent) and os.path.isdir(ent):
2728 if pat in os.path.basename(ent) and os.path.isdir(ent):
2757 ps = ent
2729 ps = ent
2758 break
2730 break
2759
2731
2760 if fallback is None and pat in ent and os.path.isdir(ent):
2732 if fallback is None and pat in ent and os.path.isdir(ent):
2761 fallback = ent
2733 fallback = ent
2762
2734
2763 # if we have no last part match, pick the first full path match
2735 # if we have no last part match, pick the first full path match
2764 if ps is None:
2736 if ps is None:
2765 ps = fallback
2737 ps = fallback
2766
2738
2767 if ps is None:
2739 if ps is None:
2768 print "No matching entry in directory history"
2740 print "No matching entry in directory history"
2769 return
2741 return
2770 else:
2742 else:
2771 opts = {}
2743 opts = {}
2772
2744
2773
2745
2774 else:
2746 else:
2775 #turn all non-space-escaping backslashes to slashes,
2747 #turn all non-space-escaping backslashes to slashes,
2776 # for c:\windows\directory\names\
2748 # for c:\windows\directory\names\
2777 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2749 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2778 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2750 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2779 # jump to previous
2751 # jump to previous
2780 if ps == '-':
2752 if ps == '-':
2781 try:
2753 try:
2782 ps = self.shell.user_ns['_dh'][-2]
2754 ps = self.shell.user_ns['_dh'][-2]
2783 except IndexError:
2755 except IndexError:
2784 raise UsageError('%cd -: No previous directory to change to.')
2756 raise UsageError('%cd -: No previous directory to change to.')
2785 # jump to bookmark if needed
2757 # jump to bookmark if needed
2786 else:
2758 else:
2787 if not os.path.isdir(ps) or opts.has_key('b'):
2759 if not os.path.isdir(ps) or opts.has_key('b'):
2788 bkms = self.db.get('bookmarks', {})
2760 bkms = self.db.get('bookmarks', {})
2789
2761
2790 if bkms.has_key(ps):
2762 if bkms.has_key(ps):
2791 target = bkms[ps]
2763 target = bkms[ps]
2792 print '(bookmark:%s) -> %s' % (ps,target)
2764 print '(bookmark:%s) -> %s' % (ps,target)
2793 ps = target
2765 ps = target
2794 else:
2766 else:
2795 if opts.has_key('b'):
2767 if opts.has_key('b'):
2796 raise UsageError("Bookmark '%s' not found. "
2768 raise UsageError("Bookmark '%s' not found. "
2797 "Use '%%bookmark -l' to see your bookmarks." % ps)
2769 "Use '%%bookmark -l' to see your bookmarks." % ps)
2798
2770
2799 # at this point ps should point to the target dir
2771 # at this point ps should point to the target dir
2800 if ps:
2772 if ps:
2801 try:
2773 try:
2802 os.chdir(os.path.expanduser(ps))
2774 os.chdir(os.path.expanduser(ps))
2803 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2775 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2804 set_term_title('IPython: ' + abbrev_cwd())
2776 set_term_title('IPython: ' + abbrev_cwd())
2805 except OSError:
2777 except OSError:
2806 print sys.exc_info()[1]
2778 print sys.exc_info()[1]
2807 else:
2779 else:
2808 cwd = os.getcwd()
2780 cwd = os.getcwd()
2809 dhist = self.shell.user_ns['_dh']
2781 dhist = self.shell.user_ns['_dh']
2810 if oldcwd != cwd:
2782 if oldcwd != cwd:
2811 dhist.append(cwd)
2783 dhist.append(cwd)
2812 self.db['dhist'] = compress_dhist(dhist)[-100:]
2784 self.db['dhist'] = compress_dhist(dhist)[-100:]
2813
2785
2814 else:
2786 else:
2815 os.chdir(self.shell.home_dir)
2787 os.chdir(self.shell.home_dir)
2816 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2788 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2817 set_term_title('IPython: ' + '~')
2789 set_term_title('IPython: ' + '~')
2818 cwd = os.getcwd()
2790 cwd = os.getcwd()
2819 dhist = self.shell.user_ns['_dh']
2791 dhist = self.shell.user_ns['_dh']
2820
2792
2821 if oldcwd != cwd:
2793 if oldcwd != cwd:
2822 dhist.append(cwd)
2794 dhist.append(cwd)
2823 self.db['dhist'] = compress_dhist(dhist)[-100:]
2795 self.db['dhist'] = compress_dhist(dhist)[-100:]
2824 if not 'q' in opts and self.shell.user_ns['_dh']:
2796 if not 'q' in opts and self.shell.user_ns['_dh']:
2825 print self.shell.user_ns['_dh'][-1]
2797 print self.shell.user_ns['_dh'][-1]
2826
2798
2827
2799
2828 def magic_env(self, parameter_s=''):
2800 def magic_env(self, parameter_s=''):
2829 """List environment variables."""
2801 """List environment variables."""
2830
2802
2831 return os.environ.data
2803 return os.environ.data
2832
2804
2833 def magic_pushd(self, parameter_s=''):
2805 def magic_pushd(self, parameter_s=''):
2834 """Place the current dir on stack and change directory.
2806 """Place the current dir on stack and change directory.
2835
2807
2836 Usage:\\
2808 Usage:\\
2837 %pushd ['dirname']
2809 %pushd ['dirname']
2838 """
2810 """
2839
2811
2840 dir_s = self.shell.dir_stack
2812 dir_s = self.shell.dir_stack
2841 tgt = os.path.expanduser(parameter_s)
2813 tgt = os.path.expanduser(parameter_s)
2842 cwd = os.getcwd().replace(self.home_dir,'~')
2814 cwd = os.getcwd().replace(self.home_dir,'~')
2843 if tgt:
2815 if tgt:
2844 self.magic_cd(parameter_s)
2816 self.magic_cd(parameter_s)
2845 dir_s.insert(0,cwd)
2817 dir_s.insert(0,cwd)
2846 return self.magic_dirs()
2818 return self.magic_dirs()
2847
2819
2848 def magic_popd(self, parameter_s=''):
2820 def magic_popd(self, parameter_s=''):
2849 """Change to directory popped off the top of the stack.
2821 """Change to directory popped off the top of the stack.
2850 """
2822 """
2851 if not self.shell.dir_stack:
2823 if not self.shell.dir_stack:
2852 raise UsageError("%popd on empty stack")
2824 raise UsageError("%popd on empty stack")
2853 top = self.shell.dir_stack.pop(0)
2825 top = self.shell.dir_stack.pop(0)
2854 self.magic_cd(top)
2826 self.magic_cd(top)
2855 print "popd ->",top
2827 print "popd ->",top
2856
2828
2857 def magic_dirs(self, parameter_s=''):
2829 def magic_dirs(self, parameter_s=''):
2858 """Return the current directory stack."""
2830 """Return the current directory stack."""
2859
2831
2860 return self.shell.dir_stack
2832 return self.shell.dir_stack
2861
2833
2862 def magic_dhist(self, parameter_s=''):
2834 def magic_dhist(self, parameter_s=''):
2863 """Print your history of visited directories.
2835 """Print your history of visited directories.
2864
2836
2865 %dhist -> print full history\\
2837 %dhist -> print full history\\
2866 %dhist n -> print last n entries only\\
2838 %dhist n -> print last n entries only\\
2867 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2839 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2868
2840
2869 This history is automatically maintained by the %cd command, and
2841 This history is automatically maintained by the %cd command, and
2870 always available as the global list variable _dh. You can use %cd -<n>
2842 always available as the global list variable _dh. You can use %cd -<n>
2871 to go to directory number <n>.
2843 to go to directory number <n>.
2872
2844
2873 Note that most of time, you should view directory history by entering
2845 Note that most of time, you should view directory history by entering
2874 cd -<TAB>.
2846 cd -<TAB>.
2875
2847
2876 """
2848 """
2877
2849
2878 dh = self.shell.user_ns['_dh']
2850 dh = self.shell.user_ns['_dh']
2879 if parameter_s:
2851 if parameter_s:
2880 try:
2852 try:
2881 args = map(int,parameter_s.split())
2853 args = map(int,parameter_s.split())
2882 except:
2854 except:
2883 self.arg_err(Magic.magic_dhist)
2855 self.arg_err(Magic.magic_dhist)
2884 return
2856 return
2885 if len(args) == 1:
2857 if len(args) == 1:
2886 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2858 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2887 elif len(args) == 2:
2859 elif len(args) == 2:
2888 ini,fin = args
2860 ini,fin = args
2889 else:
2861 else:
2890 self.arg_err(Magic.magic_dhist)
2862 self.arg_err(Magic.magic_dhist)
2891 return
2863 return
2892 else:
2864 else:
2893 ini,fin = 0,len(dh)
2865 ini,fin = 0,len(dh)
2894 nlprint(dh,
2866 nlprint(dh,
2895 header = 'Directory history (kept in _dh)',
2867 header = 'Directory history (kept in _dh)',
2896 start=ini,stop=fin)
2868 start=ini,stop=fin)
2897
2869
2898 @testdec.skip_doctest
2870 @testdec.skip_doctest
2899 def magic_sc(self, parameter_s=''):
2871 def magic_sc(self, parameter_s=''):
2900 """Shell capture - execute a shell command and capture its output.
2872 """Shell capture - execute a shell command and capture its output.
2901
2873
2902 DEPRECATED. Suboptimal, retained for backwards compatibility.
2874 DEPRECATED. Suboptimal, retained for backwards compatibility.
2903
2875
2904 You should use the form 'var = !command' instead. Example:
2876 You should use the form 'var = !command' instead. Example:
2905
2877
2906 "%sc -l myfiles = ls ~" should now be written as
2878 "%sc -l myfiles = ls ~" should now be written as
2907
2879
2908 "myfiles = !ls ~"
2880 "myfiles = !ls ~"
2909
2881
2910 myfiles.s, myfiles.l and myfiles.n still apply as documented
2882 myfiles.s, myfiles.l and myfiles.n still apply as documented
2911 below.
2883 below.
2912
2884
2913 --
2885 --
2914 %sc [options] varname=command
2886 %sc [options] varname=command
2915
2887
2916 IPython will run the given command using commands.getoutput(), and
2888 IPython will run the given command using commands.getoutput(), and
2917 will then update the user's interactive namespace with a variable
2889 will then update the user's interactive namespace with a variable
2918 called varname, containing the value of the call. Your command can
2890 called varname, containing the value of the call. Your command can
2919 contain shell wildcards, pipes, etc.
2891 contain shell wildcards, pipes, etc.
2920
2892
2921 The '=' sign in the syntax is mandatory, and the variable name you
2893 The '=' sign in the syntax is mandatory, and the variable name you
2922 supply must follow Python's standard conventions for valid names.
2894 supply must follow Python's standard conventions for valid names.
2923
2895
2924 (A special format without variable name exists for internal use)
2896 (A special format without variable name exists for internal use)
2925
2897
2926 Options:
2898 Options:
2927
2899
2928 -l: list output. Split the output on newlines into a list before
2900 -l: list output. Split the output on newlines into a list before
2929 assigning it to the given variable. By default the output is stored
2901 assigning it to the given variable. By default the output is stored
2930 as a single string.
2902 as a single string.
2931
2903
2932 -v: verbose. Print the contents of the variable.
2904 -v: verbose. Print the contents of the variable.
2933
2905
2934 In most cases you should not need to split as a list, because the
2906 In most cases you should not need to split as a list, because the
2935 returned value is a special type of string which can automatically
2907 returned value is a special type of string which can automatically
2936 provide its contents either as a list (split on newlines) or as a
2908 provide its contents either as a list (split on newlines) or as a
2937 space-separated string. These are convenient, respectively, either
2909 space-separated string. These are convenient, respectively, either
2938 for sequential processing or to be passed to a shell command.
2910 for sequential processing or to be passed to a shell command.
2939
2911
2940 For example:
2912 For example:
2941
2913
2942 # all-random
2914 # all-random
2943
2915
2944 # Capture into variable a
2916 # Capture into variable a
2945 In [1]: sc a=ls *py
2917 In [1]: sc a=ls *py
2946
2918
2947 # a is a string with embedded newlines
2919 # a is a string with embedded newlines
2948 In [2]: a
2920 In [2]: a
2949 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2921 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2950
2922
2951 # which can be seen as a list:
2923 # which can be seen as a list:
2952 In [3]: a.l
2924 In [3]: a.l
2953 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2925 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2954
2926
2955 # or as a whitespace-separated string:
2927 # or as a whitespace-separated string:
2956 In [4]: a.s
2928 In [4]: a.s
2957 Out[4]: 'setup.py win32_manual_post_install.py'
2929 Out[4]: 'setup.py win32_manual_post_install.py'
2958
2930
2959 # a.s is useful to pass as a single command line:
2931 # a.s is useful to pass as a single command line:
2960 In [5]: !wc -l $a.s
2932 In [5]: !wc -l $a.s
2961 146 setup.py
2933 146 setup.py
2962 130 win32_manual_post_install.py
2934 130 win32_manual_post_install.py
2963 276 total
2935 276 total
2964
2936
2965 # while the list form is useful to loop over:
2937 # while the list form is useful to loop over:
2966 In [6]: for f in a.l:
2938 In [6]: for f in a.l:
2967 ...: !wc -l $f
2939 ...: !wc -l $f
2968 ...:
2940 ...:
2969 146 setup.py
2941 146 setup.py
2970 130 win32_manual_post_install.py
2942 130 win32_manual_post_install.py
2971
2943
2972 Similiarly, the lists returned by the -l option are also special, in
2944 Similiarly, the lists returned by the -l option are also special, in
2973 the sense that you can equally invoke the .s attribute on them to
2945 the sense that you can equally invoke the .s attribute on them to
2974 automatically get a whitespace-separated string from their contents:
2946 automatically get a whitespace-separated string from their contents:
2975
2947
2976 In [7]: sc -l b=ls *py
2948 In [7]: sc -l b=ls *py
2977
2949
2978 In [8]: b
2950 In [8]: b
2979 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2951 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2980
2952
2981 In [9]: b.s
2953 In [9]: b.s
2982 Out[9]: 'setup.py win32_manual_post_install.py'
2954 Out[9]: 'setup.py win32_manual_post_install.py'
2983
2955
2984 In summary, both the lists and strings used for ouptut capture have
2956 In summary, both the lists and strings used for ouptut capture have
2985 the following special attributes:
2957 the following special attributes:
2986
2958
2987 .l (or .list) : value as list.
2959 .l (or .list) : value as list.
2988 .n (or .nlstr): value as newline-separated string.
2960 .n (or .nlstr): value as newline-separated string.
2989 .s (or .spstr): value as space-separated string.
2961 .s (or .spstr): value as space-separated string.
2990 """
2962 """
2991
2963
2992 opts,args = self.parse_options(parameter_s,'lv')
2964 opts,args = self.parse_options(parameter_s,'lv')
2993 # Try to get a variable name and command to run
2965 # Try to get a variable name and command to run
2994 try:
2966 try:
2995 # the variable name must be obtained from the parse_options
2967 # the variable name must be obtained from the parse_options
2996 # output, which uses shlex.split to strip options out.
2968 # output, which uses shlex.split to strip options out.
2997 var,_ = args.split('=',1)
2969 var,_ = args.split('=',1)
2998 var = var.strip()
2970 var = var.strip()
2999 # But the the command has to be extracted from the original input
2971 # But the the command has to be extracted from the original input
3000 # parameter_s, not on what parse_options returns, to avoid the
2972 # parameter_s, not on what parse_options returns, to avoid the
3001 # quote stripping which shlex.split performs on it.
2973 # quote stripping which shlex.split performs on it.
3002 _,cmd = parameter_s.split('=',1)
2974 _,cmd = parameter_s.split('=',1)
3003 except ValueError:
2975 except ValueError:
3004 var,cmd = '',''
2976 var,cmd = '',''
3005 # If all looks ok, proceed
2977 # If all looks ok, proceed
3006 split = 'l' in opts
2978 split = 'l' in opts
3007 out = self.shell.getoutput(cmd, split=split)
2979 out = self.shell.getoutput(cmd, split=split)
3008 if opts.has_key('v'):
2980 if opts.has_key('v'):
3009 print '%s ==\n%s' % (var,pformat(out))
2981 print '%s ==\n%s' % (var,pformat(out))
3010 if var:
2982 if var:
3011 self.shell.user_ns.update({var:out})
2983 self.shell.user_ns.update({var:out})
3012 else:
2984 else:
3013 return out
2985 return out
3014
2986
3015 def magic_sx(self, parameter_s=''):
2987 def magic_sx(self, parameter_s=''):
3016 """Shell execute - run a shell command and capture its output.
2988 """Shell execute - run a shell command and capture its output.
3017
2989
3018 %sx command
2990 %sx command
3019
2991
3020 IPython will run the given command using commands.getoutput(), and
2992 IPython will run the given command using commands.getoutput(), and
3021 return the result formatted as a list (split on '\\n'). Since the
2993 return the result formatted as a list (split on '\\n'). Since the
3022 output is _returned_, it will be stored in ipython's regular output
2994 output is _returned_, it will be stored in ipython's regular output
3023 cache Out[N] and in the '_N' automatic variables.
2995 cache Out[N] and in the '_N' automatic variables.
3024
2996
3025 Notes:
2997 Notes:
3026
2998
3027 1) If an input line begins with '!!', then %sx is automatically
2999 1) If an input line begins with '!!', then %sx is automatically
3028 invoked. That is, while:
3000 invoked. That is, while:
3029 !ls
3001 !ls
3030 causes ipython to simply issue system('ls'), typing
3002 causes ipython to simply issue system('ls'), typing
3031 !!ls
3003 !!ls
3032 is a shorthand equivalent to:
3004 is a shorthand equivalent to:
3033 %sx ls
3005 %sx ls
3034
3006
3035 2) %sx differs from %sc in that %sx automatically splits into a list,
3007 2) %sx differs from %sc in that %sx automatically splits into a list,
3036 like '%sc -l'. The reason for this is to make it as easy as possible
3008 like '%sc -l'. The reason for this is to make it as easy as possible
3037 to process line-oriented shell output via further python commands.
3009 to process line-oriented shell output via further python commands.
3038 %sc is meant to provide much finer control, but requires more
3010 %sc is meant to provide much finer control, but requires more
3039 typing.
3011 typing.
3040
3012
3041 3) Just like %sc -l, this is a list with special attributes:
3013 3) Just like %sc -l, this is a list with special attributes:
3042
3014
3043 .l (or .list) : value as list.
3015 .l (or .list) : value as list.
3044 .n (or .nlstr): value as newline-separated string.
3016 .n (or .nlstr): value as newline-separated string.
3045 .s (or .spstr): value as whitespace-separated string.
3017 .s (or .spstr): value as whitespace-separated string.
3046
3018
3047 This is very useful when trying to use such lists as arguments to
3019 This is very useful when trying to use such lists as arguments to
3048 system commands."""
3020 system commands."""
3049
3021
3050 if parameter_s:
3022 if parameter_s:
3051 return self.shell.getoutput(parameter_s)
3023 return self.shell.getoutput(parameter_s)
3052
3024
3053 def magic_r(self, parameter_s=''):
3054 """Repeat previous input.
3055
3056 Note: Consider using the more powerfull %rep instead!
3057
3058 If given an argument, repeats the previous command which starts with
3059 the same string, otherwise it just repeats the previous input.
3060
3061 Shell escaped commands (with ! as first character) are not recognized
3062 by this system, only pure python code and magic commands.
3063 """
3064
3065 start = parameter_s.strip()
3066 esc_magic = ESC_MAGIC
3067 # Identify magic commands even if automagic is on (which means
3068 # the in-memory version is different from that typed by the user).
3069 if self.shell.automagic:
3070 start_magic = esc_magic+start
3071 else:
3072 start_magic = start
3073 # Look through the input history in reverse
3074 for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1):
3075 input = self.shell.history_manager.input_hist_parsed[n]
3076 # skip plain 'r' lines so we don't recurse to infinity
3077 if input != '_ip.magic("r")\n' and \
3078 (input.startswith(start) or input.startswith(start_magic)):
3079 #print 'match',`input` # dbg
3080 print 'Executing:',input,
3081 self.shell.run_cell(input)
3082 return
3083 print 'No previous input matching `%s` found.' % start
3084
3085
3025
3086 def magic_bookmark(self, parameter_s=''):
3026 def magic_bookmark(self, parameter_s=''):
3087 """Manage IPython's bookmark system.
3027 """Manage IPython's bookmark system.
3088
3028
3089 %bookmark <name> - set bookmark to current dir
3029 %bookmark <name> - set bookmark to current dir
3090 %bookmark <name> <dir> - set bookmark to <dir>
3030 %bookmark <name> <dir> - set bookmark to <dir>
3091 %bookmark -l - list all bookmarks
3031 %bookmark -l - list all bookmarks
3092 %bookmark -d <name> - remove bookmark
3032 %bookmark -d <name> - remove bookmark
3093 %bookmark -r - remove all bookmarks
3033 %bookmark -r - remove all bookmarks
3094
3034
3095 You can later on access a bookmarked folder with:
3035 You can later on access a bookmarked folder with:
3096 %cd -b <name>
3036 %cd -b <name>
3097 or simply '%cd <name>' if there is no directory called <name> AND
3037 or simply '%cd <name>' if there is no directory called <name> AND
3098 there is such a bookmark defined.
3038 there is such a bookmark defined.
3099
3039
3100 Your bookmarks persist through IPython sessions, but they are
3040 Your bookmarks persist through IPython sessions, but they are
3101 associated with each profile."""
3041 associated with each profile."""
3102
3042
3103 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3043 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3104 if len(args) > 2:
3044 if len(args) > 2:
3105 raise UsageError("%bookmark: too many arguments")
3045 raise UsageError("%bookmark: too many arguments")
3106
3046
3107 bkms = self.db.get('bookmarks',{})
3047 bkms = self.db.get('bookmarks',{})
3108
3048
3109 if opts.has_key('d'):
3049 if opts.has_key('d'):
3110 try:
3050 try:
3111 todel = args[0]
3051 todel = args[0]
3112 except IndexError:
3052 except IndexError:
3113 raise UsageError(
3053 raise UsageError(
3114 "%bookmark -d: must provide a bookmark to delete")
3054 "%bookmark -d: must provide a bookmark to delete")
3115 else:
3055 else:
3116 try:
3056 try:
3117 del bkms[todel]
3057 del bkms[todel]
3118 except KeyError:
3058 except KeyError:
3119 raise UsageError(
3059 raise UsageError(
3120 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3060 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3121
3061
3122 elif opts.has_key('r'):
3062 elif opts.has_key('r'):
3123 bkms = {}
3063 bkms = {}
3124 elif opts.has_key('l'):
3064 elif opts.has_key('l'):
3125 bks = bkms.keys()
3065 bks = bkms.keys()
3126 bks.sort()
3066 bks.sort()
3127 if bks:
3067 if bks:
3128 size = max(map(len,bks))
3068 size = max(map(len,bks))
3129 else:
3069 else:
3130 size = 0
3070 size = 0
3131 fmt = '%-'+str(size)+'s -> %s'
3071 fmt = '%-'+str(size)+'s -> %s'
3132 print 'Current bookmarks:'
3072 print 'Current bookmarks:'
3133 for bk in bks:
3073 for bk in bks:
3134 print fmt % (bk,bkms[bk])
3074 print fmt % (bk,bkms[bk])
3135 else:
3075 else:
3136 if not args:
3076 if not args:
3137 raise UsageError("%bookmark: You must specify the bookmark name")
3077 raise UsageError("%bookmark: You must specify the bookmark name")
3138 elif len(args)==1:
3078 elif len(args)==1:
3139 bkms[args[0]] = os.getcwd()
3079 bkms[args[0]] = os.getcwd()
3140 elif len(args)==2:
3080 elif len(args)==2:
3141 bkms[args[0]] = args[1]
3081 bkms[args[0]] = args[1]
3142 self.db['bookmarks'] = bkms
3082 self.db['bookmarks'] = bkms
3143
3083
3144 def magic_pycat(self, parameter_s=''):
3084 def magic_pycat(self, parameter_s=''):
3145 """Show a syntax-highlighted file through a pager.
3085 """Show a syntax-highlighted file through a pager.
3146
3086
3147 This magic is similar to the cat utility, but it will assume the file
3087 This magic is similar to the cat utility, but it will assume the file
3148 to be Python source and will show it with syntax highlighting. """
3088 to be Python source and will show it with syntax highlighting. """
3149
3089
3150 try:
3090 try:
3151 filename = get_py_filename(parameter_s)
3091 filename = get_py_filename(parameter_s)
3152 cont = file_read(filename)
3092 cont = file_read(filename)
3153 except IOError:
3093 except IOError:
3154 try:
3094 try:
3155 cont = eval(parameter_s,self.user_ns)
3095 cont = eval(parameter_s,self.user_ns)
3156 except NameError:
3096 except NameError:
3157 cont = None
3097 cont = None
3158 if cont is None:
3098 if cont is None:
3159 print "Error: no such file or variable"
3099 print "Error: no such file or variable"
3160 return
3100 return
3161
3101
3162 page.page(self.shell.pycolorize(cont))
3102 page.page(self.shell.pycolorize(cont))
3163
3103
3164 def _rerun_pasted(self):
3104 def _rerun_pasted(self):
3165 """ Rerun a previously pasted command.
3105 """ Rerun a previously pasted command.
3166 """
3106 """
3167 b = self.user_ns.get('pasted_block', None)
3107 b = self.user_ns.get('pasted_block', None)
3168 if b is None:
3108 if b is None:
3169 raise UsageError('No previous pasted block available')
3109 raise UsageError('No previous pasted block available')
3170 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3110 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3171 exec b in self.user_ns
3111 exec b in self.user_ns
3172
3112
3173 def _get_pasted_lines(self, sentinel):
3113 def _get_pasted_lines(self, sentinel):
3174 """ Yield pasted lines until the user enters the given sentinel value.
3114 """ Yield pasted lines until the user enters the given sentinel value.
3175 """
3115 """
3176 from IPython.core import interactiveshell
3116 from IPython.core import interactiveshell
3177 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3117 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3178 while True:
3118 while True:
3179 l = interactiveshell.raw_input_original(':')
3119 l = interactiveshell.raw_input_original(':')
3180 if l == sentinel:
3120 if l == sentinel:
3181 return
3121 return
3182 else:
3122 else:
3183 yield l
3123 yield l
3184
3124
3185 def _strip_pasted_lines_for_code(self, raw_lines):
3125 def _strip_pasted_lines_for_code(self, raw_lines):
3186 """ Strip non-code parts of a sequence of lines to return a block of
3126 """ Strip non-code parts of a sequence of lines to return a block of
3187 code.
3127 code.
3188 """
3128 """
3189 # Regular expressions that declare text we strip from the input:
3129 # Regular expressions that declare text we strip from the input:
3190 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3130 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3191 r'^\s*(\s?>)+', # Python input prompt
3131 r'^\s*(\s?>)+', # Python input prompt
3192 r'^\s*\.{3,}', # Continuation prompts
3132 r'^\s*\.{3,}', # Continuation prompts
3193 r'^\++',
3133 r'^\++',
3194 ]
3134 ]
3195
3135
3196 strip_from_start = map(re.compile,strip_re)
3136 strip_from_start = map(re.compile,strip_re)
3197
3137
3198 lines = []
3138 lines = []
3199 for l in raw_lines:
3139 for l in raw_lines:
3200 for pat in strip_from_start:
3140 for pat in strip_from_start:
3201 l = pat.sub('',l)
3141 l = pat.sub('',l)
3202 lines.append(l)
3142 lines.append(l)
3203
3143
3204 block = "\n".join(lines) + '\n'
3144 block = "\n".join(lines) + '\n'
3205 #print "block:\n",block
3145 #print "block:\n",block
3206 return block
3146 return block
3207
3147
3208 def _execute_block(self, block, par):
3148 def _execute_block(self, block, par):
3209 """ Execute a block, or store it in a variable, per the user's request.
3149 """ Execute a block, or store it in a variable, per the user's request.
3210 """
3150 """
3211 if not par:
3151 if not par:
3212 b = textwrap.dedent(block)
3152 b = textwrap.dedent(block)
3213 self.user_ns['pasted_block'] = b
3153 self.user_ns['pasted_block'] = b
3214 exec b in self.user_ns
3154 exec b in self.user_ns
3215 else:
3155 else:
3216 self.user_ns[par] = SList(block.splitlines())
3156 self.user_ns[par] = SList(block.splitlines())
3217 print "Block assigned to '%s'" % par
3157 print "Block assigned to '%s'" % par
3218
3158
3219 def magic_quickref(self,arg):
3159 def magic_quickref(self,arg):
3220 """ Show a quick reference sheet """
3160 """ Show a quick reference sheet """
3221 import IPython.core.usage
3161 import IPython.core.usage
3222 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3162 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3223
3163
3224 page.page(qr)
3164 page.page(qr)
3225
3165
3226 def magic_doctest_mode(self,parameter_s=''):
3166 def magic_doctest_mode(self,parameter_s=''):
3227 """Toggle doctest mode on and off.
3167 """Toggle doctest mode on and off.
3228
3168
3229 This mode is intended to make IPython behave as much as possible like a
3169 This mode is intended to make IPython behave as much as possible like a
3230 plain Python shell, from the perspective of how its prompts, exceptions
3170 plain Python shell, from the perspective of how its prompts, exceptions
3231 and output look. This makes it easy to copy and paste parts of a
3171 and output look. This makes it easy to copy and paste parts of a
3232 session into doctests. It does so by:
3172 session into doctests. It does so by:
3233
3173
3234 - Changing the prompts to the classic ``>>>`` ones.
3174 - Changing the prompts to the classic ``>>>`` ones.
3235 - Changing the exception reporting mode to 'Plain'.
3175 - Changing the exception reporting mode to 'Plain'.
3236 - Disabling pretty-printing of output.
3176 - Disabling pretty-printing of output.
3237
3177
3238 Note that IPython also supports the pasting of code snippets that have
3178 Note that IPython also supports the pasting of code snippets that have
3239 leading '>>>' and '...' prompts in them. This means that you can paste
3179 leading '>>>' and '...' prompts in them. This means that you can paste
3240 doctests from files or docstrings (even if they have leading
3180 doctests from files or docstrings (even if they have leading
3241 whitespace), and the code will execute correctly. You can then use
3181 whitespace), and the code will execute correctly. You can then use
3242 '%history -t' to see the translated history; this will give you the
3182 '%history -t' to see the translated history; this will give you the
3243 input after removal of all the leading prompts and whitespace, which
3183 input after removal of all the leading prompts and whitespace, which
3244 can be pasted back into an editor.
3184 can be pasted back into an editor.
3245
3185
3246 With these features, you can switch into this mode easily whenever you
3186 With these features, you can switch into this mode easily whenever you
3247 need to do testing and changes to doctests, without having to leave
3187 need to do testing and changes to doctests, without having to leave
3248 your existing IPython session.
3188 your existing IPython session.
3249 """
3189 """
3250
3190
3251 from IPython.utils.ipstruct import Struct
3191 from IPython.utils.ipstruct import Struct
3252
3192
3253 # Shorthands
3193 # Shorthands
3254 shell = self.shell
3194 shell = self.shell
3255 oc = shell.displayhook
3195 oc = shell.displayhook
3256 meta = shell.meta
3196 meta = shell.meta
3257 disp_formatter = self.shell.display_formatter
3197 disp_formatter = self.shell.display_formatter
3258 ptformatter = disp_formatter.formatters['text/plain']
3198 ptformatter = disp_formatter.formatters['text/plain']
3259 # dstore is a data store kept in the instance metadata bag to track any
3199 # dstore is a data store kept in the instance metadata bag to track any
3260 # changes we make, so we can undo them later.
3200 # changes we make, so we can undo them later.
3261 dstore = meta.setdefault('doctest_mode',Struct())
3201 dstore = meta.setdefault('doctest_mode',Struct())
3262 save_dstore = dstore.setdefault
3202 save_dstore = dstore.setdefault
3263
3203
3264 # save a few values we'll need to recover later
3204 # save a few values we'll need to recover later
3265 mode = save_dstore('mode',False)
3205 mode = save_dstore('mode',False)
3266 save_dstore('rc_pprint',ptformatter.pprint)
3206 save_dstore('rc_pprint',ptformatter.pprint)
3267 save_dstore('xmode',shell.InteractiveTB.mode)
3207 save_dstore('xmode',shell.InteractiveTB.mode)
3268 save_dstore('rc_separate_out',shell.separate_out)
3208 save_dstore('rc_separate_out',shell.separate_out)
3269 save_dstore('rc_separate_out2',shell.separate_out2)
3209 save_dstore('rc_separate_out2',shell.separate_out2)
3270 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3210 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3271 save_dstore('rc_separate_in',shell.separate_in)
3211 save_dstore('rc_separate_in',shell.separate_in)
3272 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3212 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3273
3213
3274 if mode == False:
3214 if mode == False:
3275 # turn on
3215 # turn on
3276 oc.prompt1.p_template = '>>> '
3216 oc.prompt1.p_template = '>>> '
3277 oc.prompt2.p_template = '... '
3217 oc.prompt2.p_template = '... '
3278 oc.prompt_out.p_template = ''
3218 oc.prompt_out.p_template = ''
3279
3219
3280 # Prompt separators like plain python
3220 # Prompt separators like plain python
3281 oc.input_sep = oc.prompt1.sep = ''
3221 oc.input_sep = oc.prompt1.sep = ''
3282 oc.output_sep = ''
3222 oc.output_sep = ''
3283 oc.output_sep2 = ''
3223 oc.output_sep2 = ''
3284
3224
3285 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3225 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3286 oc.prompt_out.pad_left = False
3226 oc.prompt_out.pad_left = False
3287
3227
3288 ptformatter.pprint = False
3228 ptformatter.pprint = False
3289 disp_formatter.plain_text_only = True
3229 disp_formatter.plain_text_only = True
3290
3230
3291 shell.magic_xmode('Plain')
3231 shell.magic_xmode('Plain')
3292 else:
3232 else:
3293 # turn off
3233 # turn off
3294 oc.prompt1.p_template = shell.prompt_in1
3234 oc.prompt1.p_template = shell.prompt_in1
3295 oc.prompt2.p_template = shell.prompt_in2
3235 oc.prompt2.p_template = shell.prompt_in2
3296 oc.prompt_out.p_template = shell.prompt_out
3236 oc.prompt_out.p_template = shell.prompt_out
3297
3237
3298 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3238 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3299
3239
3300 oc.output_sep = dstore.rc_separate_out
3240 oc.output_sep = dstore.rc_separate_out
3301 oc.output_sep2 = dstore.rc_separate_out2
3241 oc.output_sep2 = dstore.rc_separate_out2
3302
3242
3303 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3243 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3304 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3244 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3305
3245
3306 ptformatter.pprint = dstore.rc_pprint
3246 ptformatter.pprint = dstore.rc_pprint
3307 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3247 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3308
3248
3309 shell.magic_xmode(dstore.xmode)
3249 shell.magic_xmode(dstore.xmode)
3310
3250
3311 # Store new mode and inform
3251 # Store new mode and inform
3312 dstore.mode = bool(1-int(mode))
3252 dstore.mode = bool(1-int(mode))
3313 mode_label = ['OFF','ON'][dstore.mode]
3253 mode_label = ['OFF','ON'][dstore.mode]
3314 print 'Doctest mode is:', mode_label
3254 print 'Doctest mode is:', mode_label
3315
3255
3316 def magic_gui(self, parameter_s=''):
3256 def magic_gui(self, parameter_s=''):
3317 """Enable or disable IPython GUI event loop integration.
3257 """Enable or disable IPython GUI event loop integration.
3318
3258
3319 %gui [GUINAME]
3259 %gui [GUINAME]
3320
3260
3321 This magic replaces IPython's threaded shells that were activated
3261 This magic replaces IPython's threaded shells that were activated
3322 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3262 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3323 can now be enabled, disabled and swtiched at runtime and keyboard
3263 can now be enabled, disabled and swtiched at runtime and keyboard
3324 interrupts should work without any problems. The following toolkits
3264 interrupts should work without any problems. The following toolkits
3325 are supported: wxPython, PyQt4, PyGTK, and Tk::
3265 are supported: wxPython, PyQt4, PyGTK, and Tk::
3326
3266
3327 %gui wx # enable wxPython event loop integration
3267 %gui wx # enable wxPython event loop integration
3328 %gui qt4|qt # enable PyQt4 event loop integration
3268 %gui qt4|qt # enable PyQt4 event loop integration
3329 %gui gtk # enable PyGTK event loop integration
3269 %gui gtk # enable PyGTK event loop integration
3330 %gui tk # enable Tk event loop integration
3270 %gui tk # enable Tk event loop integration
3331 %gui # disable all event loop integration
3271 %gui # disable all event loop integration
3332
3272
3333 WARNING: after any of these has been called you can simply create
3273 WARNING: after any of these has been called you can simply create
3334 an application object, but DO NOT start the event loop yourself, as
3274 an application object, but DO NOT start the event loop yourself, as
3335 we have already handled that.
3275 we have already handled that.
3336 """
3276 """
3337 from IPython.lib.inputhook import enable_gui
3277 from IPython.lib.inputhook import enable_gui
3338 opts, arg = self.parse_options(parameter_s, '')
3278 opts, arg = self.parse_options(parameter_s, '')
3339 if arg=='': arg = None
3279 if arg=='': arg = None
3340 return enable_gui(arg)
3280 return enable_gui(arg)
3341
3281
3342 def magic_load_ext(self, module_str):
3282 def magic_load_ext(self, module_str):
3343 """Load an IPython extension by its module name."""
3283 """Load an IPython extension by its module name."""
3344 return self.extension_manager.load_extension(module_str)
3284 return self.extension_manager.load_extension(module_str)
3345
3285
3346 def magic_unload_ext(self, module_str):
3286 def magic_unload_ext(self, module_str):
3347 """Unload an IPython extension by its module name."""
3287 """Unload an IPython extension by its module name."""
3348 self.extension_manager.unload_extension(module_str)
3288 self.extension_manager.unload_extension(module_str)
3349
3289
3350 def magic_reload_ext(self, module_str):
3290 def magic_reload_ext(self, module_str):
3351 """Reload an IPython extension by its module name."""
3291 """Reload an IPython extension by its module name."""
3352 self.extension_manager.reload_extension(module_str)
3292 self.extension_manager.reload_extension(module_str)
3353
3293
3354 @testdec.skip_doctest
3294 @testdec.skip_doctest
3355 def magic_install_profiles(self, s):
3295 def magic_install_profiles(self, s):
3356 """Install the default IPython profiles into the .ipython dir.
3296 """Install the default IPython profiles into the .ipython dir.
3357
3297
3358 If the default profiles have already been installed, they will not
3298 If the default profiles have already been installed, they will not
3359 be overwritten. You can force overwriting them by using the ``-o``
3299 be overwritten. You can force overwriting them by using the ``-o``
3360 option::
3300 option::
3361
3301
3362 In [1]: %install_profiles -o
3302 In [1]: %install_profiles -o
3363 """
3303 """
3364 if '-o' in s:
3304 if '-o' in s:
3365 overwrite = True
3305 overwrite = True
3366 else:
3306 else:
3367 overwrite = False
3307 overwrite = False
3368 from IPython.config import profile
3308 from IPython.config import profile
3369 profile_dir = os.path.split(profile.__file__)[0]
3309 profile_dir = os.path.split(profile.__file__)[0]
3370 ipython_dir = self.ipython_dir
3310 ipython_dir = self.ipython_dir
3371 files = os.listdir(profile_dir)
3311 files = os.listdir(profile_dir)
3372
3312
3373 to_install = []
3313 to_install = []
3374 for f in files:
3314 for f in files:
3375 if f.startswith('ipython_config'):
3315 if f.startswith('ipython_config'):
3376 src = os.path.join(profile_dir, f)
3316 src = os.path.join(profile_dir, f)
3377 dst = os.path.join(ipython_dir, f)
3317 dst = os.path.join(ipython_dir, f)
3378 if (not os.path.isfile(dst)) or overwrite:
3318 if (not os.path.isfile(dst)) or overwrite:
3379 to_install.append((f, src, dst))
3319 to_install.append((f, src, dst))
3380 if len(to_install)>0:
3320 if len(to_install)>0:
3381 print "Installing profiles to: ", ipython_dir
3321 print "Installing profiles to: ", ipython_dir
3382 for (f, src, dst) in to_install:
3322 for (f, src, dst) in to_install:
3383 shutil.copy(src, dst)
3323 shutil.copy(src, dst)
3384 print " %s" % f
3324 print " %s" % f
3385
3325
3386 def magic_install_default_config(self, s):
3326 def magic_install_default_config(self, s):
3387 """Install IPython's default config file into the .ipython dir.
3327 """Install IPython's default config file into the .ipython dir.
3388
3328
3389 If the default config file (:file:`ipython_config.py`) is already
3329 If the default config file (:file:`ipython_config.py`) is already
3390 installed, it will not be overwritten. You can force overwriting
3330 installed, it will not be overwritten. You can force overwriting
3391 by using the ``-o`` option::
3331 by using the ``-o`` option::
3392
3332
3393 In [1]: %install_default_config
3333 In [1]: %install_default_config
3394 """
3334 """
3395 if '-o' in s:
3335 if '-o' in s:
3396 overwrite = True
3336 overwrite = True
3397 else:
3337 else:
3398 overwrite = False
3338 overwrite = False
3399 from IPython.config import default
3339 from IPython.config import default
3400 config_dir = os.path.split(default.__file__)[0]
3340 config_dir = os.path.split(default.__file__)[0]
3401 ipython_dir = self.ipython_dir
3341 ipython_dir = self.ipython_dir
3402 default_config_file_name = 'ipython_config.py'
3342 default_config_file_name = 'ipython_config.py'
3403 src = os.path.join(config_dir, default_config_file_name)
3343 src = os.path.join(config_dir, default_config_file_name)
3404 dst = os.path.join(ipython_dir, default_config_file_name)
3344 dst = os.path.join(ipython_dir, default_config_file_name)
3405 if (not os.path.isfile(dst)) or overwrite:
3345 if (not os.path.isfile(dst)) or overwrite:
3406 shutil.copy(src, dst)
3346 shutil.copy(src, dst)
3407 print "Installing default config file: %s" % dst
3347 print "Installing default config file: %s" % dst
3408
3348
3409 # Pylab support: simple wrappers that activate pylab, load gui input
3349 # Pylab support: simple wrappers that activate pylab, load gui input
3410 # handling and modify slightly %run
3350 # handling and modify slightly %run
3411
3351
3412 @testdec.skip_doctest
3352 @testdec.skip_doctest
3413 def _pylab_magic_run(self, parameter_s=''):
3353 def _pylab_magic_run(self, parameter_s=''):
3414 Magic.magic_run(self, parameter_s,
3354 Magic.magic_run(self, parameter_s,
3415 runner=mpl_runner(self.shell.safe_execfile))
3355 runner=mpl_runner(self.shell.safe_execfile))
3416
3356
3417 _pylab_magic_run.__doc__ = magic_run.__doc__
3357 _pylab_magic_run.__doc__ = magic_run.__doc__
3418
3358
3419 @testdec.skip_doctest
3359 @testdec.skip_doctest
3420 def magic_pylab(self, s):
3360 def magic_pylab(self, s):
3421 """Load numpy and matplotlib to work interactively.
3361 """Load numpy and matplotlib to work interactively.
3422
3362
3423 %pylab [GUINAME]
3363 %pylab [GUINAME]
3424
3364
3425 This function lets you activate pylab (matplotlib, numpy and
3365 This function lets you activate pylab (matplotlib, numpy and
3426 interactive support) at any point during an IPython session.
3366 interactive support) at any point during an IPython session.
3427
3367
3428 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3368 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3429 pylab and mlab, as well as all names from numpy and pylab.
3369 pylab and mlab, as well as all names from numpy and pylab.
3430
3370
3431 Parameters
3371 Parameters
3432 ----------
3372 ----------
3433 guiname : optional
3373 guiname : optional
3434 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3374 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3435 'tk'). If given, the corresponding Matplotlib backend is used,
3375 'tk'). If given, the corresponding Matplotlib backend is used,
3436 otherwise matplotlib's default (which you can override in your
3376 otherwise matplotlib's default (which you can override in your
3437 matplotlib config file) is used.
3377 matplotlib config file) is used.
3438
3378
3439 Examples
3379 Examples
3440 --------
3380 --------
3441 In this case, where the MPL default is TkAgg:
3381 In this case, where the MPL default is TkAgg:
3442 In [2]: %pylab
3382 In [2]: %pylab
3443
3383
3444 Welcome to pylab, a matplotlib-based Python environment.
3384 Welcome to pylab, a matplotlib-based Python environment.
3445 Backend in use: TkAgg
3385 Backend in use: TkAgg
3446 For more information, type 'help(pylab)'.
3386 For more information, type 'help(pylab)'.
3447
3387
3448 But you can explicitly request a different backend:
3388 But you can explicitly request a different backend:
3449 In [3]: %pylab qt
3389 In [3]: %pylab qt
3450
3390
3451 Welcome to pylab, a matplotlib-based Python environment.
3391 Welcome to pylab, a matplotlib-based Python environment.
3452 Backend in use: Qt4Agg
3392 Backend in use: Qt4Agg
3453 For more information, type 'help(pylab)'.
3393 For more information, type 'help(pylab)'.
3454 """
3394 """
3455 self.shell.enable_pylab(s)
3395 self.shell.enable_pylab(s)
3456
3396
3457 def magic_tb(self, s):
3397 def magic_tb(self, s):
3458 """Print the last traceback with the currently active exception mode.
3398 """Print the last traceback with the currently active exception mode.
3459
3399
3460 See %xmode for changing exception reporting modes."""
3400 See %xmode for changing exception reporting modes."""
3461 self.shell.showtraceback()
3401 self.shell.showtraceback()
3462
3402
3463 @testdec.skip_doctest
3403 @testdec.skip_doctest
3464 def magic_precision(self, s=''):
3404 def magic_precision(self, s=''):
3465 """Set floating point precision for pretty printing.
3405 """Set floating point precision for pretty printing.
3466
3406
3467 Can set either integer precision or a format string.
3407 Can set either integer precision or a format string.
3468
3408
3469 If numpy has been imported and precision is an int,
3409 If numpy has been imported and precision is an int,
3470 numpy display precision will also be set, via ``numpy.set_printoptions``.
3410 numpy display precision will also be set, via ``numpy.set_printoptions``.
3471
3411
3472 If no argument is given, defaults will be restored.
3412 If no argument is given, defaults will be restored.
3473
3413
3474 Examples
3414 Examples
3475 --------
3415 --------
3476 ::
3416 ::
3477
3417
3478 In [1]: from math import pi
3418 In [1]: from math import pi
3479
3419
3480 In [2]: %precision 3
3420 In [2]: %precision 3
3481 Out[2]: '%.3f'
3421 Out[2]: '%.3f'
3482
3422
3483 In [3]: pi
3423 In [3]: pi
3484 Out[3]: 3.142
3424 Out[3]: 3.142
3485
3425
3486 In [4]: %precision %i
3426 In [4]: %precision %i
3487 Out[4]: '%i'
3427 Out[4]: '%i'
3488
3428
3489 In [5]: pi
3429 In [5]: pi
3490 Out[5]: 3
3430 Out[5]: 3
3491
3431
3492 In [6]: %precision %e
3432 In [6]: %precision %e
3493 Out[6]: '%e'
3433 Out[6]: '%e'
3494
3434
3495 In [7]: pi**10
3435 In [7]: pi**10
3496 Out[7]: 9.364805e+04
3436 Out[7]: 9.364805e+04
3497
3437
3498 In [8]: %precision
3438 In [8]: %precision
3499 Out[8]: '%r'
3439 Out[8]: '%r'
3500
3440
3501 In [9]: pi**10
3441 In [9]: pi**10
3502 Out[9]: 93648.047476082982
3442 Out[9]: 93648.047476082982
3503
3443
3504 """
3444 """
3505
3445
3506 ptformatter = self.shell.display_formatter.formatters['text/plain']
3446 ptformatter = self.shell.display_formatter.formatters['text/plain']
3507 ptformatter.float_precision = s
3447 ptformatter.float_precision = s
3508 return ptformatter.float_format
3448 return ptformatter.float_format
3509
3449
3510 # end Magic
3450 # end Magic
@@ -1,1000 +1,1025 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import re
30 import re
31
31
32 from IPython.core.alias import AliasManager
32 from IPython.core.alias import AliasManager
33 from IPython.core.autocall import IPyAutocall
33 from IPython.core.autocall import IPyAutocall
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core.macro import Macro
35 from IPython.core.splitinput import split_user_input
36 from IPython.core.splitinput import split_user_input
36 from IPython.core import page
37 from IPython.core import page
37
38
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 import IPython.utils.io
40 import IPython.utils.io
40 from IPython.utils.text import make_quoted_expr
41 from IPython.utils.text import make_quoted_expr
41 from IPython.utils.autoattr import auto_attr
42 from IPython.utils.autoattr import auto_attr
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44 # Global utilities, errors and constants
45 # Global utilities, errors and constants
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46
47
47 # Warning, these cannot be changed unless various regular expressions
48 # Warning, these cannot be changed unless various regular expressions
48 # are updated in a number of places. Not great, but at least we told you.
49 # are updated in a number of places. Not great, but at least we told you.
49 ESC_SHELL = '!'
50 ESC_SHELL = '!'
50 ESC_SH_CAP = '!!'
51 ESC_SH_CAP = '!!'
51 ESC_HELP = '?'
52 ESC_HELP = '?'
52 ESC_MAGIC = '%'
53 ESC_MAGIC = '%'
53 ESC_QUOTE = ','
54 ESC_QUOTE = ','
54 ESC_QUOTE2 = ';'
55 ESC_QUOTE2 = ';'
55 ESC_PAREN = '/'
56 ESC_PAREN = '/'
56
57
57
58
58 class PrefilterError(Exception):
59 class PrefilterError(Exception):
59 pass
60 pass
60
61
61
62
62 # RegExp to identify potential function names
63 # RegExp to identify potential function names
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64
65
65 # RegExp to exclude strings with this start from autocalling. In
66 # RegExp to exclude strings with this start from autocalling. In
66 # particular, all binary operators should be excluded, so that if foo is
67 # particular, all binary operators should be excluded, so that if foo is
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 # routine explicitely does so, to catch direct calls and rebindings of
70 # routine explicitely does so, to catch direct calls and rebindings of
70 # existing names.
71 # existing names.
71
72
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 # it affects the rest of the group in square brackets.
74 # it affects the rest of the group in square brackets.
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 r'|^is |^not |^in |^and |^or ')
76 r'|^is |^not |^in |^and |^or ')
76
77
77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 # try to catch also methods for stuff in lists/tuples/dicts: off
78 # (experimental). For this to work, the line_split regexp would need
79 # (experimental). For this to work, the line_split regexp would need
79 # to be modified so it wouldn't break things at '['. That line is
80 # to be modified so it wouldn't break things at '['. That line is
80 # nasty enough that I shouldn't change it until I can test it _well_.
81 # nasty enough that I shouldn't change it until I can test it _well_.
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82
83
83
84
84 # Handler Check Utilities
85 # Handler Check Utilities
85 def is_shadowed(identifier, ip):
86 def is_shadowed(identifier, ip):
86 """Is the given identifier defined in one of the namespaces which shadow
87 """Is the given identifier defined in one of the namespaces which shadow
87 the alias and magic namespaces? Note that an identifier is different
88 the alias and magic namespaces? Note that an identifier is different
88 than ifun, because it can not contain a '.' character."""
89 than ifun, because it can not contain a '.' character."""
89 # This is much safer than calling ofind, which can change state
90 # This is much safer than calling ofind, which can change state
90 return (identifier in ip.user_ns \
91 return (identifier in ip.user_ns \
91 or identifier in ip.internal_ns \
92 or identifier in ip.internal_ns \
92 or identifier in ip.ns_table['builtin'])
93 or identifier in ip.ns_table['builtin'])
93
94
94
95
95 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
96 # The LineInfo class used throughout
97 # The LineInfo class used throughout
97 #-----------------------------------------------------------------------------
98 #-----------------------------------------------------------------------------
98
99
99
100
100 class LineInfo(object):
101 class LineInfo(object):
101 """A single line of input and associated info.
102 """A single line of input and associated info.
102
103
103 Includes the following as properties:
104 Includes the following as properties:
104
105
105 line
106 line
106 The original, raw line
107 The original, raw line
107
108
108 continue_prompt
109 continue_prompt
109 Is this line a continuation in a sequence of multiline input?
110 Is this line a continuation in a sequence of multiline input?
110
111
111 pre
112 pre
112 The initial esc character or whitespace.
113 The initial esc character or whitespace.
113
114
114 pre_char
115 pre_char
115 The escape character(s) in pre or the empty string if there isn't one.
116 The escape character(s) in pre or the empty string if there isn't one.
116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 Note that '!!' is a possible value for pre_char. Otherwise it will
117 always be a single character.
118 always be a single character.
118
119
119 pre_whitespace
120 pre_whitespace
120 The leading whitespace from pre if it exists. If there is a pre_char,
121 The leading whitespace from pre if it exists. If there is a pre_char,
121 this is just ''.
122 this is just ''.
122
123
123 ifun
124 ifun
124 The 'function part', which is basically the maximal initial sequence
125 The 'function part', which is basically the maximal initial sequence
125 of valid python identifiers and the '.' character. This is what is
126 of valid python identifiers and the '.' character. This is what is
126 checked for alias and magic transformations, used for auto-calling,
127 checked for alias and magic transformations, used for auto-calling,
127 etc.
128 etc.
128
129
129 the_rest
130 the_rest
130 Everything else on the line.
131 Everything else on the line.
131 """
132 """
132 def __init__(self, line, continue_prompt):
133 def __init__(self, line, continue_prompt):
133 self.line = line
134 self.line = line
134 self.continue_prompt = continue_prompt
135 self.continue_prompt = continue_prompt
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136 self.pre, self.ifun, self.the_rest = split_user_input(line)
136
137
137 self.pre_char = self.pre.strip()
138 self.pre_char = self.pre.strip()
138 if self.pre_char:
139 if self.pre_char:
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 else:
141 else:
141 self.pre_whitespace = self.pre
142 self.pre_whitespace = self.pre
142
143
143 self._oinfo = None
144 self._oinfo = None
144
145
145 def ofind(self, ip):
146 def ofind(self, ip):
146 """Do a full, attribute-walking lookup of the ifun in the various
147 """Do a full, attribute-walking lookup of the ifun in the various
147 namespaces for the given IPython InteractiveShell instance.
148 namespaces for the given IPython InteractiveShell instance.
148
149
149 Return a dict with keys: found,obj,ospace,ismagic
150 Return a dict with keys: found,obj,ospace,ismagic
150
151
151 Note: can cause state changes because of calling getattr, but should
152 Note: can cause state changes because of calling getattr, but should
152 only be run if autocall is on and if the line hasn't matched any
153 only be run if autocall is on and if the line hasn't matched any
153 other, less dangerous handlers.
154 other, less dangerous handlers.
154
155
155 Does cache the results of the call, so can be called multiple times
156 Does cache the results of the call, so can be called multiple times
156 without worrying about *further* damaging state.
157 without worrying about *further* damaging state.
157 """
158 """
158 if not self._oinfo:
159 if not self._oinfo:
159 # ip.shell._ofind is actually on the Magic class!
160 # ip.shell._ofind is actually on the Magic class!
160 self._oinfo = ip.shell._ofind(self.ifun)
161 self._oinfo = ip.shell._ofind(self.ifun)
161 return self._oinfo
162 return self._oinfo
162
163
163 def __str__(self):
164 def __str__(self):
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165
166
166
167
167 #-----------------------------------------------------------------------------
168 #-----------------------------------------------------------------------------
168 # Main Prefilter manager
169 # Main Prefilter manager
169 #-----------------------------------------------------------------------------
170 #-----------------------------------------------------------------------------
170
171
171
172
172 class PrefilterManager(Configurable):
173 class PrefilterManager(Configurable):
173 """Main prefilter component.
174 """Main prefilter component.
174
175
175 The IPython prefilter is run on all user input before it is run. The
176 The IPython prefilter is run on all user input before it is run. The
176 prefilter consumes lines of input and produces transformed lines of
177 prefilter consumes lines of input and produces transformed lines of
177 input.
178 input.
178
179
179 The iplementation consists of two phases:
180 The iplementation consists of two phases:
180
181
181 1. Transformers
182 1. Transformers
182 2. Checkers and handlers
183 2. Checkers and handlers
183
184
184 Over time, we plan on deprecating the checkers and handlers and doing
185 Over time, we plan on deprecating the checkers and handlers and doing
185 everything in the transformers.
186 everything in the transformers.
186
187
187 The transformers are instances of :class:`PrefilterTransformer` and have
188 The transformers are instances of :class:`PrefilterTransformer` and have
188 a single method :meth:`transform` that takes a line and returns a
189 a single method :meth:`transform` that takes a line and returns a
189 transformed line. The transformation can be accomplished using any
190 transformed line. The transformation can be accomplished using any
190 tool, but our current ones use regular expressions for speed. We also
191 tool, but our current ones use regular expressions for speed. We also
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192
193
193 After all the transformers have been run, the line is fed to the checkers,
194 After all the transformers have been run, the line is fed to the checkers,
194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 which are instances of :class:`PrefilterChecker`. The line is passed to
195 the :meth:`check` method, which either returns `None` or a
196 the :meth:`check` method, which either returns `None` or a
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 the line is passed to the :meth:`handle` method of the returned
199 the line is passed to the :meth:`handle` method of the returned
199 handler and no further checkers are tried.
200 handler and no further checkers are tried.
200
201
201 Both transformers and checkers have a `priority` attribute, that determines
202 Both transformers and checkers have a `priority` attribute, that determines
202 the order in which they are called. Smaller priorities are tried first.
203 the order in which they are called. Smaller priorities are tried first.
203
204
204 Both transformers and checkers also have `enabled` attribute, which is
205 Both transformers and checkers also have `enabled` attribute, which is
205 a boolean that determines if the instance is used.
206 a boolean that determines if the instance is used.
206
207
207 Users or developers can change the priority or enabled attribute of
208 Users or developers can change the priority or enabled attribute of
208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 transformers or checkers, but they must call the :meth:`sort_checkers`
209 or :meth:`sort_transformers` method after changing the priority.
210 or :meth:`sort_transformers` method after changing the priority.
210 """
211 """
211
212
212 multi_line_specials = CBool(True, config=True)
213 multi_line_specials = CBool(True, config=True)
213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
214 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
214
215
215 def __init__(self, shell=None, config=None):
216 def __init__(self, shell=None, config=None):
216 super(PrefilterManager, self).__init__(shell=shell, config=config)
217 super(PrefilterManager, self).__init__(shell=shell, config=config)
217 self.shell = shell
218 self.shell = shell
218 self.init_transformers()
219 self.init_transformers()
219 self.init_handlers()
220 self.init_handlers()
220 self.init_checkers()
221 self.init_checkers()
221
222
222 #-------------------------------------------------------------------------
223 #-------------------------------------------------------------------------
223 # API for managing transformers
224 # API for managing transformers
224 #-------------------------------------------------------------------------
225 #-------------------------------------------------------------------------
225
226
226 def init_transformers(self):
227 def init_transformers(self):
227 """Create the default transformers."""
228 """Create the default transformers."""
228 self._transformers = []
229 self._transformers = []
229 for transformer_cls in _default_transformers:
230 for transformer_cls in _default_transformers:
230 transformer_cls(
231 transformer_cls(
231 shell=self.shell, prefilter_manager=self, config=self.config
232 shell=self.shell, prefilter_manager=self, config=self.config
232 )
233 )
233
234
234 def sort_transformers(self):
235 def sort_transformers(self):
235 """Sort the transformers by priority.
236 """Sort the transformers by priority.
236
237
237 This must be called after the priority of a transformer is changed.
238 This must be called after the priority of a transformer is changed.
238 The :meth:`register_transformer` method calls this automatically.
239 The :meth:`register_transformer` method calls this automatically.
239 """
240 """
240 self._transformers.sort(key=lambda x: x.priority)
241 self._transformers.sort(key=lambda x: x.priority)
241
242
242 @property
243 @property
243 def transformers(self):
244 def transformers(self):
244 """Return a list of checkers, sorted by priority."""
245 """Return a list of checkers, sorted by priority."""
245 return self._transformers
246 return self._transformers
246
247
247 def register_transformer(self, transformer):
248 def register_transformer(self, transformer):
248 """Register a transformer instance."""
249 """Register a transformer instance."""
249 if transformer not in self._transformers:
250 if transformer not in self._transformers:
250 self._transformers.append(transformer)
251 self._transformers.append(transformer)
251 self.sort_transformers()
252 self.sort_transformers()
252
253
253 def unregister_transformer(self, transformer):
254 def unregister_transformer(self, transformer):
254 """Unregister a transformer instance."""
255 """Unregister a transformer instance."""
255 if transformer in self._transformers:
256 if transformer in self._transformers:
256 self._transformers.remove(transformer)
257 self._transformers.remove(transformer)
257
258
258 #-------------------------------------------------------------------------
259 #-------------------------------------------------------------------------
259 # API for managing checkers
260 # API for managing checkers
260 #-------------------------------------------------------------------------
261 #-------------------------------------------------------------------------
261
262
262 def init_checkers(self):
263 def init_checkers(self):
263 """Create the default checkers."""
264 """Create the default checkers."""
264 self._checkers = []
265 self._checkers = []
265 for checker in _default_checkers:
266 for checker in _default_checkers:
266 checker(
267 checker(
267 shell=self.shell, prefilter_manager=self, config=self.config
268 shell=self.shell, prefilter_manager=self, config=self.config
268 )
269 )
269
270
270 def sort_checkers(self):
271 def sort_checkers(self):
271 """Sort the checkers by priority.
272 """Sort the checkers by priority.
272
273
273 This must be called after the priority of a checker is changed.
274 This must be called after the priority of a checker is changed.
274 The :meth:`register_checker` method calls this automatically.
275 The :meth:`register_checker` method calls this automatically.
275 """
276 """
276 self._checkers.sort(key=lambda x: x.priority)
277 self._checkers.sort(key=lambda x: x.priority)
277
278
278 @property
279 @property
279 def checkers(self):
280 def checkers(self):
280 """Return a list of checkers, sorted by priority."""
281 """Return a list of checkers, sorted by priority."""
281 return self._checkers
282 return self._checkers
282
283
283 def register_checker(self, checker):
284 def register_checker(self, checker):
284 """Register a checker instance."""
285 """Register a checker instance."""
285 if checker not in self._checkers:
286 if checker not in self._checkers:
286 self._checkers.append(checker)
287 self._checkers.append(checker)
287 self.sort_checkers()
288 self.sort_checkers()
288
289
289 def unregister_checker(self, checker):
290 def unregister_checker(self, checker):
290 """Unregister a checker instance."""
291 """Unregister a checker instance."""
291 if checker in self._checkers:
292 if checker in self._checkers:
292 self._checkers.remove(checker)
293 self._checkers.remove(checker)
293
294
294 #-------------------------------------------------------------------------
295 #-------------------------------------------------------------------------
295 # API for managing checkers
296 # API for managing checkers
296 #-------------------------------------------------------------------------
297 #-------------------------------------------------------------------------
297
298
298 def init_handlers(self):
299 def init_handlers(self):
299 """Create the default handlers."""
300 """Create the default handlers."""
300 self._handlers = {}
301 self._handlers = {}
301 self._esc_handlers = {}
302 self._esc_handlers = {}
302 for handler in _default_handlers:
303 for handler in _default_handlers:
303 handler(
304 handler(
304 shell=self.shell, prefilter_manager=self, config=self.config
305 shell=self.shell, prefilter_manager=self, config=self.config
305 )
306 )
306
307
307 @property
308 @property
308 def handlers(self):
309 def handlers(self):
309 """Return a dict of all the handlers."""
310 """Return a dict of all the handlers."""
310 return self._handlers
311 return self._handlers
311
312
312 def register_handler(self, name, handler, esc_strings):
313 def register_handler(self, name, handler, esc_strings):
313 """Register a handler instance by name with esc_strings."""
314 """Register a handler instance by name with esc_strings."""
314 self._handlers[name] = handler
315 self._handlers[name] = handler
315 for esc_str in esc_strings:
316 for esc_str in esc_strings:
316 self._esc_handlers[esc_str] = handler
317 self._esc_handlers[esc_str] = handler
317
318
318 def unregister_handler(self, name, handler, esc_strings):
319 def unregister_handler(self, name, handler, esc_strings):
319 """Unregister a handler instance by name with esc_strings."""
320 """Unregister a handler instance by name with esc_strings."""
320 try:
321 try:
321 del self._handlers[name]
322 del self._handlers[name]
322 except KeyError:
323 except KeyError:
323 pass
324 pass
324 for esc_str in esc_strings:
325 for esc_str in esc_strings:
325 h = self._esc_handlers.get(esc_str)
326 h = self._esc_handlers.get(esc_str)
326 if h is handler:
327 if h is handler:
327 del self._esc_handlers[esc_str]
328 del self._esc_handlers[esc_str]
328
329
329 def get_handler_by_name(self, name):
330 def get_handler_by_name(self, name):
330 """Get a handler by its name."""
331 """Get a handler by its name."""
331 return self._handlers.get(name)
332 return self._handlers.get(name)
332
333
333 def get_handler_by_esc(self, esc_str):
334 def get_handler_by_esc(self, esc_str):
334 """Get a handler by its escape string."""
335 """Get a handler by its escape string."""
335 return self._esc_handlers.get(esc_str)
336 return self._esc_handlers.get(esc_str)
336
337
337 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
338 # Main prefiltering API
339 # Main prefiltering API
339 #-------------------------------------------------------------------------
340 #-------------------------------------------------------------------------
340
341
341 def prefilter_line_info(self, line_info):
342 def prefilter_line_info(self, line_info):
342 """Prefilter a line that has been converted to a LineInfo object.
343 """Prefilter a line that has been converted to a LineInfo object.
343
344
344 This implements the checker/handler part of the prefilter pipe.
345 This implements the checker/handler part of the prefilter pipe.
345 """
346 """
346 # print "prefilter_line_info: ", line_info
347 # print "prefilter_line_info: ", line_info
347 handler = self.find_handler(line_info)
348 handler = self.find_handler(line_info)
348 return handler.handle(line_info)
349 return handler.handle(line_info)
349
350
350 def find_handler(self, line_info):
351 def find_handler(self, line_info):
351 """Find a handler for the line_info by trying checkers."""
352 """Find a handler for the line_info by trying checkers."""
352 for checker in self.checkers:
353 for checker in self.checkers:
353 if checker.enabled:
354 if checker.enabled:
354 handler = checker.check(line_info)
355 handler = checker.check(line_info)
355 if handler:
356 if handler:
356 return handler
357 return handler
357 return self.get_handler_by_name('normal')
358 return self.get_handler_by_name('normal')
358
359
359 def transform_line(self, line, continue_prompt):
360 def transform_line(self, line, continue_prompt):
360 """Calls the enabled transformers in order of increasing priority."""
361 """Calls the enabled transformers in order of increasing priority."""
361 for transformer in self.transformers:
362 for transformer in self.transformers:
362 if transformer.enabled:
363 if transformer.enabled:
363 line = transformer.transform(line, continue_prompt)
364 line = transformer.transform(line, continue_prompt)
364 return line
365 return line
365
366
366 def prefilter_line(self, line, continue_prompt=False):
367 def prefilter_line(self, line, continue_prompt=False):
367 """Prefilter a single input line as text.
368 """Prefilter a single input line as text.
368
369
369 This method prefilters a single line of text by calling the
370 This method prefilters a single line of text by calling the
370 transformers and then the checkers/handlers.
371 transformers and then the checkers/handlers.
371 """
372 """
372
373
373 # print "prefilter_line: ", line, continue_prompt
374 # print "prefilter_line: ", line, continue_prompt
374 # All handlers *must* return a value, even if it's blank ('').
375 # All handlers *must* return a value, even if it's blank ('').
375
376
376 # save the line away in case we crash, so the post-mortem handler can
377 # save the line away in case we crash, so the post-mortem handler can
377 # record it
378 # record it
378 self.shell._last_input_line = line
379 self.shell._last_input_line = line
379
380
380 if not line:
381 if not line:
381 # Return immediately on purely empty lines, so that if the user
382 # Return immediately on purely empty lines, so that if the user
382 # previously typed some whitespace that started a continuation
383 # previously typed some whitespace that started a continuation
383 # prompt, he can break out of that loop with just an empty line.
384 # prompt, he can break out of that loop with just an empty line.
384 # This is how the default python prompt works.
385 # This is how the default python prompt works.
385
386
386 # Only return if the accumulated input buffer was just whitespace!
387 # Only return if the accumulated input buffer was just whitespace!
387 if ''.join(self.shell.buffer).isspace():
388 if ''.join(self.shell.buffer).isspace():
388 self.shell.buffer[:] = []
389 self.shell.buffer[:] = []
389 return ''
390 return ''
390
391
391 # At this point, we invoke our transformers.
392 # At this point, we invoke our transformers.
392 if not continue_prompt or (continue_prompt and self.multi_line_specials):
393 if not continue_prompt or (continue_prompt and self.multi_line_specials):
393 line = self.transform_line(line, continue_prompt)
394 line = self.transform_line(line, continue_prompt)
394
395
395 # Now we compute line_info for the checkers and handlers
396 # Now we compute line_info for the checkers and handlers
396 line_info = LineInfo(line, continue_prompt)
397 line_info = LineInfo(line, continue_prompt)
397
398
398 # the input history needs to track even empty lines
399 # the input history needs to track even empty lines
399 stripped = line.strip()
400 stripped = line.strip()
400
401
401 normal_handler = self.get_handler_by_name('normal')
402 normal_handler = self.get_handler_by_name('normal')
402 if not stripped:
403 if not stripped:
403 if not continue_prompt:
404 if not continue_prompt:
404 self.shell.displayhook.prompt_count -= 1
405 self.shell.displayhook.prompt_count -= 1
405
406
406 return normal_handler.handle(line_info)
407 return normal_handler.handle(line_info)
407
408
408 # special handlers are only allowed for single line statements
409 # special handlers are only allowed for single line statements
409 if continue_prompt and not self.multi_line_specials:
410 if continue_prompt and not self.multi_line_specials:
410 return normal_handler.handle(line_info)
411 return normal_handler.handle(line_info)
411
412
412 prefiltered = self.prefilter_line_info(line_info)
413 prefiltered = self.prefilter_line_info(line_info)
413 # print "prefiltered line: %r" % prefiltered
414 # print "prefiltered line: %r" % prefiltered
414 return prefiltered
415 return prefiltered
415
416
416 def prefilter_lines(self, lines, continue_prompt=False):
417 def prefilter_lines(self, lines, continue_prompt=False):
417 """Prefilter multiple input lines of text.
418 """Prefilter multiple input lines of text.
418
419
419 This is the main entry point for prefiltering multiple lines of
420 This is the main entry point for prefiltering multiple lines of
420 input. This simply calls :meth:`prefilter_line` for each line of
421 input. This simply calls :meth:`prefilter_line` for each line of
421 input.
422 input.
422
423
423 This covers cases where there are multiple lines in the user entry,
424 This covers cases where there are multiple lines in the user entry,
424 which is the case when the user goes back to a multiline history
425 which is the case when the user goes back to a multiline history
425 entry and presses enter.
426 entry and presses enter.
426 """
427 """
427 llines = lines.rstrip('\n').split('\n')
428 llines = lines.rstrip('\n').split('\n')
428 # We can get multiple lines in one shot, where multiline input 'blends'
429 # We can get multiple lines in one shot, where multiline input 'blends'
429 # into one line, in cases like recalling from the readline history
430 # into one line, in cases like recalling from the readline history
430 # buffer. We need to make sure that in such cases, we correctly
431 # buffer. We need to make sure that in such cases, we correctly
431 # communicate downstream which line is first and which are continuation
432 # communicate downstream which line is first and which are continuation
432 # ones.
433 # ones.
433 if len(llines) > 1:
434 if len(llines) > 1:
434 out = '\n'.join([self.prefilter_line(line, lnum>0)
435 out = '\n'.join([self.prefilter_line(line, lnum>0)
435 for lnum, line in enumerate(llines) ])
436 for lnum, line in enumerate(llines) ])
436 else:
437 else:
437 out = self.prefilter_line(llines[0], continue_prompt)
438 out = self.prefilter_line(llines[0], continue_prompt)
438
439
439 return out
440 return out
440
441
441 #-----------------------------------------------------------------------------
442 #-----------------------------------------------------------------------------
442 # Prefilter transformers
443 # Prefilter transformers
443 #-----------------------------------------------------------------------------
444 #-----------------------------------------------------------------------------
444
445
445
446
446 class PrefilterTransformer(Configurable):
447 class PrefilterTransformer(Configurable):
447 """Transform a line of user input."""
448 """Transform a line of user input."""
448
449
449 priority = Int(100, config=True)
450 priority = Int(100, config=True)
450 # Transformers don't currently use shell or prefilter_manager, but as we
451 # Transformers don't currently use shell or prefilter_manager, but as we
451 # move away from checkers and handlers, they will need them.
452 # move away from checkers and handlers, they will need them.
452 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
453 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
453 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
454 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
454 enabled = Bool(True, config=True)
455 enabled = Bool(True, config=True)
455
456
456 def __init__(self, shell=None, prefilter_manager=None, config=None):
457 def __init__(self, shell=None, prefilter_manager=None, config=None):
457 super(PrefilterTransformer, self).__init__(
458 super(PrefilterTransformer, self).__init__(
458 shell=shell, prefilter_manager=prefilter_manager, config=config
459 shell=shell, prefilter_manager=prefilter_manager, config=config
459 )
460 )
460 self.prefilter_manager.register_transformer(self)
461 self.prefilter_manager.register_transformer(self)
461
462
462 def transform(self, line, continue_prompt):
463 def transform(self, line, continue_prompt):
463 """Transform a line, returning the new one."""
464 """Transform a line, returning the new one."""
464 return None
465 return None
465
466
466 def __repr__(self):
467 def __repr__(self):
467 return "<%s(priority=%r, enabled=%r)>" % (
468 return "<%s(priority=%r, enabled=%r)>" % (
468 self.__class__.__name__, self.priority, self.enabled)
469 self.__class__.__name__, self.priority, self.enabled)
469
470
470
471
471 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
472 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
472 r'\s*=\s*!(?P<cmd>.*)')
473 r'\s*=\s*!(?P<cmd>.*)')
473
474
474
475
475 class AssignSystemTransformer(PrefilterTransformer):
476 class AssignSystemTransformer(PrefilterTransformer):
476 """Handle the `files = !ls` syntax."""
477 """Handle the `files = !ls` syntax."""
477
478
478 priority = Int(100, config=True)
479 priority = Int(100, config=True)
479
480
480 def transform(self, line, continue_prompt):
481 def transform(self, line, continue_prompt):
481 m = _assign_system_re.match(line)
482 m = _assign_system_re.match(line)
482 if m is not None:
483 if m is not None:
483 cmd = m.group('cmd')
484 cmd = m.group('cmd')
484 lhs = m.group('lhs')
485 lhs = m.group('lhs')
485 expr = make_quoted_expr("sc =%s" % cmd)
486 expr = make_quoted_expr("sc =%s" % cmd)
486 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
487 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
487 return new_line
488 return new_line
488 return line
489 return line
489
490
490
491
491 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
492 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
492 r'\s*=\s*%(?P<cmd>.*)')
493 r'\s*=\s*%(?P<cmd>.*)')
493
494
494 class AssignMagicTransformer(PrefilterTransformer):
495 class AssignMagicTransformer(PrefilterTransformer):
495 """Handle the `a = %who` syntax."""
496 """Handle the `a = %who` syntax."""
496
497
497 priority = Int(200, config=True)
498 priority = Int(200, config=True)
498
499
499 def transform(self, line, continue_prompt):
500 def transform(self, line, continue_prompt):
500 m = _assign_magic_re.match(line)
501 m = _assign_magic_re.match(line)
501 if m is not None:
502 if m is not None:
502 cmd = m.group('cmd')
503 cmd = m.group('cmd')
503 lhs = m.group('lhs')
504 lhs = m.group('lhs')
504 expr = make_quoted_expr(cmd)
505 expr = make_quoted_expr(cmd)
505 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
506 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
506 return new_line
507 return new_line
507 return line
508 return line
508
509
509
510
510 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
511 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
511
512
512 class PyPromptTransformer(PrefilterTransformer):
513 class PyPromptTransformer(PrefilterTransformer):
513 """Handle inputs that start with '>>> ' syntax."""
514 """Handle inputs that start with '>>> ' syntax."""
514
515
515 priority = Int(50, config=True)
516 priority = Int(50, config=True)
516
517
517 def transform(self, line, continue_prompt):
518 def transform(self, line, continue_prompt):
518
519
519 if not line or line.isspace() or line.strip() == '...':
520 if not line or line.isspace() or line.strip() == '...':
520 # This allows us to recognize multiple input prompts separated by
521 # This allows us to recognize multiple input prompts separated by
521 # blank lines and pasted in a single chunk, very common when
522 # blank lines and pasted in a single chunk, very common when
522 # pasting doctests or long tutorial passages.
523 # pasting doctests or long tutorial passages.
523 return ''
524 return ''
524 m = _classic_prompt_re.match(line)
525 m = _classic_prompt_re.match(line)
525 if m:
526 if m:
526 return line[len(m.group(0)):]
527 return line[len(m.group(0)):]
527 else:
528 else:
528 return line
529 return line
529
530
530
531
531 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
532 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
532
533
533 class IPyPromptTransformer(PrefilterTransformer):
534 class IPyPromptTransformer(PrefilterTransformer):
534 """Handle inputs that start classic IPython prompt syntax."""
535 """Handle inputs that start classic IPython prompt syntax."""
535
536
536 priority = Int(50, config=True)
537 priority = Int(50, config=True)
537
538
538 def transform(self, line, continue_prompt):
539 def transform(self, line, continue_prompt):
539
540
540 if not line or line.isspace() or line.strip() == '...':
541 if not line or line.isspace() or line.strip() == '...':
541 # This allows us to recognize multiple input prompts separated by
542 # This allows us to recognize multiple input prompts separated by
542 # blank lines and pasted in a single chunk, very common when
543 # blank lines and pasted in a single chunk, very common when
543 # pasting doctests or long tutorial passages.
544 # pasting doctests or long tutorial passages.
544 return ''
545 return ''
545 m = _ipy_prompt_re.match(line)
546 m = _ipy_prompt_re.match(line)
546 if m:
547 if m:
547 return line[len(m.group(0)):]
548 return line[len(m.group(0)):]
548 else:
549 else:
549 return line
550 return line
550
551
551 #-----------------------------------------------------------------------------
552 #-----------------------------------------------------------------------------
552 # Prefilter checkers
553 # Prefilter checkers
553 #-----------------------------------------------------------------------------
554 #-----------------------------------------------------------------------------
554
555
555
556
556 class PrefilterChecker(Configurable):
557 class PrefilterChecker(Configurable):
557 """Inspect an input line and return a handler for that line."""
558 """Inspect an input line and return a handler for that line."""
558
559
559 priority = Int(100, config=True)
560 priority = Int(100, config=True)
560 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
561 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
561 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
562 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
562 enabled = Bool(True, config=True)
563 enabled = Bool(True, config=True)
563
564
564 def __init__(self, shell=None, prefilter_manager=None, config=None):
565 def __init__(self, shell=None, prefilter_manager=None, config=None):
565 super(PrefilterChecker, self).__init__(
566 super(PrefilterChecker, self).__init__(
566 shell=shell, prefilter_manager=prefilter_manager, config=config
567 shell=shell, prefilter_manager=prefilter_manager, config=config
567 )
568 )
568 self.prefilter_manager.register_checker(self)
569 self.prefilter_manager.register_checker(self)
569
570
570 def check(self, line_info):
571 def check(self, line_info):
571 """Inspect line_info and return a handler instance or None."""
572 """Inspect line_info and return a handler instance or None."""
572 return None
573 return None
573
574
574 def __repr__(self):
575 def __repr__(self):
575 return "<%s(priority=%r, enabled=%r)>" % (
576 return "<%s(priority=%r, enabled=%r)>" % (
576 self.__class__.__name__, self.priority, self.enabled)
577 self.__class__.__name__, self.priority, self.enabled)
577
578
578
579
579 class EmacsChecker(PrefilterChecker):
580 class EmacsChecker(PrefilterChecker):
580
581
581 priority = Int(100, config=True)
582 priority = Int(100, config=True)
582 enabled = Bool(False, config=True)
583 enabled = Bool(False, config=True)
583
584
584 def check(self, line_info):
585 def check(self, line_info):
585 "Emacs ipython-mode tags certain input lines."
586 "Emacs ipython-mode tags certain input lines."
586 if line_info.line.endswith('# PYTHON-MODE'):
587 if line_info.line.endswith('# PYTHON-MODE'):
587 return self.prefilter_manager.get_handler_by_name('emacs')
588 return self.prefilter_manager.get_handler_by_name('emacs')
588 else:
589 else:
589 return None
590 return None
590
591
591
592
592 class ShellEscapeChecker(PrefilterChecker):
593 class ShellEscapeChecker(PrefilterChecker):
593
594
594 priority = Int(200, config=True)
595 priority = Int(200, config=True)
595
596
596 def check(self, line_info):
597 def check(self, line_info):
597 if line_info.line.lstrip().startswith(ESC_SHELL):
598 if line_info.line.lstrip().startswith(ESC_SHELL):
598 return self.prefilter_manager.get_handler_by_name('shell')
599 return self.prefilter_manager.get_handler_by_name('shell')
599
600
600
601
602 class MacroChecker(PrefilterChecker):
603
604 priority = Int(250, config=True)
605
606 def check(self, line_info):
607 obj = self.shell.user_ns.get(line_info.ifun)
608 if isinstance(obj, Macro):
609 return self.prefilter_manager.get_handler_by_name('macro')
610 else:
611 return None
612
613
601 class IPyAutocallChecker(PrefilterChecker):
614 class IPyAutocallChecker(PrefilterChecker):
602
615
603 priority = Int(300, config=True)
616 priority = Int(300, config=True)
604
617
605 def check(self, line_info):
618 def check(self, line_info):
606 "Instances of IPyAutocall in user_ns get autocalled immediately"
619 "Instances of IPyAutocall in user_ns get autocalled immediately"
607 obj = self.shell.user_ns.get(line_info.ifun, None)
620 obj = self.shell.user_ns.get(line_info.ifun, None)
608 if isinstance(obj, IPyAutocall):
621 if isinstance(obj, IPyAutocall):
609 obj.set_ip(self.shell)
622 obj.set_ip(self.shell)
610 return self.prefilter_manager.get_handler_by_name('auto')
623 return self.prefilter_manager.get_handler_by_name('auto')
611 else:
624 else:
612 return None
625 return None
613
626
614
627
615 class MultiLineMagicChecker(PrefilterChecker):
628 class MultiLineMagicChecker(PrefilterChecker):
616
629
617 priority = Int(400, config=True)
630 priority = Int(400, config=True)
618
631
619 def check(self, line_info):
632 def check(self, line_info):
620 "Allow ! and !! in multi-line statements if multi_line_specials is on"
633 "Allow ! and !! in multi-line statements if multi_line_specials is on"
621 # Note that this one of the only places we check the first character of
634 # Note that this one of the only places we check the first character of
622 # ifun and *not* the pre_char. Also note that the below test matches
635 # ifun and *not* the pre_char. Also note that the below test matches
623 # both ! and !!.
636 # both ! and !!.
624 if line_info.continue_prompt \
637 if line_info.continue_prompt \
625 and self.prefilter_manager.multi_line_specials:
638 and self.prefilter_manager.multi_line_specials:
626 if line_info.ifun.startswith(ESC_MAGIC):
639 if line_info.ifun.startswith(ESC_MAGIC):
627 return self.prefilter_manager.get_handler_by_name('magic')
640 return self.prefilter_manager.get_handler_by_name('magic')
628 else:
641 else:
629 return None
642 return None
630
643
631
644
632 class EscCharsChecker(PrefilterChecker):
645 class EscCharsChecker(PrefilterChecker):
633
646
634 priority = Int(500, config=True)
647 priority = Int(500, config=True)
635
648
636 def check(self, line_info):
649 def check(self, line_info):
637 """Check for escape character and return either a handler to handle it,
650 """Check for escape character and return either a handler to handle it,
638 or None if there is no escape char."""
651 or None if there is no escape char."""
639 if line_info.line[-1] == ESC_HELP \
652 if line_info.line[-1] == ESC_HELP \
640 and line_info.pre_char != ESC_SHELL \
653 and line_info.pre_char != ESC_SHELL \
641 and line_info.pre_char != ESC_SH_CAP:
654 and line_info.pre_char != ESC_SH_CAP:
642 # the ? can be at the end, but *not* for either kind of shell escape,
655 # the ? can be at the end, but *not* for either kind of shell escape,
643 # because a ? can be a vaild final char in a shell cmd
656 # because a ? can be a vaild final char in a shell cmd
644 return self.prefilter_manager.get_handler_by_name('help')
657 return self.prefilter_manager.get_handler_by_name('help')
645 else:
658 else:
646 # This returns None like it should if no handler exists
659 # This returns None like it should if no handler exists
647 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
660 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
648
661
649
662
650 class AssignmentChecker(PrefilterChecker):
663 class AssignmentChecker(PrefilterChecker):
651
664
652 priority = Int(600, config=True)
665 priority = Int(600, config=True)
653
666
654 def check(self, line_info):
667 def check(self, line_info):
655 """Check to see if user is assigning to a var for the first time, in
668 """Check to see if user is assigning to a var for the first time, in
656 which case we want to avoid any sort of automagic / autocall games.
669 which case we want to avoid any sort of automagic / autocall games.
657
670
658 This allows users to assign to either alias or magic names true python
671 This allows users to assign to either alias or magic names true python
659 variables (the magic/alias systems always take second seat to true
672 variables (the magic/alias systems always take second seat to true
660 python code). E.g. ls='hi', or ls,that=1,2"""
673 python code). E.g. ls='hi', or ls,that=1,2"""
661 if line_info.the_rest:
674 if line_info.the_rest:
662 if line_info.the_rest[0] in '=,':
675 if line_info.the_rest[0] in '=,':
663 return self.prefilter_manager.get_handler_by_name('normal')
676 return self.prefilter_manager.get_handler_by_name('normal')
664 else:
677 else:
665 return None
678 return None
666
679
667
680
668 class AutoMagicChecker(PrefilterChecker):
681 class AutoMagicChecker(PrefilterChecker):
669
682
670 priority = Int(700, config=True)
683 priority = Int(700, config=True)
671
684
672 def check(self, line_info):
685 def check(self, line_info):
673 """If the ifun is magic, and automagic is on, run it. Note: normal,
686 """If the ifun is magic, and automagic is on, run it. Note: normal,
674 non-auto magic would already have been triggered via '%' in
687 non-auto magic would already have been triggered via '%' in
675 check_esc_chars. This just checks for automagic. Also, before
688 check_esc_chars. This just checks for automagic. Also, before
676 triggering the magic handler, make sure that there is nothing in the
689 triggering the magic handler, make sure that there is nothing in the
677 user namespace which could shadow it."""
690 user namespace which could shadow it."""
678 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
691 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
679 return None
692 return None
680
693
681 # We have a likely magic method. Make sure we should actually call it.
694 # We have a likely magic method. Make sure we should actually call it.
682 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
695 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
683 return None
696 return None
684
697
685 head = line_info.ifun.split('.',1)[0]
698 head = line_info.ifun.split('.',1)[0]
686 if is_shadowed(head, self.shell):
699 if is_shadowed(head, self.shell):
687 return None
700 return None
688
701
689 return self.prefilter_manager.get_handler_by_name('magic')
702 return self.prefilter_manager.get_handler_by_name('magic')
690
703
691
704
692 class AliasChecker(PrefilterChecker):
705 class AliasChecker(PrefilterChecker):
693
706
694 priority = Int(800, config=True)
707 priority = Int(800, config=True)
695
708
696 def check(self, line_info):
709 def check(self, line_info):
697 "Check if the initital identifier on the line is an alias."
710 "Check if the initital identifier on the line is an alias."
698 # Note: aliases can not contain '.'
711 # Note: aliases can not contain '.'
699 head = line_info.ifun.split('.',1)[0]
712 head = line_info.ifun.split('.',1)[0]
700 if line_info.ifun not in self.shell.alias_manager \
713 if line_info.ifun not in self.shell.alias_manager \
701 or head not in self.shell.alias_manager \
714 or head not in self.shell.alias_manager \
702 or is_shadowed(head, self.shell):
715 or is_shadowed(head, self.shell):
703 return None
716 return None
704
717
705 return self.prefilter_manager.get_handler_by_name('alias')
718 return self.prefilter_manager.get_handler_by_name('alias')
706
719
707
720
708 class PythonOpsChecker(PrefilterChecker):
721 class PythonOpsChecker(PrefilterChecker):
709
722
710 priority = Int(900, config=True)
723 priority = Int(900, config=True)
711
724
712 def check(self, line_info):
725 def check(self, line_info):
713 """If the 'rest' of the line begins with a function call or pretty much
726 """If the 'rest' of the line begins with a function call or pretty much
714 any python operator, we should simply execute the line (regardless of
727 any python operator, we should simply execute the line (regardless of
715 whether or not there's a possible autocall expansion). This avoids
728 whether or not there's a possible autocall expansion). This avoids
716 spurious (and very confusing) geattr() accesses."""
729 spurious (and very confusing) geattr() accesses."""
717 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
730 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
718 return self.prefilter_manager.get_handler_by_name('normal')
731 return self.prefilter_manager.get_handler_by_name('normal')
719 else:
732 else:
720 return None
733 return None
721
734
722
735
723 class AutocallChecker(PrefilterChecker):
736 class AutocallChecker(PrefilterChecker):
724
737
725 priority = Int(1000, config=True)
738 priority = Int(1000, config=True)
726
739
727 def check(self, line_info):
740 def check(self, line_info):
728 "Check if the initial word/function is callable and autocall is on."
741 "Check if the initial word/function is callable and autocall is on."
729 if not self.shell.autocall:
742 if not self.shell.autocall:
730 return None
743 return None
731
744
732 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
745 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
733 if not oinfo['found']:
746 if not oinfo['found']:
734 return None
747 return None
735
748
736 if callable(oinfo['obj']) \
749 if callable(oinfo['obj']) \
737 and (not re_exclude_auto.match(line_info.the_rest)) \
750 and (not re_exclude_auto.match(line_info.the_rest)) \
738 and re_fun_name.match(line_info.ifun):
751 and re_fun_name.match(line_info.ifun):
739 return self.prefilter_manager.get_handler_by_name('auto')
752 return self.prefilter_manager.get_handler_by_name('auto')
740 else:
753 else:
741 return None
754 return None
742
755
743
756
744 #-----------------------------------------------------------------------------
757 #-----------------------------------------------------------------------------
745 # Prefilter handlers
758 # Prefilter handlers
746 #-----------------------------------------------------------------------------
759 #-----------------------------------------------------------------------------
747
760
748
761
749 class PrefilterHandler(Configurable):
762 class PrefilterHandler(Configurable):
750
763
751 handler_name = Str('normal')
764 handler_name = Str('normal')
752 esc_strings = List([])
765 esc_strings = List([])
753 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
766 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
754 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
767 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
755
768
756 def __init__(self, shell=None, prefilter_manager=None, config=None):
769 def __init__(self, shell=None, prefilter_manager=None, config=None):
757 super(PrefilterHandler, self).__init__(
770 super(PrefilterHandler, self).__init__(
758 shell=shell, prefilter_manager=prefilter_manager, config=config
771 shell=shell, prefilter_manager=prefilter_manager, config=config
759 )
772 )
760 self.prefilter_manager.register_handler(
773 self.prefilter_manager.register_handler(
761 self.handler_name,
774 self.handler_name,
762 self,
775 self,
763 self.esc_strings
776 self.esc_strings
764 )
777 )
765
778
766 def handle(self, line_info):
779 def handle(self, line_info):
767 # print "normal: ", line_info
780 # print "normal: ", line_info
768 """Handle normal input lines. Use as a template for handlers."""
781 """Handle normal input lines. Use as a template for handlers."""
769
782
770 # With autoindent on, we need some way to exit the input loop, and I
783 # With autoindent on, we need some way to exit the input loop, and I
771 # don't want to force the user to have to backspace all the way to
784 # don't want to force the user to have to backspace all the way to
772 # clear the line. The rule will be in this case, that either two
785 # clear the line. The rule will be in this case, that either two
773 # lines of pure whitespace in a row, or a line of pure whitespace but
786 # lines of pure whitespace in a row, or a line of pure whitespace but
774 # of a size different to the indent level, will exit the input loop.
787 # of a size different to the indent level, will exit the input loop.
775 line = line_info.line
788 line = line_info.line
776 continue_prompt = line_info.continue_prompt
789 continue_prompt = line_info.continue_prompt
777
790
778 if (continue_prompt and
791 if (continue_prompt and
779 self.shell.autoindent and
792 self.shell.autoindent and
780 line.isspace() and
793 line.isspace() and
781
794
782 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
795 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
783 or
796 or
784 not self.shell.buffer
797 not self.shell.buffer
785 or
798 or
786 (self.shell.buffer[-1]).isspace()
799 (self.shell.buffer[-1]).isspace()
787 )
800 )
788 ):
801 ):
789 line = ''
802 line = ''
790
803
791 return line
804 return line
792
805
793 def __str__(self):
806 def __str__(self):
794 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
807 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
795
808
796
809
797 class AliasHandler(PrefilterHandler):
810 class AliasHandler(PrefilterHandler):
798
811
799 handler_name = Str('alias')
812 handler_name = Str('alias')
800
813
801 def handle(self, line_info):
814 def handle(self, line_info):
802 """Handle alias input lines. """
815 """Handle alias input lines. """
803 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
816 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
804 # pre is needed, because it carries the leading whitespace. Otherwise
817 # pre is needed, because it carries the leading whitespace. Otherwise
805 # aliases won't work in indented sections.
818 # aliases won't work in indented sections.
806 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
819 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
807 make_quoted_expr(transformed))
820 make_quoted_expr(transformed))
808
821
809 return line_out
822 return line_out
810
823
811
824
812 class ShellEscapeHandler(PrefilterHandler):
825 class ShellEscapeHandler(PrefilterHandler):
813
826
814 handler_name = Str('shell')
827 handler_name = Str('shell')
815 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
828 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
816
829
817 def handle(self, line_info):
830 def handle(self, line_info):
818 """Execute the line in a shell, empty return value"""
831 """Execute the line in a shell, empty return value"""
819 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
832 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
820
833
821 line = line_info.line
834 line = line_info.line
822 if line.lstrip().startswith(ESC_SH_CAP):
835 if line.lstrip().startswith(ESC_SH_CAP):
823 # rewrite LineInfo's line, ifun and the_rest to properly hold the
836 # rewrite LineInfo's line, ifun and the_rest to properly hold the
824 # call to %sx and the actual command to be executed, so
837 # call to %sx and the actual command to be executed, so
825 # handle_magic can work correctly. Note that this works even if
838 # handle_magic can work correctly. Note that this works even if
826 # the line is indented, so it handles multi_line_specials
839 # the line is indented, so it handles multi_line_specials
827 # properly.
840 # properly.
828 new_rest = line.lstrip()[2:]
841 new_rest = line.lstrip()[2:]
829 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
842 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
830 line_info.ifun = 'sx'
843 line_info.ifun = 'sx'
831 line_info.the_rest = new_rest
844 line_info.the_rest = new_rest
832 return magic_handler.handle(line_info)
845 return magic_handler.handle(line_info)
833 else:
846 else:
834 cmd = line.lstrip().lstrip(ESC_SHELL)
847 cmd = line.lstrip().lstrip(ESC_SHELL)
835 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
848 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
836 make_quoted_expr(cmd))
849 make_quoted_expr(cmd))
837 return line_out
850 return line_out
838
851
839
852
853 class MacroHandler(PrefilterHandler):
854 handler_name = Str("macro")
855
856 def handle(self, line_info):
857 obj = self.shell.user_ns.get(line_info.ifun)
858 pre_space = line_info.pre_whitespace
859 line_sep = "\n" + pre_space
860 return pre_space + line_sep.join(obj.value.splitlines())
861
862
840 class MagicHandler(PrefilterHandler):
863 class MagicHandler(PrefilterHandler):
841
864
842 handler_name = Str('magic')
865 handler_name = Str('magic')
843 esc_strings = List([ESC_MAGIC])
866 esc_strings = List([ESC_MAGIC])
844
867
845 def handle(self, line_info):
868 def handle(self, line_info):
846 """Execute magic functions."""
869 """Execute magic functions."""
847 ifun = line_info.ifun
870 ifun = line_info.ifun
848 the_rest = line_info.the_rest
871 the_rest = line_info.the_rest
849 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
872 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
850 make_quoted_expr(ifun + " " + the_rest))
873 make_quoted_expr(ifun + " " + the_rest))
851 return cmd
874 return cmd
852
875
853
876
854 class AutoHandler(PrefilterHandler):
877 class AutoHandler(PrefilterHandler):
855
878
856 handler_name = Str('auto')
879 handler_name = Str('auto')
857 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
880 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
858
881
859 def handle(self, line_info):
882 def handle(self, line_info):
860 """Handle lines which can be auto-executed, quoting if requested."""
883 """Handle lines which can be auto-executed, quoting if requested."""
861 line = line_info.line
884 line = line_info.line
862 ifun = line_info.ifun
885 ifun = line_info.ifun
863 the_rest = line_info.the_rest
886 the_rest = line_info.the_rest
864 pre = line_info.pre
887 pre = line_info.pre
865 continue_prompt = line_info.continue_prompt
888 continue_prompt = line_info.continue_prompt
866 obj = line_info.ofind(self)['obj']
889 obj = line_info.ofind(self)['obj']
867 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
890 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
868
891
869 # This should only be active for single-line input!
892 # This should only be active for single-line input!
870 if continue_prompt:
893 if continue_prompt:
871 return line
894 return line
872
895
873 force_auto = isinstance(obj, IPyAutocall)
896 force_auto = isinstance(obj, IPyAutocall)
874 auto_rewrite = True
897 auto_rewrite = True
875
898
876 if pre == ESC_QUOTE:
899 if pre == ESC_QUOTE:
877 # Auto-quote splitting on whitespace
900 # Auto-quote splitting on whitespace
878 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
901 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
879 elif pre == ESC_QUOTE2:
902 elif pre == ESC_QUOTE2:
880 # Auto-quote whole string
903 # Auto-quote whole string
881 newcmd = '%s("%s")' % (ifun,the_rest)
904 newcmd = '%s("%s")' % (ifun,the_rest)
882 elif pre == ESC_PAREN:
905 elif pre == ESC_PAREN:
883 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
906 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
884 else:
907 else:
885 # Auto-paren.
908 # Auto-paren.
886 # We only apply it to argument-less calls if the autocall
909 # We only apply it to argument-less calls if the autocall
887 # parameter is set to 2. We only need to check that autocall is <
910 # parameter is set to 2. We only need to check that autocall is <
888 # 2, since this function isn't called unless it's at least 1.
911 # 2, since this function isn't called unless it's at least 1.
889 if not the_rest and (self.shell.autocall < 2) and not force_auto:
912 if not the_rest and (self.shell.autocall < 2) and not force_auto:
890 newcmd = '%s %s' % (ifun,the_rest)
913 newcmd = '%s %s' % (ifun,the_rest)
891 auto_rewrite = False
914 auto_rewrite = False
892 else:
915 else:
893 if not force_auto and the_rest.startswith('['):
916 if not force_auto and the_rest.startswith('['):
894 if hasattr(obj,'__getitem__'):
917 if hasattr(obj,'__getitem__'):
895 # Don't autocall in this case: item access for an object
918 # Don't autocall in this case: item access for an object
896 # which is BOTH callable and implements __getitem__.
919 # which is BOTH callable and implements __getitem__.
897 newcmd = '%s %s' % (ifun,the_rest)
920 newcmd = '%s %s' % (ifun,the_rest)
898 auto_rewrite = False
921 auto_rewrite = False
899 else:
922 else:
900 # if the object doesn't support [] access, go ahead and
923 # if the object doesn't support [] access, go ahead and
901 # autocall
924 # autocall
902 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
925 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
903 elif the_rest.endswith(';'):
926 elif the_rest.endswith(';'):
904 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
927 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
905 else:
928 else:
906 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
929 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
907
930
908 if auto_rewrite:
931 if auto_rewrite:
909 self.shell.auto_rewrite_input(newcmd)
932 self.shell.auto_rewrite_input(newcmd)
910
933
911 return newcmd
934 return newcmd
912
935
913
936
914 class HelpHandler(PrefilterHandler):
937 class HelpHandler(PrefilterHandler):
915
938
916 handler_name = Str('help')
939 handler_name = Str('help')
917 esc_strings = List([ESC_HELP])
940 esc_strings = List([ESC_HELP])
918
941
919 def handle(self, line_info):
942 def handle(self, line_info):
920 """Try to get some help for the object.
943 """Try to get some help for the object.
921
944
922 obj? or ?obj -> basic information.
945 obj? or ?obj -> basic information.
923 obj?? or ??obj -> more details.
946 obj?? or ??obj -> more details.
924 """
947 """
925 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
948 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
926 line = line_info.line
949 line = line_info.line
927 # We need to make sure that we don't process lines which would be
950 # We need to make sure that we don't process lines which would be
928 # otherwise valid python, such as "x=1 # what?"
951 # otherwise valid python, such as "x=1 # what?"
929 try:
952 try:
930 codeop.compile_command(line)
953 codeop.compile_command(line)
931 except SyntaxError:
954 except SyntaxError:
932 # We should only handle as help stuff which is NOT valid syntax
955 # We should only handle as help stuff which is NOT valid syntax
933 if line[0]==ESC_HELP:
956 if line[0]==ESC_HELP:
934 line = line[1:]
957 line = line[1:]
935 elif line[-1]==ESC_HELP:
958 elif line[-1]==ESC_HELP:
936 line = line[:-1]
959 line = line[:-1]
937 if line:
960 if line:
938 #print 'line:<%r>' % line # dbg
961 #print 'line:<%r>' % line # dbg
939 self.shell.magic_pinfo(line)
962 self.shell.magic_pinfo(line)
940 else:
963 else:
941 self.shell.show_usage()
964 self.shell.show_usage()
942 return '' # Empty string is needed here!
965 return '' # Empty string is needed here!
943 except:
966 except:
944 raise
967 raise
945 # Pass any other exceptions through to the normal handler
968 # Pass any other exceptions through to the normal handler
946 return normal_handler.handle(line_info)
969 return normal_handler.handle(line_info)
947 else:
970 else:
948 # If the code compiles ok, we should handle it normally
971 # If the code compiles ok, we should handle it normally
949 return normal_handler.handle(line_info)
972 return normal_handler.handle(line_info)
950
973
951
974
952 class EmacsHandler(PrefilterHandler):
975 class EmacsHandler(PrefilterHandler):
953
976
954 handler_name = Str('emacs')
977 handler_name = Str('emacs')
955 esc_strings = List([])
978 esc_strings = List([])
956
979
957 def handle(self, line_info):
980 def handle(self, line_info):
958 """Handle input lines marked by python-mode."""
981 """Handle input lines marked by python-mode."""
959
982
960 # Currently, nothing is done. Later more functionality can be added
983 # Currently, nothing is done. Later more functionality can be added
961 # here if needed.
984 # here if needed.
962
985
963 # The input cache shouldn't be updated
986 # The input cache shouldn't be updated
964 return line_info.line
987 return line_info.line
965
988
966
989
967 #-----------------------------------------------------------------------------
990 #-----------------------------------------------------------------------------
968 # Defaults
991 # Defaults
969 #-----------------------------------------------------------------------------
992 #-----------------------------------------------------------------------------
970
993
971
994
972 _default_transformers = [
995 _default_transformers = [
973 AssignSystemTransformer,
996 AssignSystemTransformer,
974 AssignMagicTransformer,
997 AssignMagicTransformer,
975 PyPromptTransformer,
998 PyPromptTransformer,
976 IPyPromptTransformer,
999 IPyPromptTransformer,
977 ]
1000 ]
978
1001
979 _default_checkers = [
1002 _default_checkers = [
980 EmacsChecker,
1003 EmacsChecker,
981 ShellEscapeChecker,
1004 ShellEscapeChecker,
1005 MacroChecker,
982 IPyAutocallChecker,
1006 IPyAutocallChecker,
983 MultiLineMagicChecker,
1007 MultiLineMagicChecker,
984 EscCharsChecker,
1008 EscCharsChecker,
985 AssignmentChecker,
1009 AssignmentChecker,
986 AutoMagicChecker,
1010 AutoMagicChecker,
987 AliasChecker,
1011 AliasChecker,
988 PythonOpsChecker,
1012 PythonOpsChecker,
989 AutocallChecker
1013 AutocallChecker
990 ]
1014 ]
991
1015
992 _default_handlers = [
1016 _default_handlers = [
993 PrefilterHandler,
1017 PrefilterHandler,
994 AliasHandler,
1018 AliasHandler,
995 ShellEscapeHandler,
1019 ShellEscapeHandler,
1020 MacroHandler,
996 MagicHandler,
1021 MagicHandler,
997 AutoHandler,
1022 AutoHandler,
998 HelpHandler,
1023 HelpHandler,
999 EmacsHandler
1024 EmacsHandler
1000 ]
1025 ]
@@ -1,48 +1,114 b''
1 """Tests for the IPython tab-completion machinery.
1 """Tests for the IPython tab-completion machinery.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import sys
9 import sys
10 import unittest
10 import unittest
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.utils.tempdir import TemporaryDirectory
16 from IPython.utils.tempdir import TemporaryDirectory
17 from IPython.core.history import HistoryManager
17 from IPython.core.history import HistoryManager, extract_hist_ranges
18
18
19 def test_history():
19 def test_history():
20
20
21 ip = get_ipython()
21 ip = get_ipython()
22 with TemporaryDirectory() as tmpdir:
22 with TemporaryDirectory() as tmpdir:
23 #tmpdir = '/software/temp'
23 #tmpdir = '/software/temp'
24 histfile = os.path.realpath(os.path.join(tmpdir, 'history.json'))
24 histfile = os.path.realpath(os.path.join(tmpdir, 'history.sqlite'))
25 # Ensure that we restore the history management that we mess with in
25 # Ensure that we restore the history management that we mess with in
26 # this test doesn't affect the IPython instance used by the test suite
26 # this test doesn't affect the IPython instance used by the test suite
27 # beyond this test.
27 # beyond this test.
28 hist_manager_ori = ip.history_manager
28 hist_manager_ori = ip.history_manager
29 try:
29 try:
30 ip.history_manager = HistoryManager(ip)
30 ip.history_manager = HistoryManager(shell=ip)
31 ip.history_manager.hist_file = histfile
31 ip.history_manager.hist_file = histfile
32 ip.history_manager.init_db() # Has to be called after changing file
33 ip.history_manager.reset()
32 print 'test',histfile
34 print 'test',histfile
33 hist = ['a=1\n', 'def f():\n test = 1\n return test\n', 'b=2\n']
35 hist = ['a=1', 'def f():\n test = 1\n return test', 'b=2']
34 # test save and load
36 for i, h in enumerate(hist, start=1):
35 ip.history_manager.input_hist_raw[:] = []
37 ip.history_manager.store_inputs(i, h)
36 for h in hist:
38
37 ip.history_manager.input_hist_raw.append(h)
39 ip.history_manager.db_log_output = True
38 ip.save_history()
40 # Doesn't match the input, but we'll just check it's stored.
39 ip.history_manager.input_hist_raw[:] = []
41 ip.history_manager.output_hist_reprs[3].append("spam")
40 ip.reload_history()
42 ip.history_manager.store_output(3)
41 print type(ip.history_manager.input_hist_raw)
43
42 print ip.history_manager.input_hist_raw
44 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
43 nt.assert_equal(len(ip.history_manager.input_hist_raw), len(hist))
45
44 for i,h in enumerate(hist):
46 # Check lines were written to DB
45 nt.assert_equal(hist[i], ip.history_manager.input_hist_raw[i])
47 c = ip.history_manager.db.execute("SELECT source_raw FROM history")
48 nt.assert_equal([x for x, in c], hist)
49
50 # New session
51 ip.history_manager.reset()
52 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
53 for i, cmd in enumerate(newcmds, start=1):
54 ip.history_manager.store_inputs(i, cmd)
55 gothist = ip.history_manager.get_range(start=1, stop=4)
56 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
57 # Previous session:
58 gothist = ip.history_manager.get_range(-1, 1, 4)
59 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
60
61 # Check get_hist_tail
62 gothist = ip.history_manager.get_tail(4, output=True,
63 include_latest=True)
64 expected = [(1, 3, (hist[-1], ["spam"])),
65 (2, 1, (newcmds[0], None)),
66 (2, 2, (newcmds[1], None)),
67 (2, 3, (newcmds[2], None)),]
68 nt.assert_equal(list(gothist), expected)
69
70 gothist = ip.history_manager.get_tail(2)
71 expected = [(2, 1, newcmds[0]),
72 (2, 2, newcmds[1])]
73 nt.assert_equal(list(gothist), expected)
74
75 # Check get_hist_search
76 gothist = ip.history_manager.search("*test*")
77 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
78 gothist = ip.history_manager.search("b*", output=True)
79 nt.assert_equal(list(gothist), [(1,3,(hist[2],["spam"]))] )
80
81 # Cross testing: check that magic %save can get previous session.
82 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
83 ip.magic_save(testfilename + " ~1/1-3")
84 testfile = open(testfilename, "r")
85 nt.assert_equal(testfile.read(), "\n".join(hist))
86
87 # Duplicate line numbers - check that it doesn't crash, and
88 # gets a new session
89 ip.history_manager.store_inputs(1, "rogue")
90 nt.assert_equal(ip.history_manager.session_number, 3)
46 finally:
91 finally:
47 # Restore history manager
92 # Restore history manager
48 ip.history_manager = hist_manager_ori
93 ip.history_manager = hist_manager_ori
94
95 def test_extract_hist_ranges():
96 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
97 expected = [(0, 1, 2), # 0 == current session
98 (2, 3, 4),
99 (-4, 5, 7),
100 (-4, 7, 10),
101 (-9, 2, None), # None == to end
102 (-8, 1, None),
103 (-7, 1, 6)]
104 actual = list(extract_hist_ranges(instr))
105 nt.assert_equal(actual, expected)
106
107 def test_magic_rerun():
108 """Simple test for %rerun (no args -> rerun last line)"""
109 ip = get_ipython()
110 ip.run_cell("a = 10")
111 ip.run_cell("a += 1")
112 nt.assert_equal(ip.user_ns["a"], 11)
113 ip.run_cell("%rerun")
114 nt.assert_equal(ip.user_ns["a"], 12)
@@ -1,408 +1,417 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions begin
24 # Test functions begin
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 def test_rehashx():
26 def test_rehashx():
27 # clear up everything
27 # clear up everything
28 _ip = get_ipython()
28 _ip = get_ipython()
29 _ip.alias_manager.alias_table.clear()
29 _ip.alias_manager.alias_table.clear()
30 del _ip.db['syscmdlist']
30 del _ip.db['syscmdlist']
31
31
32 _ip.magic('rehashx')
32 _ip.magic('rehashx')
33 # Practically ALL ipython development systems will have more than 10 aliases
33 # Practically ALL ipython development systems will have more than 10 aliases
34
34
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 for key, val in _ip.alias_manager.alias_table.iteritems():
36 for key, val in _ip.alias_manager.alias_table.iteritems():
37 # we must strip dots from alias names
37 # we must strip dots from alias names
38 nt.assert_true('.' not in key)
38 nt.assert_true('.' not in key)
39
39
40 # rehashx must fill up syscmdlist
40 # rehashx must fill up syscmdlist
41 scoms = _ip.db['syscmdlist']
41 scoms = _ip.db['syscmdlist']
42 yield (nt.assert_true, len(scoms) > 10)
42 yield (nt.assert_true, len(scoms) > 10)
43
43
44
44
45 def test_magic_parse_options():
45 def test_magic_parse_options():
46 """Test that we don't mangle paths when parsing magic options."""
46 """Test that we don't mangle paths when parsing magic options."""
47 ip = get_ipython()
47 ip = get_ipython()
48 path = 'c:\\x'
48 path = 'c:\\x'
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 # argv splitting is os-dependent
50 # argv splitting is os-dependent
51 if os.name == 'posix':
51 if os.name == 'posix':
52 expected = 'c:x'
52 expected = 'c:x'
53 else:
53 else:
54 expected = path
54 expected = path
55 nt.assert_equals(opts['f'], expected)
55 nt.assert_equals(opts['f'], expected)
56
56
57
57
58 def doctest_hist_f():
58 def doctest_hist_f():
59 """Test %hist -f with temporary filename.
59 """Test %hist -f with temporary filename.
60
60
61 In [9]: import tempfile
61 In [9]: import tempfile
62
62
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64
64
65 In [11]: %hist -n -f $tfile 3
65 In [11]: %hist -nl -f $tfile 3
66
66
67 In [13]: import os; os.unlink(tfile)
67 In [13]: import os; os.unlink(tfile)
68 """
68 """
69
69
70
70
71 def doctest_hist_r():
71 def doctest_hist_r():
72 """Test %hist -r
72 """Test %hist -r
73
73
74 XXX - This test is not recording the output correctly. For some reason, in
74 XXX - This test is not recording the output correctly. For some reason, in
75 testing mode the raw history isn't getting populated. No idea why.
75 testing mode the raw history isn't getting populated. No idea why.
76 Disabling the output checking for now, though at least we do run it.
76 Disabling the output checking for now, though at least we do run it.
77
77
78 In [1]: 'hist' in _ip.lsmagic()
78 In [1]: 'hist' in _ip.lsmagic()
79 Out[1]: True
79 Out[1]: True
80
80
81 In [2]: x=1
81 In [2]: x=1
82
82
83 In [3]: %hist -r 2
83 In [3]: %hist -rl 2
84 x=1 # random
84 x=1 # random
85 %hist -r 2
85 %hist -r 2
86 """
86 """
87
87
88 def doctest_hist_op():
88 def doctest_hist_op():
89 """Test %hist -op
89 """Test %hist -op
90
90
91 In [1]: class b:
91 In [1]: class b:
92 ...: pass
92 ...: pass
93 ...:
93 ...:
94
94
95 In [2]: class s(b):
95 In [2]: class s(b):
96 ...: def __str__(self):
96 ...: def __str__(self):
97 ...: return 's'
97 ...: return 's'
98 ...:
98 ...:
99
99
100 In [3]:
100 In [3]:
101
101
102 In [4]: class r(b):
102 In [4]: class r(b):
103 ...: def __repr__(self):
103 ...: def __repr__(self):
104 ...: return 'r'
104 ...: return 'r'
105 ...:
105 ...:
106
106
107 In [5]: class sr(s,r): pass
107 In [5]: class sr(s,r): pass
108 ...:
108 ...:
109
109
110 In [6]:
110 In [6]:
111
111
112 In [7]: bb=b()
112 In [7]: bb=b()
113
113
114 In [8]: ss=s()
114 In [8]: ss=s()
115
115
116 In [9]: rr=r()
116 In [9]: rr=r()
117
117
118 In [10]: ssrr=sr()
118 In [10]: ssrr=sr()
119
119
120 In [11]: bb
120 In [11]: bb
121 Out[11]: <...b instance at ...>
121 Out[11]: <...b instance at ...>
122
122
123 In [12]: ss
123 In [12]: ss
124 Out[12]: <...s instance at ...>
124 Out[12]: <...s instance at ...>
125
125
126 In [13]:
126 In [13]:
127
127
128 In [14]: %hist -op
128 In [14]: %hist -op
129 >>> class b:
129 >>> class b:
130 ... pass
130 ... pass
131 ...
131 ...
132 >>> class s(b):
132 >>> class s(b):
133 ... def __str__(self):
133 ... def __str__(self):
134 ... return 's'
134 ... return 's'
135 ...
135 ...
136 >>>
136 >>>
137 >>> class r(b):
137 >>> class r(b):
138 ... def __repr__(self):
138 ... def __repr__(self):
139 ... return 'r'
139 ... return 'r'
140 ...
140 ...
141 >>> class sr(s,r): pass
141 >>> class sr(s,r): pass
142 >>>
142 >>>
143 >>> bb=b()
143 >>> bb=b()
144 >>> ss=s()
144 >>> ss=s()
145 >>> rr=r()
145 >>> rr=r()
146 >>> ssrr=sr()
146 >>> ssrr=sr()
147 >>> bb
147 >>> bb
148 <...b instance at ...>
148 <...b instance at ...>
149 >>> ss
149 >>> ss
150 <...s instance at ...>
150 <...s instance at ...>
151 >>>
151 >>>
152 """
152 """
153
153
154 def test_shist():
154 def test_macro():
155 # Simple tests of ShadowHist class - test generator.
155 ip = get_ipython()
156 import os, shutil, tempfile
156 ip.history_manager.reset() # Clear any existing history.
157
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
158 from IPython.utils import pickleshare
158 for i, cmd in enumerate(cmds, start=1):
159 from IPython.core.history import ShadowHist
159 ip.history_manager.store_inputs(i, cmd)
160
160 ip.magic("macro test 1-3")
161 tfile = tempfile.mktemp('','tmp-ipython-')
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
162
163 db = pickleshare.PickleShareDB(tfile)
164 s = ShadowHist(db, get_ipython())
165 s.add('hello')
166 s.add('world')
167 s.add('hello')
168 s.add('hello')
169 s.add('karhu')
170
171 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
172
173 yield nt.assert_equal,s.get(2),'world'
174
162
175 shutil.rmtree(tfile)
163 # List macros.
164 assert "test" in ip.magic("macro")
165
166 def test_macro_run():
167 """Test that we can run a multi-line macro successfully."""
168 ip = get_ipython()
169 ip.history_manager.reset()
170 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
171 for cmd in cmds:
172 ip.run_cell(cmd)
173 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
174 original_stdout = sys.stdout
175 new_stdout = StringIO()
176 sys.stdout = new_stdout
177 try:
178 ip.run_cell("test")
179 nt.assert_true("12" in new_stdout.getvalue())
180 ip.run_cell("test")
181 nt.assert_true("13" in new_stdout.getvalue())
182 finally:
183 sys.stdout = original_stdout
184 new_stdout.close()
176
185
177
186
178 # XXX failing for now, until we get clearcmd out of quarantine. But we should
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
179 # fix this and revert the skip to happen only if numpy is not around.
188 # fix this and revert the skip to happen only if numpy is not around.
180 #@dec.skipif_not_numpy
189 #@dec.skipif_not_numpy
181 @dec.skip_known_failure
190 @dec.skip_known_failure
182 def test_numpy_clear_array_undec():
191 def test_numpy_clear_array_undec():
183 from IPython.extensions import clearcmd
192 from IPython.extensions import clearcmd
184
193
185 _ip.ex('import numpy as np')
194 _ip.ex('import numpy as np')
186 _ip.ex('a = np.empty(2)')
195 _ip.ex('a = np.empty(2)')
187 yield (nt.assert_true, 'a' in _ip.user_ns)
196 yield (nt.assert_true, 'a' in _ip.user_ns)
188 _ip.magic('clear array')
197 _ip.magic('clear array')
189 yield (nt.assert_false, 'a' in _ip.user_ns)
198 yield (nt.assert_false, 'a' in _ip.user_ns)
190
199
191
200
192 # Multiple tests for clipboard pasting
201 # Multiple tests for clipboard pasting
193 @dec.parametric
202 @dec.parametric
194 def test_paste():
203 def test_paste():
195 _ip = get_ipython()
204 _ip = get_ipython()
196 def paste(txt, flags='-q'):
205 def paste(txt, flags='-q'):
197 """Paste input text, by default in quiet mode"""
206 """Paste input text, by default in quiet mode"""
198 hooks.clipboard_get = lambda : txt
207 hooks.clipboard_get = lambda : txt
199 _ip.magic('paste '+flags)
208 _ip.magic('paste '+flags)
200
209
201 # Inject fake clipboard hook but save original so we can restore it later
210 # Inject fake clipboard hook but save original so we can restore it later
202 hooks = _ip.hooks
211 hooks = _ip.hooks
203 user_ns = _ip.user_ns
212 user_ns = _ip.user_ns
204 original_clip = hooks.clipboard_get
213 original_clip = hooks.clipboard_get
205
214
206 try:
215 try:
207 # This try/except with an emtpy except clause is here only because
216 # This try/except with an emtpy except clause is here only because
208 # try/yield/finally is invalid syntax in Python 2.4. This will be
217 # try/yield/finally is invalid syntax in Python 2.4. This will be
209 # removed when we drop 2.4-compatibility, and the emtpy except below
218 # removed when we drop 2.4-compatibility, and the emtpy except below
210 # will be changed to a finally.
219 # will be changed to a finally.
211
220
212 # Run tests with fake clipboard function
221 # Run tests with fake clipboard function
213 user_ns.pop('x', None)
222 user_ns.pop('x', None)
214 paste('x=1')
223 paste('x=1')
215 yield nt.assert_equal(user_ns['x'], 1)
224 yield nt.assert_equal(user_ns['x'], 1)
216
225
217 user_ns.pop('x', None)
226 user_ns.pop('x', None)
218 paste('>>> x=2')
227 paste('>>> x=2')
219 yield nt.assert_equal(user_ns['x'], 2)
228 yield nt.assert_equal(user_ns['x'], 2)
220
229
221 paste("""
230 paste("""
222 >>> x = [1,2,3]
231 >>> x = [1,2,3]
223 >>> y = []
232 >>> y = []
224 >>> for i in x:
233 >>> for i in x:
225 ... y.append(i**2)
234 ... y.append(i**2)
226 ...
235 ...
227 """)
236 """)
228 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 yield nt.assert_equal(user_ns['x'], [1,2,3])
229 yield nt.assert_equal(user_ns['y'], [1,4,9])
238 yield nt.assert_equal(user_ns['y'], [1,4,9])
230
239
231 # Now, test that paste -r works
240 # Now, test that paste -r works
232 user_ns.pop('x', None)
241 user_ns.pop('x', None)
233 yield nt.assert_false('x' in user_ns)
242 yield nt.assert_false('x' in user_ns)
234 _ip.magic('paste -r')
243 _ip.magic('paste -r')
235 yield nt.assert_equal(user_ns['x'], [1,2,3])
244 yield nt.assert_equal(user_ns['x'], [1,2,3])
236
245
237 # Also test paste echoing, by temporarily faking the writer
246 # Also test paste echoing, by temporarily faking the writer
238 w = StringIO()
247 w = StringIO()
239 writer = _ip.write
248 writer = _ip.write
240 _ip.write = w.write
249 _ip.write = w.write
241 code = """
250 code = """
242 a = 100
251 a = 100
243 b = 200"""
252 b = 200"""
244 try:
253 try:
245 paste(code,'')
254 paste(code,'')
246 out = w.getvalue()
255 out = w.getvalue()
247 finally:
256 finally:
248 _ip.write = writer
257 _ip.write = writer
249 yield nt.assert_equal(user_ns['a'], 100)
258 yield nt.assert_equal(user_ns['a'], 100)
250 yield nt.assert_equal(user_ns['b'], 200)
259 yield nt.assert_equal(user_ns['b'], 200)
251 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
252
261
253 finally:
262 finally:
254 # This should be in a finally clause, instead of the bare except above.
263 # This should be in a finally clause, instead of the bare except above.
255 # Restore original hook
264 # Restore original hook
256 hooks.clipboard_get = original_clip
265 hooks.clipboard_get = original_clip
257
266
258
267
259 def test_time():
268 def test_time():
260 _ip.magic('time None')
269 _ip.magic('time None')
261
270
262
271
263 def doctest_time():
272 def doctest_time():
264 """
273 """
265 In [10]: %time None
274 In [10]: %time None
266 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
267 Wall time: 0.00 s
276 Wall time: 0.00 s
268 """
277 """
269
278
270
279
271 def test_doctest_mode():
280 def test_doctest_mode():
272 "Toggle doctest_mode twice, it should be a no-op and run without error"
281 "Toggle doctest_mode twice, it should be a no-op and run without error"
273 _ip.magic('doctest_mode')
282 _ip.magic('doctest_mode')
274 _ip.magic('doctest_mode')
283 _ip.magic('doctest_mode')
275
284
276
285
277 def test_parse_options():
286 def test_parse_options():
278 """Tests for basic options parsing in magics."""
287 """Tests for basic options parsing in magics."""
279 # These are only the most minimal of tests, more should be added later. At
288 # These are only the most minimal of tests, more should be added later. At
280 # the very least we check that basic text/unicode calls work OK.
289 # the very least we check that basic text/unicode calls work OK.
281 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
290 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
282 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
291 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
283
292
284
293
285 def test_dirops():
294 def test_dirops():
286 """Test various directory handling operations."""
295 """Test various directory handling operations."""
287 curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
296 curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
288
297
289 startdir = os.getcwd()
298 startdir = os.getcwd()
290 ipdir = _ip.ipython_dir
299 ipdir = _ip.ipython_dir
291 try:
300 try:
292 _ip.magic('cd "%s"' % ipdir)
301 _ip.magic('cd "%s"' % ipdir)
293 nt.assert_equal(curpath(), ipdir)
302 nt.assert_equal(curpath(), ipdir)
294 _ip.magic('cd -')
303 _ip.magic('cd -')
295 nt.assert_equal(curpath(), startdir)
304 nt.assert_equal(curpath(), startdir)
296 _ip.magic('pushd "%s"' % ipdir)
305 _ip.magic('pushd "%s"' % ipdir)
297 nt.assert_equal(curpath(), ipdir)
306 nt.assert_equal(curpath(), ipdir)
298 _ip.magic('popd')
307 _ip.magic('popd')
299 nt.assert_equal(curpath(), startdir)
308 nt.assert_equal(curpath(), startdir)
300 finally:
309 finally:
301 os.chdir(startdir)
310 os.chdir(startdir)
302
311
303
312
304 def check_cpaste(code, should_fail=False):
313 def check_cpaste(code, should_fail=False):
305 """Execute code via 'cpaste' and ensure it was executed, unless
314 """Execute code via 'cpaste' and ensure it was executed, unless
306 should_fail is set.
315 should_fail is set.
307 """
316 """
308 _ip.user_ns['code_ran'] = False
317 _ip.user_ns['code_ran'] = False
309
318
310 src = StringIO()
319 src = StringIO()
311 src.write('\n')
320 src.write('\n')
312 src.write(code)
321 src.write(code)
313 src.write('\n--\n')
322 src.write('\n--\n')
314 src.seek(0)
323 src.seek(0)
315
324
316 stdin_save = sys.stdin
325 stdin_save = sys.stdin
317 sys.stdin = src
326 sys.stdin = src
318
327
319 try:
328 try:
320 _ip.magic('cpaste')
329 _ip.magic('cpaste')
321 except:
330 except:
322 if not should_fail:
331 if not should_fail:
323 raise AssertionError("Failure not expected : '%s'" %
332 raise AssertionError("Failure not expected : '%s'" %
324 code)
333 code)
325 else:
334 else:
326 assert _ip.user_ns['code_ran']
335 assert _ip.user_ns['code_ran']
327 if should_fail:
336 if should_fail:
328 raise AssertionError("Failure expected : '%s'" % code)
337 raise AssertionError("Failure expected : '%s'" % code)
329 finally:
338 finally:
330 sys.stdin = stdin_save
339 sys.stdin = stdin_save
331
340
332
341
333 def test_cpaste():
342 def test_cpaste():
334 """Test cpaste magic"""
343 """Test cpaste magic"""
335
344
336 def run():
345 def run():
337 """Marker function: sets a flag when executed.
346 """Marker function: sets a flag when executed.
338 """
347 """
339 _ip.user_ns['code_ran'] = True
348 _ip.user_ns['code_ran'] = True
340 return 'run' # return string so '+ run()' doesn't result in success
349 return 'run' # return string so '+ run()' doesn't result in success
341
350
342 tests = {'pass': ["> > > run()",
351 tests = {'pass': ["> > > run()",
343 ">>> > run()",
352 ">>> > run()",
344 "+++ run()",
353 "+++ run()",
345 "++ run()",
354 "++ run()",
346 " >>> run()"],
355 " >>> run()"],
347
356
348 'fail': ["+ + run()",
357 'fail': ["+ + run()",
349 " ++ run()"]}
358 " ++ run()"]}
350
359
351 _ip.user_ns['run'] = run
360 _ip.user_ns['run'] = run
352
361
353 for code in tests['pass']:
362 for code in tests['pass']:
354 check_cpaste(code)
363 check_cpaste(code)
355
364
356 for code in tests['fail']:
365 for code in tests['fail']:
357 check_cpaste(code, should_fail=True)
366 check_cpaste(code, should_fail=True)
358
367
359 def test_xmode():
368 def test_xmode():
360 # Calling xmode three times should be a no-op
369 # Calling xmode three times should be a no-op
361 xmode = _ip.InteractiveTB.mode
370 xmode = _ip.InteractiveTB.mode
362 for i in range(3):
371 for i in range(3):
363 _ip.magic("xmode")
372 _ip.magic("xmode")
364 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
373 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
365
374
366 def doctest_who():
375 def doctest_who():
367 """doctest for %who
376 """doctest for %who
368
377
369 In [1]: %reset -f
378 In [1]: %reset -f
370
379
371 In [2]: alpha = 123
380 In [2]: alpha = 123
372
381
373 In [3]: beta = 'beta'
382 In [3]: beta = 'beta'
374
383
375 In [4]: %who int
384 In [4]: %who int
376 alpha
385 alpha
377
386
378 In [5]: %who str
387 In [5]: %who str
379 beta
388 beta
380
389
381 In [6]: %whos
390 In [6]: %whos
382 Variable Type Data/Info
391 Variable Type Data/Info
383 ----------------------------
392 ----------------------------
384 alpha int 123
393 alpha int 123
385 beta str beta
394 beta str beta
386
395
387 In [7]: %who_ls
396 In [7]: %who_ls
388 Out[7]: ['alpha', 'beta']
397 Out[7]: ['alpha', 'beta']
389 """
398 """
390
399
391 def doctest_precision():
400 def doctest_precision():
392 """doctest for %precision
401 """doctest for %precision
393
402
394 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
403 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
395
404
396 In [2]: %precision 5
405 In [2]: %precision 5
397 Out[2]: '%.5f'
406 Out[2]: '%.5f'
398
407
399 In [3]: f.float_format
408 In [3]: f.float_format
400 Out[3]: '%.5f'
409 Out[3]: '%.5f'
401
410
402 In [4]: %precision %e
411 In [4]: %precision %e
403 Out[4]: '%e'
412 Out[4]: '%e'
404
413
405 In [5]: f(3.1415927)
414 In [5]: f(3.1415927)
406 Out[5]: '3.141593e+00'
415 Out[5]: '3.141593e+00'
407 """
416 """
408
417
@@ -1,493 +1,490 b''
1 """ A FrontendWidget that emulates the interface of the console IPython and
1 """ A FrontendWidget that emulates the interface of the console IPython and
2 supports the additional functionality provided by the IPython kernel.
2 supports the additional functionality provided by the IPython kernel.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Imports
6 # Imports
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8
8
9 # Standard library imports
9 # Standard library imports
10 from collections import namedtuple
10 from collections import namedtuple
11 import re
11 import re
12 from subprocess import Popen
12 from subprocess import Popen
13 from textwrap import dedent
13 from textwrap import dedent
14
14
15 # System library imports
15 # System library imports
16 from IPython.external.qt import QtCore, QtGui
16 from IPython.external.qt import QtCore, QtGui
17
17
18 # Local imports
18 # Local imports
19 from IPython.core.inputsplitter import IPythonInputSplitter, \
19 from IPython.core.inputsplitter import IPythonInputSplitter, \
20 transform_ipy_prompt
20 transform_ipy_prompt
21 from IPython.core.usage import default_gui_banner
21 from IPython.core.usage import default_gui_banner
22 from IPython.utils.traitlets import Bool, Str
22 from IPython.utils.traitlets import Bool, Str
23 from frontend_widget import FrontendWidget
23 from frontend_widget import FrontendWidget
24 from styles import (default_light_style_sheet, default_light_syntax_style,
24 from styles import (default_light_style_sheet, default_light_syntax_style,
25 default_dark_style_sheet, default_dark_syntax_style,
25 default_dark_style_sheet, default_dark_syntax_style,
26 default_bw_style_sheet, default_bw_syntax_style)
26 default_bw_style_sheet, default_bw_syntax_style)
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Constants
29 # Constants
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 # Default strings to build and display input and output prompts (and separators
32 # Default strings to build and display input and output prompts (and separators
33 # in between)
33 # in between)
34 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
34 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
35 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
35 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
36 default_input_sep = '\n'
36 default_input_sep = '\n'
37 default_output_sep = ''
37 default_output_sep = ''
38 default_output_sep2 = ''
38 default_output_sep2 = ''
39
39
40 # Base path for most payload sources.
40 # Base path for most payload sources.
41 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
41 zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell'
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # IPythonWidget class
44 # IPythonWidget class
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 class IPythonWidget(FrontendWidget):
47 class IPythonWidget(FrontendWidget):
48 """ A FrontendWidget for an IPython kernel.
48 """ A FrontendWidget for an IPython kernel.
49 """
49 """
50
50
51 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
51 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
52 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
52 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
53 # settings.
53 # settings.
54 custom_edit = Bool(False)
54 custom_edit = Bool(False)
55 custom_edit_requested = QtCore.Signal(object, object)
55 custom_edit_requested = QtCore.Signal(object, object)
56
56
57 # A command for invoking a system text editor. If the string contains a
57 # A command for invoking a system text editor. If the string contains a
58 # {filename} format specifier, it will be used. Otherwise, the filename will
58 # {filename} format specifier, it will be used. Otherwise, the filename will
59 # be appended to the end the command.
59 # be appended to the end the command.
60 editor = Str('default', config=True)
60 editor = Str('default', config=True)
61
61
62 # The editor command to use when a specific line number is requested. The
62 # The editor command to use when a specific line number is requested. The
63 # string should contain two format specifiers: {line} and {filename}. If
63 # string should contain two format specifiers: {line} and {filename}. If
64 # this parameter is not specified, the line number option to the %edit magic
64 # this parameter is not specified, the line number option to the %edit magic
65 # will be ignored.
65 # will be ignored.
66 editor_line = Str(config=True)
66 editor_line = Str(config=True)
67
67
68 # A CSS stylesheet. The stylesheet can contain classes for:
68 # A CSS stylesheet. The stylesheet can contain classes for:
69 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
69 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
70 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
70 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
71 # 3. IPython: .error, .in-prompt, .out-prompt, etc
71 # 3. IPython: .error, .in-prompt, .out-prompt, etc
72 style_sheet = Str(config=True)
72 style_sheet = Str(config=True)
73
73
74 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
74 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
75 # the style sheet is queried for Pygments style information.
75 # the style sheet is queried for Pygments style information.
76 syntax_style = Str(config=True)
76 syntax_style = Str(config=True)
77
77
78 # Prompts.
78 # Prompts.
79 in_prompt = Str(default_in_prompt, config=True)
79 in_prompt = Str(default_in_prompt, config=True)
80 out_prompt = Str(default_out_prompt, config=True)
80 out_prompt = Str(default_out_prompt, config=True)
81 input_sep = Str(default_input_sep, config=True)
81 input_sep = Str(default_input_sep, config=True)
82 output_sep = Str(default_output_sep, config=True)
82 output_sep = Str(default_output_sep, config=True)
83 output_sep2 = Str(default_output_sep2, config=True)
83 output_sep2 = Str(default_output_sep2, config=True)
84
84
85 # FrontendWidget protected class variables.
85 # FrontendWidget protected class variables.
86 _input_splitter_class = IPythonInputSplitter
86 _input_splitter_class = IPythonInputSplitter
87
87
88 # IPythonWidget protected class variables.
88 # IPythonWidget protected class variables.
89 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
89 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
90 _payload_source_edit = zmq_shell_source + '.edit_magic'
90 _payload_source_edit = zmq_shell_source + '.edit_magic'
91 _payload_source_exit = zmq_shell_source + '.ask_exit'
91 _payload_source_exit = zmq_shell_source + '.ask_exit'
92 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
92 _payload_source_loadpy = zmq_shell_source + '.magic_loadpy'
93 _payload_source_page = 'IPython.zmq.page.page'
93 _payload_source_page = 'IPython.zmq.page.page'
94
94
95 #---------------------------------------------------------------------------
95 #---------------------------------------------------------------------------
96 # 'object' interface
96 # 'object' interface
97 #---------------------------------------------------------------------------
97 #---------------------------------------------------------------------------
98
98
99 def __init__(self, *args, **kw):
99 def __init__(self, *args, **kw):
100 super(IPythonWidget, self).__init__(*args, **kw)
100 super(IPythonWidget, self).__init__(*args, **kw)
101
101
102 # IPythonWidget protected variables.
102 # IPythonWidget protected variables.
103 self._code_to_load = None
103 self._code_to_load = None
104 self._payload_handlers = {
104 self._payload_handlers = {
105 self._payload_source_edit : self._handle_payload_edit,
105 self._payload_source_edit : self._handle_payload_edit,
106 self._payload_source_exit : self._handle_payload_exit,
106 self._payload_source_exit : self._handle_payload_exit,
107 self._payload_source_page : self._handle_payload_page,
107 self._payload_source_page : self._handle_payload_page,
108 self._payload_source_loadpy : self._handle_payload_loadpy }
108 self._payload_source_loadpy : self._handle_payload_loadpy }
109 self._previous_prompt_obj = None
109 self._previous_prompt_obj = None
110 self._keep_kernel_on_exit = None
110 self._keep_kernel_on_exit = None
111
111
112 # Initialize widget styling.
112 # Initialize widget styling.
113 if self.style_sheet:
113 if self.style_sheet:
114 self._style_sheet_changed()
114 self._style_sheet_changed()
115 self._syntax_style_changed()
115 self._syntax_style_changed()
116 else:
116 else:
117 self.set_default_style()
117 self.set_default_style()
118
118
119 #---------------------------------------------------------------------------
119 #---------------------------------------------------------------------------
120 # 'BaseFrontendMixin' abstract interface
120 # 'BaseFrontendMixin' abstract interface
121 #---------------------------------------------------------------------------
121 #---------------------------------------------------------------------------
122
122
123 def _handle_complete_reply(self, rep):
123 def _handle_complete_reply(self, rep):
124 """ Reimplemented to support IPython's improved completion machinery.
124 """ Reimplemented to support IPython's improved completion machinery.
125 """
125 """
126 cursor = self._get_cursor()
126 cursor = self._get_cursor()
127 info = self._request_info.get('complete')
127 info = self._request_info.get('complete')
128 if info and info.id == rep['parent_header']['msg_id'] and \
128 if info and info.id == rep['parent_header']['msg_id'] and \
129 info.pos == cursor.position():
129 info.pos == cursor.position():
130 matches = rep['content']['matches']
130 matches = rep['content']['matches']
131 text = rep['content']['matched_text']
131 text = rep['content']['matched_text']
132 offset = len(text)
132 offset = len(text)
133
133
134 # Clean up matches with period and path separators if the matched
134 # Clean up matches with period and path separators if the matched
135 # text has not been transformed. This is done by truncating all
135 # text has not been transformed. This is done by truncating all
136 # but the last component and then suitably decreasing the offset
136 # but the last component and then suitably decreasing the offset
137 # between the current cursor position and the start of completion.
137 # between the current cursor position and the start of completion.
138 if len(matches) > 1 and matches[0][:offset] == text:
138 if len(matches) > 1 and matches[0][:offset] == text:
139 parts = re.split(r'[./\\]', text)
139 parts = re.split(r'[./\\]', text)
140 sep_count = len(parts) - 1
140 sep_count = len(parts) - 1
141 if sep_count:
141 if sep_count:
142 chop_length = sum(map(len, parts[:sep_count])) + sep_count
142 chop_length = sum(map(len, parts[:sep_count])) + sep_count
143 matches = [ match[chop_length:] for match in matches ]
143 matches = [ match[chop_length:] for match in matches ]
144 offset -= chop_length
144 offset -= chop_length
145
145
146 # Move the cursor to the start of the match and complete.
146 # Move the cursor to the start of the match and complete.
147 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
147 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
148 self._complete_with_items(cursor, matches)
148 self._complete_with_items(cursor, matches)
149
149
150 def _handle_execute_reply(self, msg):
150 def _handle_execute_reply(self, msg):
151 """ Reimplemented to support prompt requests.
151 """ Reimplemented to support prompt requests.
152 """
152 """
153 info = self._request_info.get('execute')
153 info = self._request_info.get('execute')
154 if info and info.id == msg['parent_header']['msg_id']:
154 if info and info.id == msg['parent_header']['msg_id']:
155 if info.kind == 'prompt':
155 if info.kind == 'prompt':
156 number = msg['content']['execution_count'] + 1
156 number = msg['content']['execution_count'] + 1
157 self._show_interpreter_prompt(number)
157 self._show_interpreter_prompt(number)
158 else:
158 else:
159 super(IPythonWidget, self)._handle_execute_reply(msg)
159 super(IPythonWidget, self)._handle_execute_reply(msg)
160
160
161 def _handle_history_reply(self, msg):
161 def _handle_history_tail_reply(self, msg):
162 """ Implemented to handle history replies, which are only supported by
162 """ Implemented to handle history tail replies, which are only supported
163 the IPython kernel.
163 by the IPython kernel.
164 """
164 """
165 history_dict = msg['content']['history']
165 history_items = msg['content']['history']
166 input_history_dict = {}
166 items = [ line.rstrip() for _, _, line in history_items ]
167 for key,val in history_dict.items():
168 input_history_dict[int(key)] = val
169 items = [ val.rstrip() for _, val in sorted(input_history_dict.items()) ]
170 self._set_history(items)
167 self._set_history(items)
171
168
172 def _handle_pyout(self, msg):
169 def _handle_pyout(self, msg):
173 """ Reimplemented for IPython-style "display hook".
170 """ Reimplemented for IPython-style "display hook".
174 """
171 """
175 if not self._hidden and self._is_from_this_session(msg):
172 if not self._hidden and self._is_from_this_session(msg):
176 content = msg['content']
173 content = msg['content']
177 prompt_number = content['execution_count']
174 prompt_number = content['execution_count']
178 data = content['data']
175 data = content['data']
179 if data.has_key('text/html'):
176 if data.has_key('text/html'):
180 self._append_plain_text(self.output_sep)
177 self._append_plain_text(self.output_sep)
181 self._append_html(self._make_out_prompt(prompt_number))
178 self._append_html(self._make_out_prompt(prompt_number))
182 html = data['text/html']
179 html = data['text/html']
183 self._append_plain_text('\n')
180 self._append_plain_text('\n')
184 self._append_html(html + self.output_sep2)
181 self._append_html(html + self.output_sep2)
185 elif data.has_key('text/plain'):
182 elif data.has_key('text/plain'):
186 self._append_plain_text(self.output_sep)
183 self._append_plain_text(self.output_sep)
187 self._append_html(self._make_out_prompt(prompt_number))
184 self._append_html(self._make_out_prompt(prompt_number))
188 text = data['text/plain']
185 text = data['text/plain']
189 self._append_plain_text(text + self.output_sep2)
186 self._append_plain_text(text + self.output_sep2)
190
187
191 def _handle_display_data(self, msg):
188 def _handle_display_data(self, msg):
192 """ The base handler for the ``display_data`` message.
189 """ The base handler for the ``display_data`` message.
193 """
190 """
194 # For now, we don't display data from other frontends, but we
191 # For now, we don't display data from other frontends, but we
195 # eventually will as this allows all frontends to monitor the display
192 # eventually will as this allows all frontends to monitor the display
196 # data. But we need to figure out how to handle this in the GUI.
193 # data. But we need to figure out how to handle this in the GUI.
197 if not self._hidden and self._is_from_this_session(msg):
194 if not self._hidden and self._is_from_this_session(msg):
198 source = msg['content']['source']
195 source = msg['content']['source']
199 data = msg['content']['data']
196 data = msg['content']['data']
200 metadata = msg['content']['metadata']
197 metadata = msg['content']['metadata']
201 # In the regular IPythonWidget, we simply print the plain text
198 # In the regular IPythonWidget, we simply print the plain text
202 # representation.
199 # representation.
203 if data.has_key('text/html'):
200 if data.has_key('text/html'):
204 html = data['text/html']
201 html = data['text/html']
205 self._append_html(html)
202 self._append_html(html)
206 elif data.has_key('text/plain'):
203 elif data.has_key('text/plain'):
207 text = data['text/plain']
204 text = data['text/plain']
208 self._append_plain_text(text)
205 self._append_plain_text(text)
209 # This newline seems to be needed for text and html output.
206 # This newline seems to be needed for text and html output.
210 self._append_plain_text(u'\n')
207 self._append_plain_text(u'\n')
211
208
212 def _started_channels(self):
209 def _started_channels(self):
213 """ Reimplemented to make a history request.
210 """ Reimplemented to make a history request.
214 """
211 """
215 super(IPythonWidget, self)._started_channels()
212 super(IPythonWidget, self)._started_channels()
216 self.kernel_manager.xreq_channel.history(raw=True, output=False)
213 self.kernel_manager.xreq_channel.history_tail(1000)
217
214
218 #---------------------------------------------------------------------------
215 #---------------------------------------------------------------------------
219 # 'ConsoleWidget' public interface
216 # 'ConsoleWidget' public interface
220 #---------------------------------------------------------------------------
217 #---------------------------------------------------------------------------
221
218
222 def copy(self):
219 def copy(self):
223 """ Copy the currently selected text to the clipboard, removing prompts
220 """ Copy the currently selected text to the clipboard, removing prompts
224 if possible.
221 if possible.
225 """
222 """
226 text = self._control.textCursor().selection().toPlainText()
223 text = self._control.textCursor().selection().toPlainText()
227 if text:
224 if text:
228 lines = map(transform_ipy_prompt, text.splitlines())
225 lines = map(transform_ipy_prompt, text.splitlines())
229 text = '\n'.join(lines)
226 text = '\n'.join(lines)
230 QtGui.QApplication.clipboard().setText(text)
227 QtGui.QApplication.clipboard().setText(text)
231
228
232 #---------------------------------------------------------------------------
229 #---------------------------------------------------------------------------
233 # 'FrontendWidget' public interface
230 # 'FrontendWidget' public interface
234 #---------------------------------------------------------------------------
231 #---------------------------------------------------------------------------
235
232
236 def execute_file(self, path, hidden=False):
233 def execute_file(self, path, hidden=False):
237 """ Reimplemented to use the 'run' magic.
234 """ Reimplemented to use the 'run' magic.
238 """
235 """
239 self.execute('%%run %s' % path, hidden=hidden)
236 self.execute('%%run %s' % path, hidden=hidden)
240
237
241 #---------------------------------------------------------------------------
238 #---------------------------------------------------------------------------
242 # 'FrontendWidget' protected interface
239 # 'FrontendWidget' protected interface
243 #---------------------------------------------------------------------------
240 #---------------------------------------------------------------------------
244
241
245 def _complete(self):
242 def _complete(self):
246 """ Reimplemented to support IPython's improved completion machinery.
243 """ Reimplemented to support IPython's improved completion machinery.
247 """
244 """
248 # We let the kernel split the input line, so we *always* send an empty
245 # We let the kernel split the input line, so we *always* send an empty
249 # text field. Readline-based frontends do get a real text field which
246 # text field. Readline-based frontends do get a real text field which
250 # they can use.
247 # they can use.
251 text = ''
248 text = ''
252
249
253 # Send the completion request to the kernel
250 # Send the completion request to the kernel
254 msg_id = self.kernel_manager.xreq_channel.complete(
251 msg_id = self.kernel_manager.xreq_channel.complete(
255 text, # text
252 text, # text
256 self._get_input_buffer_cursor_line(), # line
253 self._get_input_buffer_cursor_line(), # line
257 self._get_input_buffer_cursor_column(), # cursor_pos
254 self._get_input_buffer_cursor_column(), # cursor_pos
258 self.input_buffer) # block
255 self.input_buffer) # block
259 pos = self._get_cursor().position()
256 pos = self._get_cursor().position()
260 info = self._CompletionRequest(msg_id, pos)
257 info = self._CompletionRequest(msg_id, pos)
261 self._request_info['complete'] = info
258 self._request_info['complete'] = info
262
259
263 def _get_banner(self):
260 def _get_banner(self):
264 """ Reimplemented to return IPython's default banner.
261 """ Reimplemented to return IPython's default banner.
265 """
262 """
266 return default_gui_banner
263 return default_gui_banner
267
264
268 def _process_execute_error(self, msg):
265 def _process_execute_error(self, msg):
269 """ Reimplemented for IPython-style traceback formatting.
266 """ Reimplemented for IPython-style traceback formatting.
270 """
267 """
271 content = msg['content']
268 content = msg['content']
272 traceback = '\n'.join(content['traceback']) + '\n'
269 traceback = '\n'.join(content['traceback']) + '\n'
273 if False:
270 if False:
274 # FIXME: For now, tracebacks come as plain text, so we can't use
271 # FIXME: For now, tracebacks come as plain text, so we can't use
275 # the html renderer yet. Once we refactor ultratb to produce
272 # the html renderer yet. Once we refactor ultratb to produce
276 # properly styled tracebacks, this branch should be the default
273 # properly styled tracebacks, this branch should be the default
277 traceback = traceback.replace(' ', '&nbsp;')
274 traceback = traceback.replace(' ', '&nbsp;')
278 traceback = traceback.replace('\n', '<br/>')
275 traceback = traceback.replace('\n', '<br/>')
279
276
280 ename = content['ename']
277 ename = content['ename']
281 ename_styled = '<span class="error">%s</span>' % ename
278 ename_styled = '<span class="error">%s</span>' % ename
282 traceback = traceback.replace(ename, ename_styled)
279 traceback = traceback.replace(ename, ename_styled)
283
280
284 self._append_html(traceback)
281 self._append_html(traceback)
285 else:
282 else:
286 # This is the fallback for now, using plain text with ansi escapes
283 # This is the fallback for now, using plain text with ansi escapes
287 self._append_plain_text(traceback)
284 self._append_plain_text(traceback)
288
285
289 def _process_execute_payload(self, item):
286 def _process_execute_payload(self, item):
290 """ Reimplemented to dispatch payloads to handler methods.
287 """ Reimplemented to dispatch payloads to handler methods.
291 """
288 """
292 handler = self._payload_handlers.get(item['source'])
289 handler = self._payload_handlers.get(item['source'])
293 if handler is None:
290 if handler is None:
294 # We have no handler for this type of payload, simply ignore it
291 # We have no handler for this type of payload, simply ignore it
295 return False
292 return False
296 else:
293 else:
297 handler(item)
294 handler(item)
298 return True
295 return True
299
296
300 def _show_interpreter_prompt(self, number=None):
297 def _show_interpreter_prompt(self, number=None):
301 """ Reimplemented for IPython-style prompts.
298 """ Reimplemented for IPython-style prompts.
302 """
299 """
303 # If a number was not specified, make a prompt number request.
300 # If a number was not specified, make a prompt number request.
304 if number is None:
301 if number is None:
305 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
302 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
306 info = self._ExecutionRequest(msg_id, 'prompt')
303 info = self._ExecutionRequest(msg_id, 'prompt')
307 self._request_info['execute'] = info
304 self._request_info['execute'] = info
308 return
305 return
309
306
310 # Show a new prompt and save information about it so that it can be
307 # Show a new prompt and save information about it so that it can be
311 # updated later if the prompt number turns out to be wrong.
308 # updated later if the prompt number turns out to be wrong.
312 self._prompt_sep = self.input_sep
309 self._prompt_sep = self.input_sep
313 self._show_prompt(self._make_in_prompt(number), html=True)
310 self._show_prompt(self._make_in_prompt(number), html=True)
314 block = self._control.document().lastBlock()
311 block = self._control.document().lastBlock()
315 length = len(self._prompt)
312 length = len(self._prompt)
316 self._previous_prompt_obj = self._PromptBlock(block, length, number)
313 self._previous_prompt_obj = self._PromptBlock(block, length, number)
317
314
318 # Update continuation prompt to reflect (possibly) new prompt length.
315 # Update continuation prompt to reflect (possibly) new prompt length.
319 self._set_continuation_prompt(
316 self._set_continuation_prompt(
320 self._make_continuation_prompt(self._prompt), html=True)
317 self._make_continuation_prompt(self._prompt), html=True)
321
318
322 # Load code from the %loadpy magic, if necessary.
319 # Load code from the %loadpy magic, if necessary.
323 if self._code_to_load is not None:
320 if self._code_to_load is not None:
324 self.input_buffer = dedent(self._code_to_load.rstrip())
321 self.input_buffer = dedent(self._code_to_load.rstrip())
325 self._code_to_load = None
322 self._code_to_load = None
326
323
327 def _show_interpreter_prompt_for_reply(self, msg):
324 def _show_interpreter_prompt_for_reply(self, msg):
328 """ Reimplemented for IPython-style prompts.
325 """ Reimplemented for IPython-style prompts.
329 """
326 """
330 # Update the old prompt number if necessary.
327 # Update the old prompt number if necessary.
331 content = msg['content']
328 content = msg['content']
332 previous_prompt_number = content['execution_count']
329 previous_prompt_number = content['execution_count']
333 if self._previous_prompt_obj and \
330 if self._previous_prompt_obj and \
334 self._previous_prompt_obj.number != previous_prompt_number:
331 self._previous_prompt_obj.number != previous_prompt_number:
335 block = self._previous_prompt_obj.block
332 block = self._previous_prompt_obj.block
336
333
337 # Make sure the prompt block has not been erased.
334 # Make sure the prompt block has not been erased.
338 if block.isValid() and block.text():
335 if block.isValid() and block.text():
339
336
340 # Remove the old prompt and insert a new prompt.
337 # Remove the old prompt and insert a new prompt.
341 cursor = QtGui.QTextCursor(block)
338 cursor = QtGui.QTextCursor(block)
342 cursor.movePosition(QtGui.QTextCursor.Right,
339 cursor.movePosition(QtGui.QTextCursor.Right,
343 QtGui.QTextCursor.KeepAnchor,
340 QtGui.QTextCursor.KeepAnchor,
344 self._previous_prompt_obj.length)
341 self._previous_prompt_obj.length)
345 prompt = self._make_in_prompt(previous_prompt_number)
342 prompt = self._make_in_prompt(previous_prompt_number)
346 self._prompt = self._insert_html_fetching_plain_text(
343 self._prompt = self._insert_html_fetching_plain_text(
347 cursor, prompt)
344 cursor, prompt)
348
345
349 # When the HTML is inserted, Qt blows away the syntax
346 # When the HTML is inserted, Qt blows away the syntax
350 # highlighting for the line, so we need to rehighlight it.
347 # highlighting for the line, so we need to rehighlight it.
351 self._highlighter.rehighlightBlock(cursor.block())
348 self._highlighter.rehighlightBlock(cursor.block())
352
349
353 self._previous_prompt_obj = None
350 self._previous_prompt_obj = None
354
351
355 # Show a new prompt with the kernel's estimated prompt number.
352 # Show a new prompt with the kernel's estimated prompt number.
356 self._show_interpreter_prompt(previous_prompt_number + 1)
353 self._show_interpreter_prompt(previous_prompt_number + 1)
357
354
358 #---------------------------------------------------------------------------
355 #---------------------------------------------------------------------------
359 # 'IPythonWidget' interface
356 # 'IPythonWidget' interface
360 #---------------------------------------------------------------------------
357 #---------------------------------------------------------------------------
361
358
362 def set_default_style(self, colors='lightbg'):
359 def set_default_style(self, colors='lightbg'):
363 """ Sets the widget style to the class defaults.
360 """ Sets the widget style to the class defaults.
364
361
365 Parameters:
362 Parameters:
366 -----------
363 -----------
367 colors : str, optional (default lightbg)
364 colors : str, optional (default lightbg)
368 Whether to use the default IPython light background or dark
365 Whether to use the default IPython light background or dark
369 background or B&W style.
366 background or B&W style.
370 """
367 """
371 colors = colors.lower()
368 colors = colors.lower()
372 if colors=='lightbg':
369 if colors=='lightbg':
373 self.style_sheet = default_light_style_sheet
370 self.style_sheet = default_light_style_sheet
374 self.syntax_style = default_light_syntax_style
371 self.syntax_style = default_light_syntax_style
375 elif colors=='linux':
372 elif colors=='linux':
376 self.style_sheet = default_dark_style_sheet
373 self.style_sheet = default_dark_style_sheet
377 self.syntax_style = default_dark_syntax_style
374 self.syntax_style = default_dark_syntax_style
378 elif colors=='nocolor':
375 elif colors=='nocolor':
379 self.style_sheet = default_bw_style_sheet
376 self.style_sheet = default_bw_style_sheet
380 self.syntax_style = default_bw_syntax_style
377 self.syntax_style = default_bw_syntax_style
381 else:
378 else:
382 raise KeyError("No such color scheme: %s"%colors)
379 raise KeyError("No such color scheme: %s"%colors)
383
380
384 #---------------------------------------------------------------------------
381 #---------------------------------------------------------------------------
385 # 'IPythonWidget' protected interface
382 # 'IPythonWidget' protected interface
386 #---------------------------------------------------------------------------
383 #---------------------------------------------------------------------------
387
384
388 def _edit(self, filename, line=None):
385 def _edit(self, filename, line=None):
389 """ Opens a Python script for editing.
386 """ Opens a Python script for editing.
390
387
391 Parameters:
388 Parameters:
392 -----------
389 -----------
393 filename : str
390 filename : str
394 A path to a local system file.
391 A path to a local system file.
395
392
396 line : int, optional
393 line : int, optional
397 A line of interest in the file.
394 A line of interest in the file.
398 """
395 """
399 if self.custom_edit:
396 if self.custom_edit:
400 self.custom_edit_requested.emit(filename, line)
397 self.custom_edit_requested.emit(filename, line)
401 elif self.editor == 'default':
398 elif self.editor == 'default':
402 self._append_plain_text('No default editor available.\n')
399 self._append_plain_text('No default editor available.\n')
403 else:
400 else:
404 try:
401 try:
405 filename = '"%s"' % filename
402 filename = '"%s"' % filename
406 if line and self.editor_line:
403 if line and self.editor_line:
407 command = self.editor_line.format(filename=filename,
404 command = self.editor_line.format(filename=filename,
408 line=line)
405 line=line)
409 else:
406 else:
410 try:
407 try:
411 command = self.editor.format()
408 command = self.editor.format()
412 except KeyError:
409 except KeyError:
413 command = self.editor.format(filename=filename)
410 command = self.editor.format(filename=filename)
414 else:
411 else:
415 command += ' ' + filename
412 command += ' ' + filename
416 except KeyError:
413 except KeyError:
417 self._append_plain_text('Invalid editor command.\n')
414 self._append_plain_text('Invalid editor command.\n')
418 else:
415 else:
419 try:
416 try:
420 Popen(command, shell=True)
417 Popen(command, shell=True)
421 except OSError:
418 except OSError:
422 msg = 'Opening editor with command "%s" failed.\n'
419 msg = 'Opening editor with command "%s" failed.\n'
423 self._append_plain_text(msg % command)
420 self._append_plain_text(msg % command)
424
421
425 def _make_in_prompt(self, number):
422 def _make_in_prompt(self, number):
426 """ Given a prompt number, returns an HTML In prompt.
423 """ Given a prompt number, returns an HTML In prompt.
427 """
424 """
428 body = self.in_prompt % number
425 body = self.in_prompt % number
429 return '<span class="in-prompt">%s</span>' % body
426 return '<span class="in-prompt">%s</span>' % body
430
427
431 def _make_continuation_prompt(self, prompt):
428 def _make_continuation_prompt(self, prompt):
432 """ Given a plain text version of an In prompt, returns an HTML
429 """ Given a plain text version of an In prompt, returns an HTML
433 continuation prompt.
430 continuation prompt.
434 """
431 """
435 end_chars = '...: '
432 end_chars = '...: '
436 space_count = len(prompt.lstrip('\n')) - len(end_chars)
433 space_count = len(prompt.lstrip('\n')) - len(end_chars)
437 body = '&nbsp;' * space_count + end_chars
434 body = '&nbsp;' * space_count + end_chars
438 return '<span class="in-prompt">%s</span>' % body
435 return '<span class="in-prompt">%s</span>' % body
439
436
440 def _make_out_prompt(self, number):
437 def _make_out_prompt(self, number):
441 """ Given a prompt number, returns an HTML Out prompt.
438 """ Given a prompt number, returns an HTML Out prompt.
442 """
439 """
443 body = self.out_prompt % number
440 body = self.out_prompt % number
444 return '<span class="out-prompt">%s</span>' % body
441 return '<span class="out-prompt">%s</span>' % body
445
442
446 #------ Payload handlers --------------------------------------------------
443 #------ Payload handlers --------------------------------------------------
447
444
448 # Payload handlers with a generic interface: each takes the opaque payload
445 # Payload handlers with a generic interface: each takes the opaque payload
449 # dict, unpacks it and calls the underlying functions with the necessary
446 # dict, unpacks it and calls the underlying functions with the necessary
450 # arguments.
447 # arguments.
451
448
452 def _handle_payload_edit(self, item):
449 def _handle_payload_edit(self, item):
453 self._edit(item['filename'], item['line_number'])
450 self._edit(item['filename'], item['line_number'])
454
451
455 def _handle_payload_exit(self, item):
452 def _handle_payload_exit(self, item):
456 self._keep_kernel_on_exit = item['keepkernel']
453 self._keep_kernel_on_exit = item['keepkernel']
457 self.exit_requested.emit()
454 self.exit_requested.emit()
458
455
459 def _handle_payload_loadpy(self, item):
456 def _handle_payload_loadpy(self, item):
460 # Simple save the text of the .py file for later. The text is written
457 # Simple save the text of the .py file for later. The text is written
461 # to the buffer when _prompt_started_hook is called.
458 # to the buffer when _prompt_started_hook is called.
462 self._code_to_load = item['text']
459 self._code_to_load = item['text']
463
460
464 def _handle_payload_page(self, item):
461 def _handle_payload_page(self, item):
465 # Since the plain text widget supports only a very small subset of HTML
462 # Since the plain text widget supports only a very small subset of HTML
466 # and we have no control over the HTML source, we only page HTML
463 # and we have no control over the HTML source, we only page HTML
467 # payloads in the rich text widget.
464 # payloads in the rich text widget.
468 if item['html'] and self.kind == 'rich':
465 if item['html'] and self.kind == 'rich':
469 self._page(item['html'], html=True)
466 self._page(item['html'], html=True)
470 else:
467 else:
471 self._page(item['text'], html=False)
468 self._page(item['text'], html=False)
472
469
473 #------ Trait change handlers --------------------------------------------
470 #------ Trait change handlers --------------------------------------------
474
471
475 def _style_sheet_changed(self):
472 def _style_sheet_changed(self):
476 """ Set the style sheets of the underlying widgets.
473 """ Set the style sheets of the underlying widgets.
477 """
474 """
478 self.setStyleSheet(self.style_sheet)
475 self.setStyleSheet(self.style_sheet)
479 self._control.document().setDefaultStyleSheet(self.style_sheet)
476 self._control.document().setDefaultStyleSheet(self.style_sheet)
480 if self._page_control:
477 if self._page_control:
481 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
478 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
482
479
483 bg_color = self._control.palette().window().color()
480 bg_color = self._control.palette().window().color()
484 self._ansi_processor.set_background_color(bg_color)
481 self._ansi_processor.set_background_color(bg_color)
485
482
486 def _syntax_style_changed(self):
483 def _syntax_style_changed(self):
487 """ Set the style for the syntax highlighter.
484 """ Set the style for the syntax highlighter.
488 """
485 """
489 if self.syntax_style:
486 if self.syntax_style:
490 self._highlighter.set_style(self.syntax_style)
487 self._highlighter.set_style(self.syntax_style)
491 else:
488 else:
492 self._highlighter.set_style_sheet(self.style_sheet)
489 self._highlighter.set_style_sheet(self.style_sheet)
493
490
@@ -1,623 +1,558 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
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 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.lib.inputhook import enable_gui
27 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.pylabtools import pylab_activate
28 from IPython.lib.pylabtools import pylab_activate
29 from IPython.testing import decorators as testdec
29 from IPython.testing import decorators as testdec
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
34 from IPython.utils.traitlets import Int, Str, CBool
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 def get_default_editor():
40 def get_default_editor():
41 try:
41 try:
42 ed = os.environ['EDITOR']
42 ed = os.environ['EDITOR']
43 except KeyError:
43 except KeyError:
44 if os.name == 'posix':
44 if os.name == 'posix':
45 ed = 'vi' # the only one guaranteed to be there!
45 ed = 'vi' # the only one guaranteed to be there!
46 else:
46 else:
47 ed = 'notepad' # same in Windows!
47 ed = 'notepad' # same in Windows!
48 return ed
48 return ed
49
49
50
50
51 # store the builtin raw_input globally, and use this always, in case user code
51 # store the builtin raw_input globally, and use this always, in case user code
52 # overwrites it (like wx.py.PyShell does)
52 # overwrites it (like wx.py.PyShell does)
53 raw_input_original = raw_input
53 raw_input_original = raw_input
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Main class
56 # Main class
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 class TerminalInteractiveShell(InteractiveShell):
59 class TerminalInteractiveShell(InteractiveShell):
60
60
61 autoedit_syntax = CBool(False, config=True)
61 autoedit_syntax = CBool(False, config=True)
62 banner = Str('')
62 banner = Str('')
63 banner1 = Str(default_banner, config=True)
63 banner1 = Str(default_banner, config=True)
64 banner2 = Str('', config=True)
64 banner2 = Str('', config=True)
65 confirm_exit = CBool(True, config=True)
65 confirm_exit = CBool(True, config=True)
66 # This display_banner only controls whether or not self.show_banner()
66 # This display_banner only controls whether or not self.show_banner()
67 # is called when mainloop/interact are called. The default is False
67 # is called when mainloop/interact are called. The default is False
68 # because for the terminal based application, the banner behavior
68 # because for the terminal based application, the banner behavior
69 # is controlled by Global.display_banner, which IPythonApp looks at
69 # is controlled by Global.display_banner, which IPythonApp looks at
70 # to determine if *it* should call show_banner() by hand or not.
70 # to determine if *it* should call show_banner() by hand or not.
71 display_banner = CBool(False) # This isn't configurable!
71 display_banner = CBool(False) # This isn't configurable!
72 embedded = CBool(False)
72 embedded = CBool(False)
73 embedded_active = CBool(False)
73 embedded_active = CBool(False)
74 editor = Str(get_default_editor(), config=True)
74 editor = Str(get_default_editor(), config=True)
75 pager = Str('less', config=True)
75 pager = Str('less', config=True)
76
76
77 screen_length = Int(0, config=True)
77 screen_length = Int(0, config=True)
78 term_title = CBool(False, config=True)
78 term_title = CBool(False, config=True)
79
79
80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
81 user_global_ns=None, custom_exceptions=((),None),
81 user_global_ns=None, custom_exceptions=((),None),
82 usage=None, banner1=None, banner2=None,
82 usage=None, banner1=None, banner2=None,
83 display_banner=None):
83 display_banner=None):
84
84
85 super(TerminalInteractiveShell, self).__init__(
85 super(TerminalInteractiveShell, self).__init__(
86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
87 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
87 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
88 )
88 )
89 self.init_term_title()
89 self.init_term_title()
90 self.init_usage(usage)
90 self.init_usage(usage)
91 self.init_banner(banner1, banner2, display_banner)
91 self.init_banner(banner1, banner2, display_banner)
92
92
93 #-------------------------------------------------------------------------
93 #-------------------------------------------------------------------------
94 # Things related to the terminal
94 # Things related to the terminal
95 #-------------------------------------------------------------------------
95 #-------------------------------------------------------------------------
96
96
97 @property
97 @property
98 def usable_screen_length(self):
98 def usable_screen_length(self):
99 if self.screen_length == 0:
99 if self.screen_length == 0:
100 return 0
100 return 0
101 else:
101 else:
102 num_lines_bot = self.separate_in.count('\n')+1
102 num_lines_bot = self.separate_in.count('\n')+1
103 return self.screen_length - num_lines_bot
103 return self.screen_length - num_lines_bot
104
104
105 def init_term_title(self):
105 def init_term_title(self):
106 # Enable or disable the terminal title.
106 # Enable or disable the terminal title.
107 if self.term_title:
107 if self.term_title:
108 toggle_set_term_title(True)
108 toggle_set_term_title(True)
109 set_term_title('IPython: ' + abbrev_cwd())
109 set_term_title('IPython: ' + abbrev_cwd())
110 else:
110 else:
111 toggle_set_term_title(False)
111 toggle_set_term_title(False)
112
112
113 #-------------------------------------------------------------------------
113 #-------------------------------------------------------------------------
114 # Things related to aliases
114 # Things related to aliases
115 #-------------------------------------------------------------------------
115 #-------------------------------------------------------------------------
116
116
117 def init_alias(self):
117 def init_alias(self):
118 # The parent class defines aliases that can be safely used with any
118 # The parent class defines aliases that can be safely used with any
119 # frontend.
119 # frontend.
120 super(TerminalInteractiveShell, self).init_alias()
120 super(TerminalInteractiveShell, self).init_alias()
121
121
122 # Now define aliases that only make sense on the terminal, because they
122 # Now define aliases that only make sense on the terminal, because they
123 # need direct access to the console in a way that we can't emulate in
123 # need direct access to the console in a way that we can't emulate in
124 # GUI or web frontend
124 # GUI or web frontend
125 if os.name == 'posix':
125 if os.name == 'posix':
126 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
126 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
127 ('man', 'man')]
127 ('man', 'man')]
128 elif os.name == 'nt':
128 elif os.name == 'nt':
129 aliases = [('cls', 'cls')]
129 aliases = [('cls', 'cls')]
130
130
131
131
132 for name, cmd in aliases:
132 for name, cmd in aliases:
133 self.alias_manager.define_alias(name, cmd)
133 self.alias_manager.define_alias(name, cmd)
134
134
135 #-------------------------------------------------------------------------
135 #-------------------------------------------------------------------------
136 # Things related to the banner and usage
136 # Things related to the banner and usage
137 #-------------------------------------------------------------------------
137 #-------------------------------------------------------------------------
138
138
139 def _banner1_changed(self):
139 def _banner1_changed(self):
140 self.compute_banner()
140 self.compute_banner()
141
141
142 def _banner2_changed(self):
142 def _banner2_changed(self):
143 self.compute_banner()
143 self.compute_banner()
144
144
145 def _term_title_changed(self, name, new_value):
145 def _term_title_changed(self, name, new_value):
146 self.init_term_title()
146 self.init_term_title()
147
147
148 def init_banner(self, banner1, banner2, display_banner):
148 def init_banner(self, banner1, banner2, display_banner):
149 if banner1 is not None:
149 if banner1 is not None:
150 self.banner1 = banner1
150 self.banner1 = banner1
151 if banner2 is not None:
151 if banner2 is not None:
152 self.banner2 = banner2
152 self.banner2 = banner2
153 if display_banner is not None:
153 if display_banner is not None:
154 self.display_banner = display_banner
154 self.display_banner = display_banner
155 self.compute_banner()
155 self.compute_banner()
156
156
157 def show_banner(self, banner=None):
157 def show_banner(self, banner=None):
158 if banner is None:
158 if banner is None:
159 banner = self.banner
159 banner = self.banner
160 self.write(banner)
160 self.write(banner)
161
161
162 def compute_banner(self):
162 def compute_banner(self):
163 self.banner = self.banner1
163 self.banner = self.banner1
164 if self.profile:
164 if self.profile:
165 self.banner += '\nIPython profile: %s\n' % self.profile
165 self.banner += '\nIPython profile: %s\n' % self.profile
166 if self.banner2:
166 if self.banner2:
167 self.banner += '\n' + self.banner2
167 self.banner += '\n' + self.banner2
168
168
169 def init_usage(self, usage=None):
169 def init_usage(self, usage=None):
170 if usage is None:
170 if usage is None:
171 self.usage = interactive_usage
171 self.usage = interactive_usage
172 else:
172 else:
173 self.usage = usage
173 self.usage = usage
174
174
175 #-------------------------------------------------------------------------
175 #-------------------------------------------------------------------------
176 # Mainloop and code execution logic
176 # Mainloop and code execution logic
177 #-------------------------------------------------------------------------
177 #-------------------------------------------------------------------------
178
178
179 def mainloop(self, display_banner=None):
179 def mainloop(self, display_banner=None):
180 """Start the mainloop.
180 """Start the mainloop.
181
181
182 If an optional banner argument is given, it will override the
182 If an optional banner argument is given, it will override the
183 internally created default banner.
183 internally created default banner.
184 """
184 """
185
185
186 with nested(self.builtin_trap, self.display_trap):
186 with nested(self.builtin_trap, self.display_trap):
187
187
188 # if you run stuff with -c <cmd>, raw hist is not updated
189 # ensure that it's in sync
190 self.history_manager.sync_inputs()
191
192 while 1:
188 while 1:
193 try:
189 try:
194 self.interact(display_banner=display_banner)
190 self.interact(display_banner=display_banner)
195 #self.interact_with_readline()
191 #self.interact_with_readline()
196 # XXX for testing of a readline-decoupled repl loop, call
192 # XXX for testing of a readline-decoupled repl loop, call
197 # interact_with_readline above
193 # interact_with_readline above
198 break
194 break
199 except KeyboardInterrupt:
195 except KeyboardInterrupt:
200 # this should not be necessary, but KeyboardInterrupt
196 # this should not be necessary, but KeyboardInterrupt
201 # handling seems rather unpredictable...
197 # handling seems rather unpredictable...
202 self.write("\nKeyboardInterrupt in interact()\n")
198 self.write("\nKeyboardInterrupt in interact()\n")
203
199
204 def interact(self, display_banner=None):
200 def interact(self, display_banner=None):
205 """Closely emulate the interactive Python console."""
201 """Closely emulate the interactive Python console."""
206
202
207 # batch run -> do not interact
203 # batch run -> do not interact
208 if self.exit_now:
204 if self.exit_now:
209 return
205 return
210
206
211 if display_banner is None:
207 if display_banner is None:
212 display_banner = self.display_banner
208 display_banner = self.display_banner
213 if display_banner:
209 if display_banner:
214 self.show_banner()
210 self.show_banner()
215
211
216 more = False
212 more = False
217
213
218 # Mark activity in the builtins
214 # Mark activity in the builtins
219 __builtin__.__dict__['__IPYTHON__active'] += 1
215 __builtin__.__dict__['__IPYTHON__active'] += 1
220
216
221 if self.has_readline:
217 if self.has_readline:
222 self.readline_startup_hook(self.pre_readline)
218 self.readline_startup_hook(self.pre_readline)
223 # exit_now is set by a call to %Exit or %Quit, through the
219 # exit_now is set by a call to %Exit or %Quit, through the
224 # ask_exit callback.
220 # ask_exit callback.
225
221
226 while not self.exit_now:
222 while not self.exit_now:
227 self.hooks.pre_prompt_hook()
223 self.hooks.pre_prompt_hook()
228 if more:
224 if more:
229 try:
225 try:
230 prompt = self.hooks.generate_prompt(True)
226 prompt = self.hooks.generate_prompt(True)
231 except:
227 except:
232 self.showtraceback()
228 self.showtraceback()
233 if self.autoindent:
229 if self.autoindent:
234 self.rl_do_indent = True
230 self.rl_do_indent = True
235
231
236 else:
232 else:
237 try:
233 try:
238 prompt = self.hooks.generate_prompt(False)
234 prompt = self.hooks.generate_prompt(False)
239 except:
235 except:
240 self.showtraceback()
236 self.showtraceback()
241 try:
237 try:
242 line = self.raw_input(prompt)
238 line = self.raw_input(prompt)
243 if self.exit_now:
239 if self.exit_now:
244 # quick exit on sys.std[in|out] close
240 # quick exit on sys.std[in|out] close
245 break
241 break
246 if self.autoindent:
242 if self.autoindent:
247 self.rl_do_indent = False
243 self.rl_do_indent = False
248
244
249 except KeyboardInterrupt:
245 except KeyboardInterrupt:
250 #double-guard against keyboardinterrupts during kbdint handling
246 #double-guard against keyboardinterrupts during kbdint handling
251 try:
247 try:
252 self.write('\nKeyboardInterrupt\n')
248 self.write('\nKeyboardInterrupt\n')
253 self.resetbuffer()
249 self.resetbuffer()
254 more = False
250 more = False
255 except KeyboardInterrupt:
251 except KeyboardInterrupt:
256 pass
252 pass
257 except EOFError:
253 except EOFError:
258 if self.autoindent:
254 if self.autoindent:
259 self.rl_do_indent = False
255 self.rl_do_indent = False
260 if self.has_readline:
256 if self.has_readline:
261 self.readline_startup_hook(None)
257 self.readline_startup_hook(None)
262 self.write('\n')
258 self.write('\n')
263 self.exit()
259 self.exit()
264 except bdb.BdbQuit:
260 except bdb.BdbQuit:
265 warn('The Python debugger has exited with a BdbQuit exception.\n'
261 warn('The Python debugger has exited with a BdbQuit exception.\n'
266 'Because of how pdb handles the stack, it is impossible\n'
262 'Because of how pdb handles the stack, it is impossible\n'
267 'for IPython to properly format this particular exception.\n'
263 'for IPython to properly format this particular exception.\n'
268 'IPython will resume normal operation.')
264 'IPython will resume normal operation.')
269 except:
265 except:
270 # exceptions here are VERY RARE, but they can be triggered
266 # exceptions here are VERY RARE, but they can be triggered
271 # asynchronously by signal handlers, for example.
267 # asynchronously by signal handlers, for example.
272 self.showtraceback()
268 self.showtraceback()
273 else:
269 else:
274 self.input_splitter.push(line)
270 self.input_splitter.push(line)
275 more = self.input_splitter.push_accepts_more()
271 more = self.input_splitter.push_accepts_more()
276 if (self.SyntaxTB.last_syntax_error and
272 if (self.SyntaxTB.last_syntax_error and
277 self.autoedit_syntax):
273 self.autoedit_syntax):
278 self.edit_syntax_error()
274 self.edit_syntax_error()
279 if not more:
275 if not more:
280 source_raw = self.input_splitter.source_raw_reset()[1]
276 source_raw = self.input_splitter.source_raw_reset()[1]
281 self.run_cell(source_raw)
277 self.run_cell(source_raw)
282
278
283 # We are off again...
279 # We are off again...
284 __builtin__.__dict__['__IPYTHON__active'] -= 1
280 __builtin__.__dict__['__IPYTHON__active'] -= 1
285
281
286 # Turn off the exit flag, so the mainloop can be restarted if desired
282 # Turn off the exit flag, so the mainloop can be restarted if desired
287 self.exit_now = False
283 self.exit_now = False
288
284
289 def raw_input(self, prompt='', continue_prompt=False):
290 """Write a prompt and read a line.
291
292 The returned line does not include the trailing newline.
293 When the user enters the EOF key sequence, EOFError is raised.
294
295 Optional inputs:
296
297 - prompt(''): a string to be printed to prompt the user.
298
299 - continue_prompt(False): whether this line is the first one or a
300 continuation in a sequence of inputs.
301 """
302 # Code run by the user may have modified the readline completer state.
303 # We must ensure that our completer is back in place.
304
305 if self.has_readline:
306 self.set_readline_completer()
307
308 try:
309 line = raw_input_original(prompt).decode(self.stdin_encoding)
310 except ValueError:
311 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
312 " or sys.stdout.close()!\nExiting IPython!")
313 self.ask_exit()
314 return ""
315
316 # Try to be reasonably smart about not re-indenting pasted input more
317 # than necessary. We do this by trimming out the auto-indent initial
318 # spaces, if the user's actual input started itself with whitespace.
319 if self.autoindent:
320 if num_ini_spaces(line) > self.indent_current_nsp:
321 line = line[self.indent_current_nsp:]
322 self.indent_current_nsp = 0
323
324 # store the unfiltered input before the user has any chance to modify
325 # it.
326 if line.strip():
327 if continue_prompt:
328 if self.has_readline and self.readline_use:
329 histlen = self.readline.get_current_history_length()
330 if histlen > 1:
331 newhist = self.history_manager.input_hist_raw[-1].rstrip()
332 self.readline.remove_history_item(histlen-1)
333 self.readline.replace_history_item(histlen-2,
334 newhist.encode(self.stdin_encoding))
335 else:
336 self.history_manager.input_hist_raw.append('%s\n' % line)
337 elif not continue_prompt:
338 self.history_manager.input_hist_raw.append('\n')
339 try:
340 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
341 except:
342 # blanket except, in case a user-defined prefilter crashes, so it
343 # can't take all of ipython with it.
344 self.showtraceback()
345 return ''
346 else:
347 return lineout
348
349
350 def raw_input(self, prompt=''):
285 def raw_input(self, prompt=''):
351 """Write a prompt and read a line.
286 """Write a prompt and read a line.
352
287
353 The returned line does not include the trailing newline.
288 The returned line does not include the trailing newline.
354 When the user enters the EOF key sequence, EOFError is raised.
289 When the user enters the EOF key sequence, EOFError is raised.
355
290
356 Optional inputs:
291 Optional inputs:
357
292
358 - prompt(''): a string to be printed to prompt the user.
293 - prompt(''): a string to be printed to prompt the user.
359
294
360 - continue_prompt(False): whether this line is the first one or a
295 - continue_prompt(False): whether this line is the first one or a
361 continuation in a sequence of inputs.
296 continuation in a sequence of inputs.
362 """
297 """
363 # Code run by the user may have modified the readline completer state.
298 # Code run by the user may have modified the readline completer state.
364 # We must ensure that our completer is back in place.
299 # We must ensure that our completer is back in place.
365
300
366 if self.has_readline:
301 if self.has_readline:
367 self.set_readline_completer()
302 self.set_readline_completer()
368
303
369 try:
304 try:
370 line = raw_input_original(prompt).decode(self.stdin_encoding)
305 line = raw_input_original(prompt).decode(self.stdin_encoding)
371 except ValueError:
306 except ValueError:
372 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
307 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
373 " or sys.stdout.close()!\nExiting IPython!")
308 " or sys.stdout.close()!\nExiting IPython!")
374 self.ask_exit()
309 self.ask_exit()
375 return ""
310 return ""
376
311
377 # Try to be reasonably smart about not re-indenting pasted input more
312 # Try to be reasonably smart about not re-indenting pasted input more
378 # than necessary. We do this by trimming out the auto-indent initial
313 # than necessary. We do this by trimming out the auto-indent initial
379 # spaces, if the user's actual input started itself with whitespace.
314 # spaces, if the user's actual input started itself with whitespace.
380 if self.autoindent:
315 if self.autoindent:
381 if num_ini_spaces(line) > self.indent_current_nsp:
316 if num_ini_spaces(line) > self.indent_current_nsp:
382 line = line[self.indent_current_nsp:]
317 line = line[self.indent_current_nsp:]
383 self.indent_current_nsp = 0
318 self.indent_current_nsp = 0
384
319
385 return line
320 return line
386
321
387 #-------------------------------------------------------------------------
322 #-------------------------------------------------------------------------
388 # Methods to support auto-editing of SyntaxErrors.
323 # Methods to support auto-editing of SyntaxErrors.
389 #-------------------------------------------------------------------------
324 #-------------------------------------------------------------------------
390
325
391 def edit_syntax_error(self):
326 def edit_syntax_error(self):
392 """The bottom half of the syntax error handler called in the main loop.
327 """The bottom half of the syntax error handler called in the main loop.
393
328
394 Loop until syntax error is fixed or user cancels.
329 Loop until syntax error is fixed or user cancels.
395 """
330 """
396
331
397 while self.SyntaxTB.last_syntax_error:
332 while self.SyntaxTB.last_syntax_error:
398 # copy and clear last_syntax_error
333 # copy and clear last_syntax_error
399 err = self.SyntaxTB.clear_err_state()
334 err = self.SyntaxTB.clear_err_state()
400 if not self._should_recompile(err):
335 if not self._should_recompile(err):
401 return
336 return
402 try:
337 try:
403 # may set last_syntax_error again if a SyntaxError is raised
338 # may set last_syntax_error again if a SyntaxError is raised
404 self.safe_execfile(err.filename,self.user_ns)
339 self.safe_execfile(err.filename,self.user_ns)
405 except:
340 except:
406 self.showtraceback()
341 self.showtraceback()
407 else:
342 else:
408 try:
343 try:
409 f = file(err.filename)
344 f = file(err.filename)
410 try:
345 try:
411 # This should be inside a display_trap block and I
346 # This should be inside a display_trap block and I
412 # think it is.
347 # think it is.
413 sys.displayhook(f.read())
348 sys.displayhook(f.read())
414 finally:
349 finally:
415 f.close()
350 f.close()
416 except:
351 except:
417 self.showtraceback()
352 self.showtraceback()
418
353
419 def _should_recompile(self,e):
354 def _should_recompile(self,e):
420 """Utility routine for edit_syntax_error"""
355 """Utility routine for edit_syntax_error"""
421
356
422 if e.filename in ('<ipython console>','<input>','<string>',
357 if e.filename in ('<ipython console>','<input>','<string>',
423 '<console>','<BackgroundJob compilation>',
358 '<console>','<BackgroundJob compilation>',
424 None):
359 None):
425
360
426 return False
361 return False
427 try:
362 try:
428 if (self.autoedit_syntax and
363 if (self.autoedit_syntax and
429 not self.ask_yes_no('Return to editor to correct syntax error? '
364 not self.ask_yes_no('Return to editor to correct syntax error? '
430 '[Y/n] ','y')):
365 '[Y/n] ','y')):
431 return False
366 return False
432 except EOFError:
367 except EOFError:
433 return False
368 return False
434
369
435 def int0(x):
370 def int0(x):
436 try:
371 try:
437 return int(x)
372 return int(x)
438 except TypeError:
373 except TypeError:
439 return 0
374 return 0
440 # always pass integer line and offset values to editor hook
375 # always pass integer line and offset values to editor hook
441 try:
376 try:
442 self.hooks.fix_error_editor(e.filename,
377 self.hooks.fix_error_editor(e.filename,
443 int0(e.lineno),int0(e.offset),e.msg)
378 int0(e.lineno),int0(e.offset),e.msg)
444 except TryNext:
379 except TryNext:
445 warn('Could not open editor')
380 warn('Could not open editor')
446 return False
381 return False
447 return True
382 return True
448
383
449 #-------------------------------------------------------------------------
384 #-------------------------------------------------------------------------
450 # Things related to GUI support and pylab
385 # Things related to GUI support and pylab
451 #-------------------------------------------------------------------------
386 #-------------------------------------------------------------------------
452
387
453 def enable_pylab(self, gui=None):
388 def enable_pylab(self, gui=None):
454 """Activate pylab support at runtime.
389 """Activate pylab support at runtime.
455
390
456 This turns on support for matplotlib, preloads into the interactive
391 This turns on support for matplotlib, preloads into the interactive
457 namespace all of numpy and pylab, and configures IPython to correcdtly
392 namespace all of numpy and pylab, and configures IPython to correcdtly
458 interact with the GUI event loop. The GUI backend to be used can be
393 interact with the GUI event loop. The GUI backend to be used can be
459 optionally selected with the optional :param:`gui` argument.
394 optionally selected with the optional :param:`gui` argument.
460
395
461 Parameters
396 Parameters
462 ----------
397 ----------
463 gui : optional, string
398 gui : optional, string
464
399
465 If given, dictates the choice of matplotlib GUI backend to use
400 If given, dictates the choice of matplotlib GUI backend to use
466 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
401 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
467 'gtk'), otherwise we use the default chosen by matplotlib (as
402 'gtk'), otherwise we use the default chosen by matplotlib (as
468 dictated by the matplotlib build-time options plus the user's
403 dictated by the matplotlib build-time options plus the user's
469 matplotlibrc configuration file).
404 matplotlibrc configuration file).
470 """
405 """
471 # We want to prevent the loading of pylab to pollute the user's
406 # We want to prevent the loading of pylab to pollute the user's
472 # namespace as shown by the %who* magics, so we execute the activation
407 # namespace as shown by the %who* magics, so we execute the activation
473 # code in an empty namespace, and we update *both* user_ns and
408 # code in an empty namespace, and we update *both* user_ns and
474 # user_ns_hidden with this information.
409 # user_ns_hidden with this information.
475 ns = {}
410 ns = {}
476 gui = pylab_activate(ns, gui)
411 gui = pylab_activate(ns, gui)
477 self.user_ns.update(ns)
412 self.user_ns.update(ns)
478 self.user_ns_hidden.update(ns)
413 self.user_ns_hidden.update(ns)
479 # Now we must activate the gui pylab wants to use, and fix %run to take
414 # Now we must activate the gui pylab wants to use, and fix %run to take
480 # plot updates into account
415 # plot updates into account
481 enable_gui(gui)
416 enable_gui(gui)
482 self.magic_run = self._pylab_magic_run
417 self.magic_run = self._pylab_magic_run
483
418
484 #-------------------------------------------------------------------------
419 #-------------------------------------------------------------------------
485 # Things related to exiting
420 # Things related to exiting
486 #-------------------------------------------------------------------------
421 #-------------------------------------------------------------------------
487
422
488 def ask_exit(self):
423 def ask_exit(self):
489 """ Ask the shell to exit. Can be overiden and used as a callback. """
424 """ Ask the shell to exit. Can be overiden and used as a callback. """
490 self.exit_now = True
425 self.exit_now = True
491
426
492 def exit(self):
427 def exit(self):
493 """Handle interactive exit.
428 """Handle interactive exit.
494
429
495 This method calls the ask_exit callback."""
430 This method calls the ask_exit callback."""
496 if self.confirm_exit:
431 if self.confirm_exit:
497 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
432 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
498 self.ask_exit()
433 self.ask_exit()
499 else:
434 else:
500 self.ask_exit()
435 self.ask_exit()
501
436
502 #------------------------------------------------------------------------
437 #------------------------------------------------------------------------
503 # Magic overrides
438 # Magic overrides
504 #------------------------------------------------------------------------
439 #------------------------------------------------------------------------
505 # Once the base class stops inheriting from magic, this code needs to be
440 # Once the base class stops inheriting from magic, this code needs to be
506 # moved into a separate machinery as well. For now, at least isolate here
441 # moved into a separate machinery as well. For now, at least isolate here
507 # the magics which this class needs to implement differently from the base
442 # the magics which this class needs to implement differently from the base
508 # class, or that are unique to it.
443 # class, or that are unique to it.
509
444
510 def magic_autoindent(self, parameter_s = ''):
445 def magic_autoindent(self, parameter_s = ''):
511 """Toggle autoindent on/off (if available)."""
446 """Toggle autoindent on/off (if available)."""
512
447
513 self.shell.set_autoindent()
448 self.shell.set_autoindent()
514 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
449 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
515
450
516 @testdec.skip_doctest
451 @testdec.skip_doctest
517 def magic_cpaste(self, parameter_s=''):
452 def magic_cpaste(self, parameter_s=''):
518 """Paste & execute a pre-formatted code block from clipboard.
453 """Paste & execute a pre-formatted code block from clipboard.
519
454
520 You must terminate the block with '--' (two minus-signs) alone on the
455 You must terminate the block with '--' (two minus-signs) alone on the
521 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
456 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
522 is the new sentinel for this operation)
457 is the new sentinel for this operation)
523
458
524 The block is dedented prior to execution to enable execution of method
459 The block is dedented prior to execution to enable execution of method
525 definitions. '>' and '+' characters at the beginning of a line are
460 definitions. '>' and '+' characters at the beginning of a line are
526 ignored, to allow pasting directly from e-mails, diff files and
461 ignored, to allow pasting directly from e-mails, diff files and
527 doctests (the '...' continuation prompt is also stripped). The
462 doctests (the '...' continuation prompt is also stripped). The
528 executed block is also assigned to variable named 'pasted_block' for
463 executed block is also assigned to variable named 'pasted_block' for
529 later editing with '%edit pasted_block'.
464 later editing with '%edit pasted_block'.
530
465
531 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
466 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
532 This assigns the pasted block to variable 'foo' as string, without
467 This assigns the pasted block to variable 'foo' as string, without
533 dedenting or executing it (preceding >>> and + is still stripped)
468 dedenting or executing it (preceding >>> and + is still stripped)
534
469
535 '%cpaste -r' re-executes the block previously entered by cpaste.
470 '%cpaste -r' re-executes the block previously entered by cpaste.
536
471
537 Do not be alarmed by garbled output on Windows (it's a readline bug).
472 Do not be alarmed by garbled output on Windows (it's a readline bug).
538 Just press enter and type -- (and press enter again) and the block
473 Just press enter and type -- (and press enter again) and the block
539 will be what was just pasted.
474 will be what was just pasted.
540
475
541 IPython statements (magics, shell escapes) are not supported (yet).
476 IPython statements (magics, shell escapes) are not supported (yet).
542
477
543 See also
478 See also
544 --------
479 --------
545 paste: automatically pull code from clipboard.
480 paste: automatically pull code from clipboard.
546
481
547 Examples
482 Examples
548 --------
483 --------
549 ::
484 ::
550
485
551 In [8]: %cpaste
486 In [8]: %cpaste
552 Pasting code; enter '--' alone on the line to stop.
487 Pasting code; enter '--' alone on the line to stop.
553 :>>> a = ["world!", "Hello"]
488 :>>> a = ["world!", "Hello"]
554 :>>> print " ".join(sorted(a))
489 :>>> print " ".join(sorted(a))
555 :--
490 :--
556 Hello world!
491 Hello world!
557 """
492 """
558
493
559 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
494 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
560 par = args.strip()
495 par = args.strip()
561 if opts.has_key('r'):
496 if opts.has_key('r'):
562 self._rerun_pasted()
497 self._rerun_pasted()
563 return
498 return
564
499
565 sentinel = opts.get('s','--')
500 sentinel = opts.get('s','--')
566
501
567 block = self._strip_pasted_lines_for_code(
502 block = self._strip_pasted_lines_for_code(
568 self._get_pasted_lines(sentinel))
503 self._get_pasted_lines(sentinel))
569
504
570 self._execute_block(block, par)
505 self._execute_block(block, par)
571
506
572 def magic_paste(self, parameter_s=''):
507 def magic_paste(self, parameter_s=''):
573 """Paste & execute a pre-formatted code block from clipboard.
508 """Paste & execute a pre-formatted code block from clipboard.
574
509
575 The text is pulled directly from the clipboard without user
510 The text is pulled directly from the clipboard without user
576 intervention and printed back on the screen before execution (unless
511 intervention and printed back on the screen before execution (unless
577 the -q flag is given to force quiet mode).
512 the -q flag is given to force quiet mode).
578
513
579 The block is dedented prior to execution to enable execution of method
514 The block is dedented prior to execution to enable execution of method
580 definitions. '>' and '+' characters at the beginning of a line are
515 definitions. '>' and '+' characters at the beginning of a line are
581 ignored, to allow pasting directly from e-mails, diff files and
516 ignored, to allow pasting directly from e-mails, diff files and
582 doctests (the '...' continuation prompt is also stripped). The
517 doctests (the '...' continuation prompt is also stripped). The
583 executed block is also assigned to variable named 'pasted_block' for
518 executed block is also assigned to variable named 'pasted_block' for
584 later editing with '%edit pasted_block'.
519 later editing with '%edit pasted_block'.
585
520
586 You can also pass a variable name as an argument, e.g. '%paste foo'.
521 You can also pass a variable name as an argument, e.g. '%paste foo'.
587 This assigns the pasted block to variable 'foo' as string, without
522 This assigns the pasted block to variable 'foo' as string, without
588 dedenting or executing it (preceding >>> and + is still stripped)
523 dedenting or executing it (preceding >>> and + is still stripped)
589
524
590 Options
525 Options
591 -------
526 -------
592
527
593 -r: re-executes the block previously entered by cpaste.
528 -r: re-executes the block previously entered by cpaste.
594
529
595 -q: quiet mode: do not echo the pasted text back to the terminal.
530 -q: quiet mode: do not echo the pasted text back to the terminal.
596
531
597 IPython statements (magics, shell escapes) are not supported (yet).
532 IPython statements (magics, shell escapes) are not supported (yet).
598
533
599 See also
534 See also
600 --------
535 --------
601 cpaste: manually paste code into terminal until you mark its end.
536 cpaste: manually paste code into terminal until you mark its end.
602 """
537 """
603 opts,args = self.parse_options(parameter_s,'rq',mode='string')
538 opts,args = self.parse_options(parameter_s,'rq',mode='string')
604 par = args.strip()
539 par = args.strip()
605 if opts.has_key('r'):
540 if opts.has_key('r'):
606 self._rerun_pasted()
541 self._rerun_pasted()
607 return
542 return
608
543
609 text = self.shell.hooks.clipboard_get()
544 text = self.shell.hooks.clipboard_get()
610 block = self._strip_pasted_lines_for_code(text.splitlines())
545 block = self._strip_pasted_lines_for_code(text.splitlines())
611
546
612 # By default, echo back to terminal unless quiet mode is requested
547 # By default, echo back to terminal unless quiet mode is requested
613 if not opts.has_key('q'):
548 if not opts.has_key('q'):
614 write = self.shell.write
549 write = self.shell.write
615 write(self.shell.pycolorize(block))
550 write(self.shell.pycolorize(block))
616 if not block.endswith('\n'):
551 if not block.endswith('\n'):
617 write('\n')
552 write('\n')
618 write("## -- End pasted text --\n")
553 write("## -- End pasted text --\n")
619
554
620 self._execute_block(block, par)
555 self._execute_block(block, par)
621
556
622
557
623 InteractiveShellABC.register(TerminalInteractiveShell)
558 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,499 +1,496 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with strings and text.
3 Utilities for working with strings and text.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 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 import __main__
17 import __main__
18
18
19 import os
19 import os
20 import re
20 import re
21 import shutil
21 import shutil
22 import types
23
22
24 from IPython.external.path import path
23 from IPython.external.path import path
25
24
26 from IPython.utils.io import nlprint
25 from IPython.utils.io import nlprint
27 from IPython.utils.data import flatten
26 from IPython.utils.data import flatten
28
27
29 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
30 # Code
29 # Code
31 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
32
31
33 StringTypes = types.StringTypes
34
35
32
36 def unquote_ends(istr):
33 def unquote_ends(istr):
37 """Remove a single pair of quotes from the endpoints of a string."""
34 """Remove a single pair of quotes from the endpoints of a string."""
38
35
39 if not istr:
36 if not istr:
40 return istr
37 return istr
41 if (istr[0]=="'" and istr[-1]=="'") or \
38 if (istr[0]=="'" and istr[-1]=="'") or \
42 (istr[0]=='"' and istr[-1]=='"'):
39 (istr[0]=='"' and istr[-1]=='"'):
43 return istr[1:-1]
40 return istr[1:-1]
44 else:
41 else:
45 return istr
42 return istr
46
43
47
44
48 class LSString(str):
45 class LSString(str):
49 """String derivative with a special access attributes.
46 """String derivative with a special access attributes.
50
47
51 These are normal strings, but with the special attributes:
48 These are normal strings, but with the special attributes:
52
49
53 .l (or .list) : value as list (split on newlines).
50 .l (or .list) : value as list (split on newlines).
54 .n (or .nlstr): original value (the string itself).
51 .n (or .nlstr): original value (the string itself).
55 .s (or .spstr): value as whitespace-separated string.
52 .s (or .spstr): value as whitespace-separated string.
56 .p (or .paths): list of path objects
53 .p (or .paths): list of path objects
57
54
58 Any values which require transformations are computed only once and
55 Any values which require transformations are computed only once and
59 cached.
56 cached.
60
57
61 Such strings are very useful to efficiently interact with the shell, which
58 Such strings are very useful to efficiently interact with the shell, which
62 typically only understands whitespace-separated options for commands."""
59 typically only understands whitespace-separated options for commands."""
63
60
64 def get_list(self):
61 def get_list(self):
65 try:
62 try:
66 return self.__list
63 return self.__list
67 except AttributeError:
64 except AttributeError:
68 self.__list = self.split('\n')
65 self.__list = self.split('\n')
69 return self.__list
66 return self.__list
70
67
71 l = list = property(get_list)
68 l = list = property(get_list)
72
69
73 def get_spstr(self):
70 def get_spstr(self):
74 try:
71 try:
75 return self.__spstr
72 return self.__spstr
76 except AttributeError:
73 except AttributeError:
77 self.__spstr = self.replace('\n',' ')
74 self.__spstr = self.replace('\n',' ')
78 return self.__spstr
75 return self.__spstr
79
76
80 s = spstr = property(get_spstr)
77 s = spstr = property(get_spstr)
81
78
82 def get_nlstr(self):
79 def get_nlstr(self):
83 return self
80 return self
84
81
85 n = nlstr = property(get_nlstr)
82 n = nlstr = property(get_nlstr)
86
83
87 def get_paths(self):
84 def get_paths(self):
88 try:
85 try:
89 return self.__paths
86 return self.__paths
90 except AttributeError:
87 except AttributeError:
91 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
88 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
92 return self.__paths
89 return self.__paths
93
90
94 p = paths = property(get_paths)
91 p = paths = property(get_paths)
95
92
96 # FIXME: We need to reimplement type specific displayhook and then add this
93 # FIXME: We need to reimplement type specific displayhook and then add this
97 # back as a custom printer. This should also be moved outside utils into the
94 # back as a custom printer. This should also be moved outside utils into the
98 # core.
95 # core.
99
96
100 # def print_lsstring(arg):
97 # def print_lsstring(arg):
101 # """ Prettier (non-repr-like) and more informative printer for LSString """
98 # """ Prettier (non-repr-like) and more informative printer for LSString """
102 # print "LSString (.p, .n, .l, .s available). Value:"
99 # print "LSString (.p, .n, .l, .s available). Value:"
103 # print arg
100 # print arg
104 #
101 #
105 #
102 #
106 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
103 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
107
104
108
105
109 class SList(list):
106 class SList(list):
110 """List derivative with a special access attributes.
107 """List derivative with a special access attributes.
111
108
112 These are normal lists, but with the special attributes:
109 These are normal lists, but with the special attributes:
113
110
114 .l (or .list) : value as list (the list itself).
111 .l (or .list) : value as list (the list itself).
115 .n (or .nlstr): value as a string, joined on newlines.
112 .n (or .nlstr): value as a string, joined on newlines.
116 .s (or .spstr): value as a string, joined on spaces.
113 .s (or .spstr): value as a string, joined on spaces.
117 .p (or .paths): list of path objects
114 .p (or .paths): list of path objects
118
115
119 Any values which require transformations are computed only once and
116 Any values which require transformations are computed only once and
120 cached."""
117 cached."""
121
118
122 def get_list(self):
119 def get_list(self):
123 return self
120 return self
124
121
125 l = list = property(get_list)
122 l = list = property(get_list)
126
123
127 def get_spstr(self):
124 def get_spstr(self):
128 try:
125 try:
129 return self.__spstr
126 return self.__spstr
130 except AttributeError:
127 except AttributeError:
131 self.__spstr = ' '.join(self)
128 self.__spstr = ' '.join(self)
132 return self.__spstr
129 return self.__spstr
133
130
134 s = spstr = property(get_spstr)
131 s = spstr = property(get_spstr)
135
132
136 def get_nlstr(self):
133 def get_nlstr(self):
137 try:
134 try:
138 return self.__nlstr
135 return self.__nlstr
139 except AttributeError:
136 except AttributeError:
140 self.__nlstr = '\n'.join(self)
137 self.__nlstr = '\n'.join(self)
141 return self.__nlstr
138 return self.__nlstr
142
139
143 n = nlstr = property(get_nlstr)
140 n = nlstr = property(get_nlstr)
144
141
145 def get_paths(self):
142 def get_paths(self):
146 try:
143 try:
147 return self.__paths
144 return self.__paths
148 except AttributeError:
145 except AttributeError:
149 self.__paths = [path(p) for p in self if os.path.exists(p)]
146 self.__paths = [path(p) for p in self if os.path.exists(p)]
150 return self.__paths
147 return self.__paths
151
148
152 p = paths = property(get_paths)
149 p = paths = property(get_paths)
153
150
154 def grep(self, pattern, prune = False, field = None):
151 def grep(self, pattern, prune = False, field = None):
155 """ Return all strings matching 'pattern' (a regex or callable)
152 """ Return all strings matching 'pattern' (a regex or callable)
156
153
157 This is case-insensitive. If prune is true, return all items
154 This is case-insensitive. If prune is true, return all items
158 NOT matching the pattern.
155 NOT matching the pattern.
159
156
160 If field is specified, the match must occur in the specified
157 If field is specified, the match must occur in the specified
161 whitespace-separated field.
158 whitespace-separated field.
162
159
163 Examples::
160 Examples::
164
161
165 a.grep( lambda x: x.startswith('C') )
162 a.grep( lambda x: x.startswith('C') )
166 a.grep('Cha.*log', prune=1)
163 a.grep('Cha.*log', prune=1)
167 a.grep('chm', field=-1)
164 a.grep('chm', field=-1)
168 """
165 """
169
166
170 def match_target(s):
167 def match_target(s):
171 if field is None:
168 if field is None:
172 return s
169 return s
173 parts = s.split()
170 parts = s.split()
174 try:
171 try:
175 tgt = parts[field]
172 tgt = parts[field]
176 return tgt
173 return tgt
177 except IndexError:
174 except IndexError:
178 return ""
175 return ""
179
176
180 if isinstance(pattern, basestring):
177 if isinstance(pattern, basestring):
181 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
178 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
182 else:
179 else:
183 pred = pattern
180 pred = pattern
184 if not prune:
181 if not prune:
185 return SList([el for el in self if pred(match_target(el))])
182 return SList([el for el in self if pred(match_target(el))])
186 else:
183 else:
187 return SList([el for el in self if not pred(match_target(el))])
184 return SList([el for el in self if not pred(match_target(el))])
188
185
189 def fields(self, *fields):
186 def fields(self, *fields):
190 """ Collect whitespace-separated fields from string list
187 """ Collect whitespace-separated fields from string list
191
188
192 Allows quick awk-like usage of string lists.
189 Allows quick awk-like usage of string lists.
193
190
194 Example data (in var a, created by 'a = !ls -l')::
191 Example data (in var a, created by 'a = !ls -l')::
195 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
192 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
196 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
193 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
197
194
198 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
195 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
199 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
196 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
200 (note the joining by space).
197 (note the joining by space).
201 a.fields(-1) is ['ChangeLog', 'IPython']
198 a.fields(-1) is ['ChangeLog', 'IPython']
202
199
203 IndexErrors are ignored.
200 IndexErrors are ignored.
204
201
205 Without args, fields() just split()'s the strings.
202 Without args, fields() just split()'s the strings.
206 """
203 """
207 if len(fields) == 0:
204 if len(fields) == 0:
208 return [el.split() for el in self]
205 return [el.split() for el in self]
209
206
210 res = SList()
207 res = SList()
211 for el in [f.split() for f in self]:
208 for el in [f.split() for f in self]:
212 lineparts = []
209 lineparts = []
213
210
214 for fd in fields:
211 for fd in fields:
215 try:
212 try:
216 lineparts.append(el[fd])
213 lineparts.append(el[fd])
217 except IndexError:
214 except IndexError:
218 pass
215 pass
219 if lineparts:
216 if lineparts:
220 res.append(" ".join(lineparts))
217 res.append(" ".join(lineparts))
221
218
222 return res
219 return res
223
220
224 def sort(self,field= None, nums = False):
221 def sort(self,field= None, nums = False):
225 """ sort by specified fields (see fields())
222 """ sort by specified fields (see fields())
226
223
227 Example::
224 Example::
228 a.sort(1, nums = True)
225 a.sort(1, nums = True)
229
226
230 Sorts a by second field, in numerical order (so that 21 > 3)
227 Sorts a by second field, in numerical order (so that 21 > 3)
231
228
232 """
229 """
233
230
234 #decorate, sort, undecorate
231 #decorate, sort, undecorate
235 if field is not None:
232 if field is not None:
236 dsu = [[SList([line]).fields(field), line] for line in self]
233 dsu = [[SList([line]).fields(field), line] for line in self]
237 else:
234 else:
238 dsu = [[line, line] for line in self]
235 dsu = [[line, line] for line in self]
239 if nums:
236 if nums:
240 for i in range(len(dsu)):
237 for i in range(len(dsu)):
241 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
238 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
242 try:
239 try:
243 n = int(numstr)
240 n = int(numstr)
244 except ValueError:
241 except ValueError:
245 n = 0;
242 n = 0;
246 dsu[i][0] = n
243 dsu[i][0] = n
247
244
248
245
249 dsu.sort()
246 dsu.sort()
250 return SList([t[1] for t in dsu])
247 return SList([t[1] for t in dsu])
251
248
252
249
253 # FIXME: We need to reimplement type specific displayhook and then add this
250 # FIXME: We need to reimplement type specific displayhook and then add this
254 # back as a custom printer. This should also be moved outside utils into the
251 # back as a custom printer. This should also be moved outside utils into the
255 # core.
252 # core.
256
253
257 # def print_slist(arg):
254 # def print_slist(arg):
258 # """ Prettier (non-repr-like) and more informative printer for SList """
255 # """ Prettier (non-repr-like) and more informative printer for SList """
259 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
256 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
260 # if hasattr(arg, 'hideonce') and arg.hideonce:
257 # if hasattr(arg, 'hideonce') and arg.hideonce:
261 # arg.hideonce = False
258 # arg.hideonce = False
262 # return
259 # return
263 #
260 #
264 # nlprint(arg)
261 # nlprint(arg)
265 #
262 #
266 # print_slist = result_display.when_type(SList)(print_slist)
263 # print_slist = result_display.when_type(SList)(print_slist)
267
264
268
265
269 def esc_quotes(strng):
266 def esc_quotes(strng):
270 """Return the input string with single and double quotes escaped out"""
267 """Return the input string with single and double quotes escaped out"""
271
268
272 return strng.replace('"','\\"').replace("'","\\'")
269 return strng.replace('"','\\"').replace("'","\\'")
273
270
274
271
275 def make_quoted_expr(s):
272 def make_quoted_expr(s):
276 """Return string s in appropriate quotes, using raw string if possible.
273 """Return string s in appropriate quotes, using raw string if possible.
277
274
278 XXX - example removed because it caused encoding errors in documentation
275 XXX - example removed because it caused encoding errors in documentation
279 generation. We need a new example that doesn't contain invalid chars.
276 generation. We need a new example that doesn't contain invalid chars.
280
277
281 Note the use of raw string and padding at the end to allow trailing
278 Note the use of raw string and padding at the end to allow trailing
282 backslash.
279 backslash.
283 """
280 """
284
281
285 tail = ''
282 tail = ''
286 tailpadding = ''
283 tailpadding = ''
287 raw = ''
284 raw = ''
288 if "\\" in s:
285 if "\\" in s:
289 raw = 'r'
286 raw = 'r'
290 if s.endswith('\\'):
287 if s.endswith('\\'):
291 tail = '[:-1]'
288 tail = '[:-1]'
292 tailpadding = '_'
289 tailpadding = '_'
293 if '"' not in s:
290 if '"' not in s:
294 quote = '"'
291 quote = '"'
295 elif "'" not in s:
292 elif "'" not in s:
296 quote = "'"
293 quote = "'"
297 elif '"""' not in s and not s.endswith('"'):
294 elif '"""' not in s and not s.endswith('"'):
298 quote = '"""'
295 quote = '"""'
299 elif "'''" not in s and not s.endswith("'"):
296 elif "'''" not in s and not s.endswith("'"):
300 quote = "'''"
297 quote = "'''"
301 else:
298 else:
302 # give up, backslash-escaped string will do
299 # give up, backslash-escaped string will do
303 return '"%s"' % esc_quotes(s)
300 return '"%s"' % esc_quotes(s)
304 res = raw + quote + s + tailpadding + quote + tail
301 res = raw + quote + s + tailpadding + quote + tail
305 return res
302 return res
306
303
307
304
308 def qw(words,flat=0,sep=None,maxsplit=-1):
305 def qw(words,flat=0,sep=None,maxsplit=-1):
309 """Similar to Perl's qw() operator, but with some more options.
306 """Similar to Perl's qw() operator, but with some more options.
310
307
311 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
308 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
312
309
313 words can also be a list itself, and with flat=1, the output will be
310 words can also be a list itself, and with flat=1, the output will be
314 recursively flattened.
311 recursively flattened.
315
312
316 Examples:
313 Examples:
317
314
318 >>> qw('1 2')
315 >>> qw('1 2')
319 ['1', '2']
316 ['1', '2']
320
317
321 >>> qw(['a b','1 2',['m n','p q']])
318 >>> qw(['a b','1 2',['m n','p q']])
322 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
319 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
323
320
324 >>> qw(['a b','1 2',['m n','p q']],flat=1)
321 >>> qw(['a b','1 2',['m n','p q']],flat=1)
325 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
322 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
326 """
323 """
327
324
328 if type(words) in StringTypes:
325 if isinstance(words, basestring):
329 return [word.strip() for word in words.split(sep,maxsplit)
326 return [word.strip() for word in words.split(sep,maxsplit)
330 if word and not word.isspace() ]
327 if word and not word.isspace() ]
331 if flat:
328 if flat:
332 return flatten(map(qw,words,[1]*len(words)))
329 return flatten(map(qw,words,[1]*len(words)))
333 return map(qw,words)
330 return map(qw,words)
334
331
335
332
336 def qwflat(words,sep=None,maxsplit=-1):
333 def qwflat(words,sep=None,maxsplit=-1):
337 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
334 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
338 return qw(words,1,sep,maxsplit)
335 return qw(words,1,sep,maxsplit)
339
336
340
337
341 def qw_lol(indata):
338 def qw_lol(indata):
342 """qw_lol('a b') -> [['a','b']],
339 """qw_lol('a b') -> [['a','b']],
343 otherwise it's just a call to qw().
340 otherwise it's just a call to qw().
344
341
345 We need this to make sure the modules_some keys *always* end up as a
342 We need this to make sure the modules_some keys *always* end up as a
346 list of lists."""
343 list of lists."""
347
344
348 if type(indata) in StringTypes:
345 if isinstance(indata, basestring):
349 return [qw(indata)]
346 return [qw(indata)]
350 else:
347 else:
351 return qw(indata)
348 return qw(indata)
352
349
353
350
354 def grep(pat,list,case=1):
351 def grep(pat,list,case=1):
355 """Simple minded grep-like function.
352 """Simple minded grep-like function.
356 grep(pat,list) returns occurrences of pat in list, None on failure.
353 grep(pat,list) returns occurrences of pat in list, None on failure.
357
354
358 It only does simple string matching, with no support for regexps. Use the
355 It only does simple string matching, with no support for regexps. Use the
359 option case=0 for case-insensitive matching."""
356 option case=0 for case-insensitive matching."""
360
357
361 # This is pretty crude. At least it should implement copying only references
358 # This is pretty crude. At least it should implement copying only references
362 # to the original data in case it's big. Now it copies the data for output.
359 # to the original data in case it's big. Now it copies the data for output.
363 out=[]
360 out=[]
364 if case:
361 if case:
365 for term in list:
362 for term in list:
366 if term.find(pat)>-1: out.append(term)
363 if term.find(pat)>-1: out.append(term)
367 else:
364 else:
368 lpat=pat.lower()
365 lpat=pat.lower()
369 for term in list:
366 for term in list:
370 if term.lower().find(lpat)>-1: out.append(term)
367 if term.lower().find(lpat)>-1: out.append(term)
371
368
372 if len(out): return out
369 if len(out): return out
373 else: return None
370 else: return None
374
371
375
372
376 def dgrep(pat,*opts):
373 def dgrep(pat,*opts):
377 """Return grep() on dir()+dir(__builtins__).
374 """Return grep() on dir()+dir(__builtins__).
378
375
379 A very common use of grep() when working interactively."""
376 A very common use of grep() when working interactively."""
380
377
381 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
378 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
382
379
383
380
384 def idgrep(pat):
381 def idgrep(pat):
385 """Case-insensitive dgrep()"""
382 """Case-insensitive dgrep()"""
386
383
387 return dgrep(pat,0)
384 return dgrep(pat,0)
388
385
389
386
390 def igrep(pat,list):
387 def igrep(pat,list):
391 """Synonym for case-insensitive grep."""
388 """Synonym for case-insensitive grep."""
392
389
393 return grep(pat,list,case=0)
390 return grep(pat,list,case=0)
394
391
395
392
396 def indent(str,nspaces=4,ntabs=0):
393 def indent(str,nspaces=4,ntabs=0):
397 """Indent a string a given number of spaces or tabstops.
394 """Indent a string a given number of spaces or tabstops.
398
395
399 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
396 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
400 """
397 """
401 if str is None:
398 if str is None:
402 return
399 return
403 ind = '\t'*ntabs+' '*nspaces
400 ind = '\t'*ntabs+' '*nspaces
404 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
401 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
405 if outstr.endswith(os.linesep+ind):
402 if outstr.endswith(os.linesep+ind):
406 return outstr[:-len(ind)]
403 return outstr[:-len(ind)]
407 else:
404 else:
408 return outstr
405 return outstr
409
406
410 def native_line_ends(filename,backup=1):
407 def native_line_ends(filename,backup=1):
411 """Convert (in-place) a file to line-ends native to the current OS.
408 """Convert (in-place) a file to line-ends native to the current OS.
412
409
413 If the optional backup argument is given as false, no backup of the
410 If the optional backup argument is given as false, no backup of the
414 original file is left. """
411 original file is left. """
415
412
416 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
413 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
417
414
418 bak_filename = filename + backup_suffixes[os.name]
415 bak_filename = filename + backup_suffixes[os.name]
419
416
420 original = open(filename).read()
417 original = open(filename).read()
421 shutil.copy2(filename,bak_filename)
418 shutil.copy2(filename,bak_filename)
422 try:
419 try:
423 new = open(filename,'wb')
420 new = open(filename,'wb')
424 new.write(os.linesep.join(original.splitlines()))
421 new.write(os.linesep.join(original.splitlines()))
425 new.write(os.linesep) # ALWAYS put an eol at the end of the file
422 new.write(os.linesep) # ALWAYS put an eol at the end of the file
426 new.close()
423 new.close()
427 except:
424 except:
428 os.rename(bak_filename,filename)
425 os.rename(bak_filename,filename)
429 if not backup:
426 if not backup:
430 try:
427 try:
431 os.remove(bak_filename)
428 os.remove(bak_filename)
432 except:
429 except:
433 pass
430 pass
434
431
435
432
436 def list_strings(arg):
433 def list_strings(arg):
437 """Always return a list of strings, given a string or list of strings
434 """Always return a list of strings, given a string or list of strings
438 as input.
435 as input.
439
436
440 :Examples:
437 :Examples:
441
438
442 In [7]: list_strings('A single string')
439 In [7]: list_strings('A single string')
443 Out[7]: ['A single string']
440 Out[7]: ['A single string']
444
441
445 In [8]: list_strings(['A single string in a list'])
442 In [8]: list_strings(['A single string in a list'])
446 Out[8]: ['A single string in a list']
443 Out[8]: ['A single string in a list']
447
444
448 In [9]: list_strings(['A','list','of','strings'])
445 In [9]: list_strings(['A','list','of','strings'])
449 Out[9]: ['A', 'list', 'of', 'strings']
446 Out[9]: ['A', 'list', 'of', 'strings']
450 """
447 """
451
448
452 if isinstance(arg,basestring): return [arg]
449 if isinstance(arg,basestring): return [arg]
453 else: return arg
450 else: return arg
454
451
455
452
456 def marquee(txt='',width=78,mark='*'):
453 def marquee(txt='',width=78,mark='*'):
457 """Return the input string centered in a 'marquee'.
454 """Return the input string centered in a 'marquee'.
458
455
459 :Examples:
456 :Examples:
460
457
461 In [16]: marquee('A test',40)
458 In [16]: marquee('A test',40)
462 Out[16]: '**************** A test ****************'
459 Out[16]: '**************** A test ****************'
463
460
464 In [17]: marquee('A test',40,'-')
461 In [17]: marquee('A test',40,'-')
465 Out[17]: '---------------- A test ----------------'
462 Out[17]: '---------------- A test ----------------'
466
463
467 In [18]: marquee('A test',40,' ')
464 In [18]: marquee('A test',40,' ')
468 Out[18]: ' A test '
465 Out[18]: ' A test '
469
466
470 """
467 """
471 if not txt:
468 if not txt:
472 return (mark*width)[:width]
469 return (mark*width)[:width]
473 nmark = (width-len(txt)-2)/len(mark)/2
470 nmark = (width-len(txt)-2)/len(mark)/2
474 if nmark < 0: nmark =0
471 if nmark < 0: nmark =0
475 marks = mark*nmark
472 marks = mark*nmark
476 return '%s %s %s' % (marks,txt,marks)
473 return '%s %s %s' % (marks,txt,marks)
477
474
478
475
479 ini_spaces_re = re.compile(r'^(\s+)')
476 ini_spaces_re = re.compile(r'^(\s+)')
480
477
481 def num_ini_spaces(strng):
478 def num_ini_spaces(strng):
482 """Return the number of initial spaces in a string"""
479 """Return the number of initial spaces in a string"""
483
480
484 ini_spaces = ini_spaces_re.match(strng)
481 ini_spaces = ini_spaces_re.match(strng)
485 if ini_spaces:
482 if ini_spaces:
486 return ini_spaces.end()
483 return ini_spaces.end()
487 else:
484 else:
488 return 0
485 return 0
489
486
490
487
491 def format_screen(strng):
488 def format_screen(strng):
492 """Format a string for screen printing.
489 """Format a string for screen printing.
493
490
494 This removes some latex-type format codes."""
491 This removes some latex-type format codes."""
495 # Paragraph continue
492 # Paragraph continue
496 par_re = re.compile(r'\\$',re.MULTILINE)
493 par_re = re.compile(r'\\$',re.MULTILINE)
497 strng = par_re.sub('',strng)
494 strng = par_re.sub('',strng)
498 return strng
495 return strng
499
496
@@ -1,656 +1,658 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Standard library imports.
18 # Standard library imports.
19 import __builtin__
19 import __builtin__
20 import atexit
20 import atexit
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24 import logging
24 import logging
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.jsonutil import json_clean
31 from IPython.utils.jsonutil import json_clean
32 from IPython.lib import pylabtools
32 from IPython.lib import pylabtools
33 from IPython.utils.traitlets import Instance, Float
33 from IPython.utils.traitlets import Instance, Float
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 start_kernel)
35 start_kernel)
36 from iostream import OutStream
36 from iostream import OutStream
37 from session import Session, Message
37 from session import Session, Message
38 from zmqshell import ZMQInteractiveShell
38 from zmqshell import ZMQInteractiveShell
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Globals
41 # Globals
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 # Module-level logger
44 # Module-level logger
45 logger = logging.getLogger(__name__)
45 logger = logging.getLogger(__name__)
46
46
47 # FIXME: this needs to be done more cleanly later, once we have proper
47 # FIXME: this needs to be done more cleanly later, once we have proper
48 # configuration support. This is a library, so it shouldn't set a stream
48 # configuration support. This is a library, so it shouldn't set a stream
49 # handler, see:
49 # handler, see:
50 # http://docs.python.org/library/logging.html#configuring-logging-for-a-library
50 # http://docs.python.org/library/logging.html#configuring-logging-for-a-library
51 # But this lets us at least do developer debugging for now by manually turning
51 # But this lets us at least do developer debugging for now by manually turning
52 # it on/off. And once we have full config support, the client entry points
52 # it on/off. And once we have full config support, the client entry points
53 # will select their logging handlers, as well as passing to this library the
53 # will select their logging handlers, as well as passing to this library the
54 # logging level.
54 # logging level.
55
55
56 if 0: # dbg - set to 1 to actually see the messages.
56 if 0: # dbg - set to 1 to actually see the messages.
57 logger.addHandler(logging.StreamHandler())
57 logger.addHandler(logging.StreamHandler())
58 logger.setLevel(logging.DEBUG)
58 logger.setLevel(logging.DEBUG)
59
59
60 # /FIXME
60 # /FIXME
61
61
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63 # Main kernel class
63 # Main kernel class
64 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
65
65
66 class Kernel(Configurable):
66 class Kernel(Configurable):
67
67
68 #---------------------------------------------------------------------------
68 #---------------------------------------------------------------------------
69 # Kernel interface
69 # Kernel interface
70 #---------------------------------------------------------------------------
70 #---------------------------------------------------------------------------
71
71
72 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
72 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
73 session = Instance(Session)
73 session = Instance(Session)
74 reply_socket = Instance('zmq.Socket')
74 reply_socket = Instance('zmq.Socket')
75 pub_socket = Instance('zmq.Socket')
75 pub_socket = Instance('zmq.Socket')
76 req_socket = Instance('zmq.Socket')
76 req_socket = Instance('zmq.Socket')
77
77
78 # Private interface
78 # Private interface
79
79
80 # Time to sleep after flushing the stdout/err buffers in each execute
80 # Time to sleep after flushing the stdout/err buffers in each execute
81 # cycle. While this introduces a hard limit on the minimal latency of the
81 # cycle. While this introduces a hard limit on the minimal latency of the
82 # execute cycle, it helps prevent output synchronization problems for
82 # execute cycle, it helps prevent output synchronization problems for
83 # clients.
83 # clients.
84 # Units are in seconds. The minimum zmq latency on local host is probably
84 # Units are in seconds. The minimum zmq latency on local host is probably
85 # ~150 microseconds, set this to 500us for now. We may need to increase it
85 # ~150 microseconds, set this to 500us for now. We may need to increase it
86 # a little if it's not enough after more interactive testing.
86 # a little if it's not enough after more interactive testing.
87 _execute_sleep = Float(0.0005, config=True)
87 _execute_sleep = Float(0.0005, config=True)
88
88
89 # Frequency of the kernel's event loop.
89 # Frequency of the kernel's event loop.
90 # Units are in seconds, kernel subclasses for GUI toolkits may need to
90 # Units are in seconds, kernel subclasses for GUI toolkits may need to
91 # adapt to milliseconds.
91 # adapt to milliseconds.
92 _poll_interval = Float(0.05, config=True)
92 _poll_interval = Float(0.05, config=True)
93
93
94 # If the shutdown was requested over the network, we leave here the
94 # If the shutdown was requested over the network, we leave here the
95 # necessary reply message so it can be sent by our registered atexit
95 # necessary reply message so it can be sent by our registered atexit
96 # handler. This ensures that the reply is only sent to clients truly at
96 # handler. This ensures that the reply is only sent to clients truly at
97 # the end of our shutdown process (which happens after the underlying
97 # the end of our shutdown process (which happens after the underlying
98 # IPython shell's own shutdown).
98 # IPython shell's own shutdown).
99 _shutdown_message = None
99 _shutdown_message = None
100
100
101 # This is a dict of port number that the kernel is listening on. It is set
101 # This is a dict of port number that the kernel is listening on. It is set
102 # by record_ports and used by connect_request.
102 # by record_ports and used by connect_request.
103 _recorded_ports = None
103 _recorded_ports = None
104
104
105
105
106 def __init__(self, **kwargs):
106 def __init__(self, **kwargs):
107 super(Kernel, self).__init__(**kwargs)
107 super(Kernel, self).__init__(**kwargs)
108
108
109 # Before we even start up the shell, register *first* our exit handlers
109 # Before we even start up the shell, register *first* our exit handlers
110 # so they come before the shell's
110 # so they come before the shell's
111 atexit.register(self._at_shutdown)
111 atexit.register(self._at_shutdown)
112
112
113 # Initialize the InteractiveShell subclass
113 # Initialize the InteractiveShell subclass
114 self.shell = ZMQInteractiveShell.instance()
114 self.shell = ZMQInteractiveShell.instance()
115 self.shell.displayhook.session = self.session
115 self.shell.displayhook.session = self.session
116 self.shell.displayhook.pub_socket = self.pub_socket
116 self.shell.displayhook.pub_socket = self.pub_socket
117 self.shell.display_pub.session = self.session
117 self.shell.display_pub.session = self.session
118 self.shell.display_pub.pub_socket = self.pub_socket
118 self.shell.display_pub.pub_socket = self.pub_socket
119
119
120 # TMP - hack while developing
120 # TMP - hack while developing
121 self.shell._reply_content = None
121 self.shell._reply_content = None
122
122
123 # Build dict of handlers for message types
123 # Build dict of handlers for message types
124 msg_types = [ 'execute_request', 'complete_request',
124 msg_types = [ 'execute_request', 'complete_request',
125 'object_info_request', 'history_request',
125 'object_info_request', 'history_tail_request',
126 'connect_request', 'shutdown_request']
126 'connect_request', 'shutdown_request']
127 self.handlers = {}
127 self.handlers = {}
128 for msg_type in msg_types:
128 for msg_type in msg_types:
129 self.handlers[msg_type] = getattr(self, msg_type)
129 self.handlers[msg_type] = getattr(self, msg_type)
130
130
131 def do_one_iteration(self):
131 def do_one_iteration(self):
132 """Do one iteration of the kernel's evaluation loop.
132 """Do one iteration of the kernel's evaluation loop.
133 """
133 """
134 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
134 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
135 if msg is None:
135 if msg is None:
136 return
136 return
137
137
138 # This assert will raise in versions of zeromq 2.0.7 and lesser.
138 # This assert will raise in versions of zeromq 2.0.7 and lesser.
139 # We now require 2.0.8 or above, so we can uncomment for safety.
139 # We now require 2.0.8 or above, so we can uncomment for safety.
140 # print(ident,msg, file=sys.__stdout__)
140 # print(ident,msg, file=sys.__stdout__)
141 assert ident is not None, "Missing message part."
141 assert ident is not None, "Missing message part."
142
142
143 # Print some info about this message and leave a '--->' marker, so it's
143 # Print some info about this message and leave a '--->' marker, so it's
144 # easier to trace visually the message chain when debugging. Each
144 # easier to trace visually the message chain when debugging. Each
145 # handler prints its message at the end.
145 # handler prints its message at the end.
146 # Eventually we'll move these from stdout to a logger.
146 # Eventually we'll move these from stdout to a logger.
147 logger.debug('\n*** MESSAGE TYPE:'+str(msg['msg_type'])+'***')
147 logger.debug('\n*** MESSAGE TYPE:'+str(msg['msg_type'])+'***')
148 logger.debug(' Content: '+str(msg['content'])+'\n --->\n ')
148 logger.debug(' Content: '+str(msg['content'])+'\n --->\n ')
149
149
150 # Find and call actual handler for message
150 # Find and call actual handler for message
151 handler = self.handlers.get(msg['msg_type'], None)
151 handler = self.handlers.get(msg['msg_type'], None)
152 if handler is None:
152 if handler is None:
153 logger.error("UNKNOWN MESSAGE TYPE:" +str(msg))
153 logger.error("UNKNOWN MESSAGE TYPE:" +str(msg))
154 else:
154 else:
155 handler(ident, msg)
155 handler(ident, msg)
156
156
157 # Check whether we should exit, in case the incoming message set the
157 # Check whether we should exit, in case the incoming message set the
158 # exit flag on
158 # exit flag on
159 if self.shell.exit_now:
159 if self.shell.exit_now:
160 logger.debug('\nExiting IPython kernel...')
160 logger.debug('\nExiting IPython kernel...')
161 # We do a normal, clean exit, which allows any actions registered
161 # We do a normal, clean exit, which allows any actions registered
162 # via atexit (such as history saving) to take place.
162 # via atexit (such as history saving) to take place.
163 sys.exit(0)
163 sys.exit(0)
164
164
165
165
166 def start(self):
166 def start(self):
167 """ Start the kernel main loop.
167 """ Start the kernel main loop.
168 """
168 """
169 while True:
169 while True:
170 time.sleep(self._poll_interval)
170 time.sleep(self._poll_interval)
171 self.do_one_iteration()
171 self.do_one_iteration()
172
172
173 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
173 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
174 """Record the ports that this kernel is using.
174 """Record the ports that this kernel is using.
175
175
176 The creator of the Kernel instance must call this methods if they
176 The creator of the Kernel instance must call this methods if they
177 want the :meth:`connect_request` method to return the port numbers.
177 want the :meth:`connect_request` method to return the port numbers.
178 """
178 """
179 self._recorded_ports = {
179 self._recorded_ports = {
180 'xrep_port' : xrep_port,
180 'xrep_port' : xrep_port,
181 'pub_port' : pub_port,
181 'pub_port' : pub_port,
182 'req_port' : req_port,
182 'req_port' : req_port,
183 'hb_port' : hb_port
183 'hb_port' : hb_port
184 }
184 }
185
185
186 #---------------------------------------------------------------------------
186 #---------------------------------------------------------------------------
187 # Kernel request handlers
187 # Kernel request handlers
188 #---------------------------------------------------------------------------
188 #---------------------------------------------------------------------------
189
189
190 def _publish_pyin(self, code, parent):
190 def _publish_pyin(self, code, parent):
191 """Publish the code request on the pyin stream."""
191 """Publish the code request on the pyin stream."""
192
192
193 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
193 pyin_msg = self.session.send(self.pub_socket, u'pyin',{u'code':code}, parent=parent)
194
194
195 def execute_request(self, ident, parent):
195 def execute_request(self, ident, parent):
196
196
197 status_msg = self.session.send(self.pub_socket,
197 status_msg = self.session.send(self.pub_socket,
198 u'status',
198 u'status',
199 {u'execution_state':u'busy'},
199 {u'execution_state':u'busy'},
200 parent=parent
200 parent=parent
201 )
201 )
202
202
203 try:
203 try:
204 content = parent[u'content']
204 content = parent[u'content']
205 code = content[u'code']
205 code = content[u'code']
206 silent = content[u'silent']
206 silent = content[u'silent']
207 except:
207 except:
208 logger.error("Got bad msg: ")
208 logger.error("Got bad msg: ")
209 logger.error(str(Message(parent)))
209 logger.error(str(Message(parent)))
210 return
210 return
211
211
212 shell = self.shell # we'll need this a lot here
212 shell = self.shell # we'll need this a lot here
213
213
214 # Replace raw_input. Note that is not sufficient to replace
214 # Replace raw_input. Note that is not sufficient to replace
215 # raw_input in the user namespace.
215 # raw_input in the user namespace.
216 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
216 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
217 __builtin__.raw_input = raw_input
217 __builtin__.raw_input = raw_input
218
218
219 # Set the parent message of the display hook and out streams.
219 # Set the parent message of the display hook and out streams.
220 shell.displayhook.set_parent(parent)
220 shell.displayhook.set_parent(parent)
221 shell.display_pub.set_parent(parent)
221 shell.display_pub.set_parent(parent)
222 sys.stdout.set_parent(parent)
222 sys.stdout.set_parent(parent)
223 sys.stderr.set_parent(parent)
223 sys.stderr.set_parent(parent)
224
224
225 # Re-broadcast our input for the benefit of listening clients, and
225 # Re-broadcast our input for the benefit of listening clients, and
226 # start computing output
226 # start computing output
227 if not silent:
227 if not silent:
228 self._publish_pyin(code, parent)
228 self._publish_pyin(code, parent)
229
229
230 reply_content = {}
230 reply_content = {}
231 try:
231 try:
232 if silent:
232 if silent:
233 # run_code uses 'exec' mode, so no displayhook will fire, and it
233 # run_code uses 'exec' mode, so no displayhook will fire, and it
234 # doesn't call logging or history manipulations. Print
234 # doesn't call logging or history manipulations. Print
235 # statements in that code will obviously still execute.
235 # statements in that code will obviously still execute.
236 shell.run_code(code)
236 shell.run_code(code)
237 else:
237 else:
238 # FIXME: the shell calls the exception handler itself.
238 # FIXME: the shell calls the exception handler itself.
239 shell._reply_content = None
239 shell._reply_content = None
240 shell.run_cell(code)
240 shell.run_cell(code)
241 except:
241 except:
242 status = u'error'
242 status = u'error'
243 # FIXME: this code right now isn't being used yet by default,
243 # FIXME: this code right now isn't being used yet by default,
244 # because the runlines() call above directly fires off exception
244 # because the runlines() call above directly fires off exception
245 # reporting. This code, therefore, is only active in the scenario
245 # reporting. This code, therefore, is only active in the scenario
246 # where runlines itself has an unhandled exception. We need to
246 # where runlines itself has an unhandled exception. We need to
247 # uniformize this, for all exception construction to come from a
247 # uniformize this, for all exception construction to come from a
248 # single location in the codbase.
248 # single location in the codbase.
249 etype, evalue, tb = sys.exc_info()
249 etype, evalue, tb = sys.exc_info()
250 tb_list = traceback.format_exception(etype, evalue, tb)
250 tb_list = traceback.format_exception(etype, evalue, tb)
251 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
251 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
252 else:
252 else:
253 status = u'ok'
253 status = u'ok'
254
254
255 reply_content[u'status'] = status
255 reply_content[u'status'] = status
256
256
257 # Return the execution counter so clients can display prompts
257 # Return the execution counter so clients can display prompts
258 reply_content['execution_count'] = shell.execution_count -1
258 reply_content['execution_count'] = shell.execution_count -1
259
259
260 # FIXME - fish exception info out of shell, possibly left there by
260 # FIXME - fish exception info out of shell, possibly left there by
261 # runlines. We'll need to clean up this logic later.
261 # runlines. We'll need to clean up this logic later.
262 if shell._reply_content is not None:
262 if shell._reply_content is not None:
263 reply_content.update(shell._reply_content)
263 reply_content.update(shell._reply_content)
264
264
265 # At this point, we can tell whether the main code execution succeeded
265 # At this point, we can tell whether the main code execution succeeded
266 # or not. If it did, we proceed to evaluate user_variables/expressions
266 # or not. If it did, we proceed to evaluate user_variables/expressions
267 if reply_content['status'] == 'ok':
267 if reply_content['status'] == 'ok':
268 reply_content[u'user_variables'] = \
268 reply_content[u'user_variables'] = \
269 shell.user_variables(content[u'user_variables'])
269 shell.user_variables(content[u'user_variables'])
270 reply_content[u'user_expressions'] = \
270 reply_content[u'user_expressions'] = \
271 shell.user_expressions(content[u'user_expressions'])
271 shell.user_expressions(content[u'user_expressions'])
272 else:
272 else:
273 # If there was an error, don't even try to compute variables or
273 # If there was an error, don't even try to compute variables or
274 # expressions
274 # expressions
275 reply_content[u'user_variables'] = {}
275 reply_content[u'user_variables'] = {}
276 reply_content[u'user_expressions'] = {}
276 reply_content[u'user_expressions'] = {}
277
277
278 # Payloads should be retrieved regardless of outcome, so we can both
278 # Payloads should be retrieved regardless of outcome, so we can both
279 # recover partial output (that could have been generated early in a
279 # recover partial output (that could have been generated early in a
280 # block, before an error) and clear the payload system always.
280 # block, before an error) and clear the payload system always.
281 reply_content[u'payload'] = shell.payload_manager.read_payload()
281 reply_content[u'payload'] = shell.payload_manager.read_payload()
282 # Be agressive about clearing the payload because we don't want
282 # Be agressive about clearing the payload because we don't want
283 # it to sit in memory until the next execute_request comes in.
283 # it to sit in memory until the next execute_request comes in.
284 shell.payload_manager.clear_payload()
284 shell.payload_manager.clear_payload()
285
285
286 # Flush output before sending the reply.
286 # Flush output before sending the reply.
287 sys.stdout.flush()
287 sys.stdout.flush()
288 sys.stderr.flush()
288 sys.stderr.flush()
289 # FIXME: on rare occasions, the flush doesn't seem to make it to the
289 # FIXME: on rare occasions, the flush doesn't seem to make it to the
290 # clients... This seems to mitigate the problem, but we definitely need
290 # clients... This seems to mitigate the problem, but we definitely need
291 # to better understand what's going on.
291 # to better understand what's going on.
292 if self._execute_sleep:
292 if self._execute_sleep:
293 time.sleep(self._execute_sleep)
293 time.sleep(self._execute_sleep)
294
294
295 # Send the reply.
295 # Send the reply.
296 reply_msg = self.session.send(self.reply_socket, u'execute_reply',
296 reply_msg = self.session.send(self.reply_socket, u'execute_reply',
297 reply_content, parent, ident=ident)
297 reply_content, parent, ident=ident)
298 logger.debug(str(reply_msg))
298 logger.debug(str(reply_msg))
299
299
300 if reply_msg['content']['status'] == u'error':
300 if reply_msg['content']['status'] == u'error':
301 self._abort_queue()
301 self._abort_queue()
302
302
303 status_msg = self.session.send(self.pub_socket,
303 status_msg = self.session.send(self.pub_socket,
304 u'status',
304 u'status',
305 {u'execution_state':u'idle'},
305 {u'execution_state':u'idle'},
306 parent=parent
306 parent=parent
307 )
307 )
308
308
309 def complete_request(self, ident, parent):
309 def complete_request(self, ident, parent):
310 txt, matches = self._complete(parent)
310 txt, matches = self._complete(parent)
311 matches = {'matches' : matches,
311 matches = {'matches' : matches,
312 'matched_text' : txt,
312 'matched_text' : txt,
313 'status' : 'ok'}
313 'status' : 'ok'}
314 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
314 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
315 matches, parent, ident)
315 matches, parent, ident)
316 logger.debug(str(completion_msg))
316 logger.debug(str(completion_msg))
317
317
318 def object_info_request(self, ident, parent):
318 def object_info_request(self, ident, parent):
319 object_info = self.shell.object_inspect(parent['content']['oname'])
319 object_info = self.shell.object_inspect(parent['content']['oname'])
320 # Before we send this object over, we scrub it for JSON usage
320 # Before we send this object over, we scrub it for JSON usage
321 oinfo = json_clean(object_info)
321 oinfo = json_clean(object_info)
322 msg = self.session.send(self.reply_socket, 'object_info_reply',
322 msg = self.session.send(self.reply_socket, 'object_info_reply',
323 oinfo, parent, ident)
323 oinfo, parent, ident)
324 logger.debug(msg)
324 logger.debug(msg)
325
325
326 def history_request(self, ident, parent):
326 def history_tail_request(self, ident, parent):
327 output = parent['content']['output']
327 # We need to pull these out, as passing **kwargs doesn't work with
328 index = parent['content']['index']
328 # unicode keys before Python 2.6.5.
329 n = parent['content']['n']
329 raw = parent['content']['raw']
330 raw = parent['content']['raw']
330 hist = self.shell.get_history(index=index, raw=raw, output=output)
331 output = parent['content']['output']
331 content = {'history' : hist}
332 hist = self.shell.history_manager.get_tail(n, raw=raw, output=output)
332 msg = self.session.send(self.reply_socket, 'history_reply',
333 content = {'history' : list(hist)}
334 msg = self.session.send(self.reply_socket, 'history_tail_reply',
333 content, parent, ident)
335 content, parent, ident)
334 logger.debug(str(msg))
336 logger.debug(str(msg))
335
337
336 def connect_request(self, ident, parent):
338 def connect_request(self, ident, parent):
337 if self._recorded_ports is not None:
339 if self._recorded_ports is not None:
338 content = self._recorded_ports.copy()
340 content = self._recorded_ports.copy()
339 else:
341 else:
340 content = {}
342 content = {}
341 msg = self.session.send(self.reply_socket, 'connect_reply',
343 msg = self.session.send(self.reply_socket, 'connect_reply',
342 content, parent, ident)
344 content, parent, ident)
343 logger.debug(msg)
345 logger.debug(msg)
344
346
345 def shutdown_request(self, ident, parent):
347 def shutdown_request(self, ident, parent):
346 self.shell.exit_now = True
348 self.shell.exit_now = True
347 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
349 self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent)
348 sys.exit(0)
350 sys.exit(0)
349
351
350 #---------------------------------------------------------------------------
352 #---------------------------------------------------------------------------
351 # Protected interface
353 # Protected interface
352 #---------------------------------------------------------------------------
354 #---------------------------------------------------------------------------
353
355
354 def _abort_queue(self):
356 def _abort_queue(self):
355 while True:
357 while True:
356 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
358 ident,msg = self.session.recv(self.reply_socket, zmq.NOBLOCK)
357 if msg is None:
359 if msg is None:
358 break
360 break
359 else:
361 else:
360 assert ident is not None, \
362 assert ident is not None, \
361 "Unexpected missing message part."
363 "Unexpected missing message part."
362
364
363 logger.debug("Aborting:\n"+str(Message(msg)))
365 logger.debug("Aborting:\n"+str(Message(msg)))
364 msg_type = msg['msg_type']
366 msg_type = msg['msg_type']
365 reply_type = msg_type.split('_')[0] + '_reply'
367 reply_type = msg_type.split('_')[0] + '_reply'
366 reply_msg = self.session.send(self.reply_socket, reply_type,
368 reply_msg = self.session.send(self.reply_socket, reply_type,
367 {'status' : 'aborted'}, msg, ident=ident)
369 {'status' : 'aborted'}, msg, ident=ident)
368 logger.debug(reply_msg)
370 logger.debug(reply_msg)
369 # We need to wait a bit for requests to come in. This can probably
371 # We need to wait a bit for requests to come in. This can probably
370 # be set shorter for true asynchronous clients.
372 # be set shorter for true asynchronous clients.
371 time.sleep(0.1)
373 time.sleep(0.1)
372
374
373 def _raw_input(self, prompt, ident, parent):
375 def _raw_input(self, prompt, ident, parent):
374 # Flush output before making the request.
376 # Flush output before making the request.
375 sys.stderr.flush()
377 sys.stderr.flush()
376 sys.stdout.flush()
378 sys.stdout.flush()
377
379
378 # Send the input request.
380 # Send the input request.
379 content = dict(prompt=prompt)
381 content = dict(prompt=prompt)
380 msg = self.session.send(self.req_socket, u'input_request', content, parent)
382 msg = self.session.send(self.req_socket, u'input_request', content, parent)
381
383
382 # Await a response.
384 # Await a response.
383 ident, reply = self.session.recv(self.req_socket, 0)
385 ident, reply = self.session.recv(self.req_socket, 0)
384 try:
386 try:
385 value = reply['content']['value']
387 value = reply['content']['value']
386 except:
388 except:
387 logger.error("Got bad raw_input reply: ")
389 logger.error("Got bad raw_input reply: ")
388 logger.error(str(Message(parent)))
390 logger.error(str(Message(parent)))
389 value = ''
391 value = ''
390 return value
392 return value
391
393
392 def _complete(self, msg):
394 def _complete(self, msg):
393 c = msg['content']
395 c = msg['content']
394 try:
396 try:
395 cpos = int(c['cursor_pos'])
397 cpos = int(c['cursor_pos'])
396 except:
398 except:
397 # If we don't get something that we can convert to an integer, at
399 # If we don't get something that we can convert to an integer, at
398 # least attempt the completion guessing the cursor is at the end of
400 # least attempt the completion guessing the cursor is at the end of
399 # the text, if there's any, and otherwise of the line
401 # the text, if there's any, and otherwise of the line
400 cpos = len(c['text'])
402 cpos = len(c['text'])
401 if cpos==0:
403 if cpos==0:
402 cpos = len(c['line'])
404 cpos = len(c['line'])
403 return self.shell.complete(c['text'], c['line'], cpos)
405 return self.shell.complete(c['text'], c['line'], cpos)
404
406
405 def _object_info(self, context):
407 def _object_info(self, context):
406 symbol, leftover = self._symbol_from_context(context)
408 symbol, leftover = self._symbol_from_context(context)
407 if symbol is not None and not leftover:
409 if symbol is not None and not leftover:
408 doc = getattr(symbol, '__doc__', '')
410 doc = getattr(symbol, '__doc__', '')
409 else:
411 else:
410 doc = ''
412 doc = ''
411 object_info = dict(docstring = doc)
413 object_info = dict(docstring = doc)
412 return object_info
414 return object_info
413
415
414 def _symbol_from_context(self, context):
416 def _symbol_from_context(self, context):
415 if not context:
417 if not context:
416 return None, context
418 return None, context
417
419
418 base_symbol_string = context[0]
420 base_symbol_string = context[0]
419 symbol = self.shell.user_ns.get(base_symbol_string, None)
421 symbol = self.shell.user_ns.get(base_symbol_string, None)
420 if symbol is None:
422 if symbol is None:
421 symbol = __builtin__.__dict__.get(base_symbol_string, None)
423 symbol = __builtin__.__dict__.get(base_symbol_string, None)
422 if symbol is None:
424 if symbol is None:
423 return None, context
425 return None, context
424
426
425 context = context[1:]
427 context = context[1:]
426 for i, name in enumerate(context):
428 for i, name in enumerate(context):
427 new_symbol = getattr(symbol, name, None)
429 new_symbol = getattr(symbol, name, None)
428 if new_symbol is None:
430 if new_symbol is None:
429 return symbol, context[i:]
431 return symbol, context[i:]
430 else:
432 else:
431 symbol = new_symbol
433 symbol = new_symbol
432
434
433 return symbol, []
435 return symbol, []
434
436
435 def _at_shutdown(self):
437 def _at_shutdown(self):
436 """Actions taken at shutdown by the kernel, called by python's atexit.
438 """Actions taken at shutdown by the kernel, called by python's atexit.
437 """
439 """
438 # io.rprint("Kernel at_shutdown") # dbg
440 # io.rprint("Kernel at_shutdown") # dbg
439 if self._shutdown_message is not None:
441 if self._shutdown_message is not None:
440 self.session.send(self.reply_socket, self._shutdown_message)
442 self.session.send(self.reply_socket, self._shutdown_message)
441 self.session.send(self.pub_socket, self._shutdown_message)
443 self.session.send(self.pub_socket, self._shutdown_message)
442 logger.debug(str(self._shutdown_message))
444 logger.debug(str(self._shutdown_message))
443 # A very short sleep to give zmq time to flush its message buffers
445 # A very short sleep to give zmq time to flush its message buffers
444 # before Python truly shuts down.
446 # before Python truly shuts down.
445 time.sleep(0.01)
447 time.sleep(0.01)
446
448
447
449
448 class QtKernel(Kernel):
450 class QtKernel(Kernel):
449 """A Kernel subclass with Qt support."""
451 """A Kernel subclass with Qt support."""
450
452
451 def start(self):
453 def start(self):
452 """Start a kernel with QtPy4 event loop integration."""
454 """Start a kernel with QtPy4 event loop integration."""
453
455
454 from PyQt4 import QtCore
456 from PyQt4 import QtCore
455 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
457 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
456
458
457 self.app = get_app_qt4([" "])
459 self.app = get_app_qt4([" "])
458 self.app.setQuitOnLastWindowClosed(False)
460 self.app.setQuitOnLastWindowClosed(False)
459 self.timer = QtCore.QTimer()
461 self.timer = QtCore.QTimer()
460 self.timer.timeout.connect(self.do_one_iteration)
462 self.timer.timeout.connect(self.do_one_iteration)
461 # Units for the timer are in milliseconds
463 # Units for the timer are in milliseconds
462 self.timer.start(1000*self._poll_interval)
464 self.timer.start(1000*self._poll_interval)
463 start_event_loop_qt4(self.app)
465 start_event_loop_qt4(self.app)
464
466
465
467
466 class WxKernel(Kernel):
468 class WxKernel(Kernel):
467 """A Kernel subclass with Wx support."""
469 """A Kernel subclass with Wx support."""
468
470
469 def start(self):
471 def start(self):
470 """Start a kernel with wx event loop support."""
472 """Start a kernel with wx event loop support."""
471
473
472 import wx
474 import wx
473 from IPython.lib.guisupport import start_event_loop_wx
475 from IPython.lib.guisupport import start_event_loop_wx
474
476
475 doi = self.do_one_iteration
477 doi = self.do_one_iteration
476 # Wx uses milliseconds
478 # Wx uses milliseconds
477 poll_interval = int(1000*self._poll_interval)
479 poll_interval = int(1000*self._poll_interval)
478
480
479 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
481 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
480 # We make the Frame hidden when we create it in the main app below.
482 # We make the Frame hidden when we create it in the main app below.
481 class TimerFrame(wx.Frame):
483 class TimerFrame(wx.Frame):
482 def __init__(self, func):
484 def __init__(self, func):
483 wx.Frame.__init__(self, None, -1)
485 wx.Frame.__init__(self, None, -1)
484 self.timer = wx.Timer(self)
486 self.timer = wx.Timer(self)
485 # Units for the timer are in milliseconds
487 # Units for the timer are in milliseconds
486 self.timer.Start(poll_interval)
488 self.timer.Start(poll_interval)
487 self.Bind(wx.EVT_TIMER, self.on_timer)
489 self.Bind(wx.EVT_TIMER, self.on_timer)
488 self.func = func
490 self.func = func
489
491
490 def on_timer(self, event):
492 def on_timer(self, event):
491 self.func()
493 self.func()
492
494
493 # We need a custom wx.App to create our Frame subclass that has the
495 # We need a custom wx.App to create our Frame subclass that has the
494 # wx.Timer to drive the ZMQ event loop.
496 # wx.Timer to drive the ZMQ event loop.
495 class IPWxApp(wx.App):
497 class IPWxApp(wx.App):
496 def OnInit(self):
498 def OnInit(self):
497 self.frame = TimerFrame(doi)
499 self.frame = TimerFrame(doi)
498 self.frame.Show(False)
500 self.frame.Show(False)
499 return True
501 return True
500
502
501 # The redirect=False here makes sure that wx doesn't replace
503 # The redirect=False here makes sure that wx doesn't replace
502 # sys.stdout/stderr with its own classes.
504 # sys.stdout/stderr with its own classes.
503 self.app = IPWxApp(redirect=False)
505 self.app = IPWxApp(redirect=False)
504 start_event_loop_wx(self.app)
506 start_event_loop_wx(self.app)
505
507
506
508
507 class TkKernel(Kernel):
509 class TkKernel(Kernel):
508 """A Kernel subclass with Tk support."""
510 """A Kernel subclass with Tk support."""
509
511
510 def start(self):
512 def start(self):
511 """Start a Tk enabled event loop."""
513 """Start a Tk enabled event loop."""
512
514
513 import Tkinter
515 import Tkinter
514 doi = self.do_one_iteration
516 doi = self.do_one_iteration
515 # Tk uses milliseconds
517 # Tk uses milliseconds
516 poll_interval = int(1000*self._poll_interval)
518 poll_interval = int(1000*self._poll_interval)
517 # For Tkinter, we create a Tk object and call its withdraw method.
519 # For Tkinter, we create a Tk object and call its withdraw method.
518 class Timer(object):
520 class Timer(object):
519 def __init__(self, func):
521 def __init__(self, func):
520 self.app = Tkinter.Tk()
522 self.app = Tkinter.Tk()
521 self.app.withdraw()
523 self.app.withdraw()
522 self.func = func
524 self.func = func
523
525
524 def on_timer(self):
526 def on_timer(self):
525 self.func()
527 self.func()
526 self.app.after(poll_interval, self.on_timer)
528 self.app.after(poll_interval, self.on_timer)
527
529
528 def start(self):
530 def start(self):
529 self.on_timer() # Call it once to get things going.
531 self.on_timer() # Call it once to get things going.
530 self.app.mainloop()
532 self.app.mainloop()
531
533
532 self.timer = Timer(doi)
534 self.timer = Timer(doi)
533 self.timer.start()
535 self.timer.start()
534
536
535
537
536 class GTKKernel(Kernel):
538 class GTKKernel(Kernel):
537 """A Kernel subclass with GTK support."""
539 """A Kernel subclass with GTK support."""
538
540
539 def start(self):
541 def start(self):
540 """Start the kernel, coordinating with the GTK event loop"""
542 """Start the kernel, coordinating with the GTK event loop"""
541 from .gui.gtkembed import GTKEmbed
543 from .gui.gtkembed import GTKEmbed
542
544
543 gtk_kernel = GTKEmbed(self)
545 gtk_kernel = GTKEmbed(self)
544 gtk_kernel.start()
546 gtk_kernel.start()
545
547
546
548
547 #-----------------------------------------------------------------------------
549 #-----------------------------------------------------------------------------
548 # Kernel main and launch functions
550 # Kernel main and launch functions
549 #-----------------------------------------------------------------------------
551 #-----------------------------------------------------------------------------
550
552
551 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
553 def launch_kernel(ip=None, xrep_port=0, pub_port=0, req_port=0, hb_port=0,
552 independent=False, pylab=False, colors=None):
554 independent=False, pylab=False, colors=None):
553 """Launches a localhost kernel, binding to the specified ports.
555 """Launches a localhost kernel, binding to the specified ports.
554
556
555 Parameters
557 Parameters
556 ----------
558 ----------
557 ip : str, optional
559 ip : str, optional
558 The ip address the kernel will bind to.
560 The ip address the kernel will bind to.
559
561
560 xrep_port : int, optional
562 xrep_port : int, optional
561 The port to use for XREP channel.
563 The port to use for XREP channel.
562
564
563 pub_port : int, optional
565 pub_port : int, optional
564 The port to use for the SUB channel.
566 The port to use for the SUB channel.
565
567
566 req_port : int, optional
568 req_port : int, optional
567 The port to use for the REQ (raw input) channel.
569 The port to use for the REQ (raw input) channel.
568
570
569 hb_port : int, optional
571 hb_port : int, optional
570 The port to use for the hearbeat REP channel.
572 The port to use for the hearbeat REP channel.
571
573
572 independent : bool, optional (default False)
574 independent : bool, optional (default False)
573 If set, the kernel process is guaranteed to survive if this process
575 If set, the kernel process is guaranteed to survive if this process
574 dies. If not set, an effort is made to ensure that the kernel is killed
576 dies. If not set, an effort is made to ensure that the kernel is killed
575 when this process dies. Note that in this case it is still good practice
577 when this process dies. Note that in this case it is still good practice
576 to kill kernels manually before exiting.
578 to kill kernels manually before exiting.
577
579
578 pylab : bool or string, optional (default False)
580 pylab : bool or string, optional (default False)
579 If not False, the kernel will be launched with pylab enabled. If a
581 If not False, the kernel will be launched with pylab enabled. If a
580 string is passed, matplotlib will use the specified backend. Otherwise,
582 string is passed, matplotlib will use the specified backend. Otherwise,
581 matplotlib's default backend will be used.
583 matplotlib's default backend will be used.
582
584
583 colors : None or string, optional (default None)
585 colors : None or string, optional (default None)
584 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
586 If not None, specify the color scheme. One of (NoColor, LightBG, Linux)
585
587
586 Returns
588 Returns
587 -------
589 -------
588 A tuple of form:
590 A tuple of form:
589 (kernel_process, xrep_port, pub_port, req_port)
591 (kernel_process, xrep_port, pub_port, req_port)
590 where kernel_process is a Popen object and the ports are integers.
592 where kernel_process is a Popen object and the ports are integers.
591 """
593 """
592 extra_arguments = []
594 extra_arguments = []
593 if pylab:
595 if pylab:
594 extra_arguments.append('--pylab')
596 extra_arguments.append('--pylab')
595 if isinstance(pylab, basestring):
597 if isinstance(pylab, basestring):
596 extra_arguments.append(pylab)
598 extra_arguments.append(pylab)
597 if ip is not None:
599 if ip is not None:
598 extra_arguments.append('--ip')
600 extra_arguments.append('--ip')
599 if isinstance(ip, basestring):
601 if isinstance(ip, basestring):
600 extra_arguments.append(ip)
602 extra_arguments.append(ip)
601 if colors is not None:
603 if colors is not None:
602 extra_arguments.append('--colors')
604 extra_arguments.append('--colors')
603 extra_arguments.append(colors)
605 extra_arguments.append(colors)
604 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
606 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
605 xrep_port, pub_port, req_port, hb_port,
607 xrep_port, pub_port, req_port, hb_port,
606 independent, extra_arguments)
608 independent, extra_arguments)
607
609
608
610
609 def main():
611 def main():
610 """ The IPython kernel main entry point.
612 """ The IPython kernel main entry point.
611 """
613 """
612 parser = make_argument_parser()
614 parser = make_argument_parser()
613 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
615 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
614 const='auto', help = \
616 const='auto', help = \
615 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
617 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
616 given, the GUI backend is matplotlib's, otherwise use one of: \
618 given, the GUI backend is matplotlib's, otherwise use one of: \
617 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
619 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
618 parser.add_argument('--colors',
620 parser.add_argument('--colors',
619 type=str, dest='colors',
621 type=str, dest='colors',
620 help="Set the color scheme (NoColor, Linux, and LightBG).",
622 help="Set the color scheme (NoColor, Linux, and LightBG).",
621 metavar='ZMQInteractiveShell.colors')
623 metavar='ZMQInteractiveShell.colors')
622 namespace = parser.parse_args()
624 namespace = parser.parse_args()
623
625
624 kernel_class = Kernel
626 kernel_class = Kernel
625
627
626 kernel_classes = {
628 kernel_classes = {
627 'qt' : QtKernel,
629 'qt' : QtKernel,
628 'qt4': QtKernel,
630 'qt4': QtKernel,
629 'inline': Kernel,
631 'inline': Kernel,
630 'wx' : WxKernel,
632 'wx' : WxKernel,
631 'tk' : TkKernel,
633 'tk' : TkKernel,
632 'gtk': GTKKernel,
634 'gtk': GTKKernel,
633 }
635 }
634 if namespace.pylab:
636 if namespace.pylab:
635 if namespace.pylab == 'auto':
637 if namespace.pylab == 'auto':
636 gui, backend = pylabtools.find_gui_and_backend()
638 gui, backend = pylabtools.find_gui_and_backend()
637 else:
639 else:
638 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
640 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
639 kernel_class = kernel_classes.get(gui)
641 kernel_class = kernel_classes.get(gui)
640 if kernel_class is None:
642 if kernel_class is None:
641 raise ValueError('GUI is not supported: %r' % gui)
643 raise ValueError('GUI is not supported: %r' % gui)
642 pylabtools.activate_matplotlib(backend)
644 pylabtools.activate_matplotlib(backend)
643 if namespace.colors:
645 if namespace.colors:
644 ZMQInteractiveShell.colors=namespace.colors
646 ZMQInteractiveShell.colors=namespace.colors
645
647
646 kernel = make_kernel(namespace, kernel_class, OutStream)
648 kernel = make_kernel(namespace, kernel_class, OutStream)
647
649
648 if namespace.pylab:
650 if namespace.pylab:
649 pylabtools.import_pylab(kernel.shell.user_ns, backend,
651 pylabtools.import_pylab(kernel.shell.user_ns, backend,
650 shell=kernel.shell)
652 shell=kernel.shell)
651
653
652 start_kernel(namespace, kernel)
654 start_kernel(namespace, kernel)
653
655
654
656
655 if __name__ == '__main__':
657 if __name__ == '__main__':
656 main()
658 main()
@@ -1,910 +1,908 b''
1 """Base classes to manage the interaction with a running kernel.
1 """Base classes to manage the interaction with a running kernel.
2
2
3 TODO
3 TODO
4 * Create logger to handle debugging and console messages.
4 * Create logger to handle debugging and console messages.
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2010 The IPython Development Team
8 # Copyright (C) 2008-2010 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 # Standard library imports.
18 # Standard library imports.
19 import atexit
19 import atexit
20 from Queue import Queue, Empty
20 from Queue import Queue, Empty
21 from subprocess import Popen
21 from subprocess import Popen
22 import signal
22 import signal
23 import sys
23 import sys
24 from threading import Thread
24 from threading import Thread
25 import time
25 import time
26 import logging
26 import logging
27
27
28 # System library imports.
28 # System library imports.
29 import zmq
29 import zmq
30 from zmq import POLLIN, POLLOUT, POLLERR
30 from zmq import POLLIN, POLLOUT, POLLERR
31 from zmq.eventloop import ioloop
31 from zmq.eventloop import ioloop
32
32
33 # Local imports.
33 # Local imports.
34 from IPython.utils import io
34 from IPython.utils import io
35 from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS
35 from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS
36 from IPython.utils.traitlets import HasTraits, Any, Instance, Type, TCPAddress
36 from IPython.utils.traitlets import HasTraits, Any, Instance, Type, TCPAddress
37 from session import Session, Message
37 from session import Session, Message
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Constants and exceptions
40 # Constants and exceptions
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 class InvalidPortNumber(Exception):
43 class InvalidPortNumber(Exception):
44 pass
44 pass
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Utility functions
47 # Utility functions
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50 # some utilities to validate message structure, these might get moved elsewhere
50 # some utilities to validate message structure, these might get moved elsewhere
51 # if they prove to have more generic utility
51 # if they prove to have more generic utility
52
52
53 def validate_string_list(lst):
53 def validate_string_list(lst):
54 """Validate that the input is a list of strings.
54 """Validate that the input is a list of strings.
55
55
56 Raises ValueError if not."""
56 Raises ValueError if not."""
57 if not isinstance(lst, list):
57 if not isinstance(lst, list):
58 raise ValueError('input %r must be a list' % lst)
58 raise ValueError('input %r must be a list' % lst)
59 for x in lst:
59 for x in lst:
60 if not isinstance(x, basestring):
60 if not isinstance(x, basestring):
61 raise ValueError('element %r in list must be a string' % x)
61 raise ValueError('element %r in list must be a string' % x)
62
62
63
63
64 def validate_string_dict(dct):
64 def validate_string_dict(dct):
65 """Validate that the input is a dict with string keys and values.
65 """Validate that the input is a dict with string keys and values.
66
66
67 Raises ValueError if not."""
67 Raises ValueError if not."""
68 for k,v in dct.iteritems():
68 for k,v in dct.iteritems():
69 if not isinstance(k, basestring):
69 if not isinstance(k, basestring):
70 raise ValueError('key %r in dict must be a string' % k)
70 raise ValueError('key %r in dict must be a string' % k)
71 if not isinstance(v, basestring):
71 if not isinstance(v, basestring):
72 raise ValueError('value %r in dict must be a string' % v)
72 raise ValueError('value %r in dict must be a string' % v)
73
73
74
74
75 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
76 # ZMQ Socket Channel classes
76 # ZMQ Socket Channel classes
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78
78
79 class ZmqSocketChannel(Thread):
79 class ZmqSocketChannel(Thread):
80 """The base class for the channels that use ZMQ sockets.
80 """The base class for the channels that use ZMQ sockets.
81 """
81 """
82 context = None
82 context = None
83 session = None
83 session = None
84 socket = None
84 socket = None
85 ioloop = None
85 ioloop = None
86 iostate = None
86 iostate = None
87 _address = None
87 _address = None
88
88
89 def __init__(self, context, session, address):
89 def __init__(self, context, session, address):
90 """Create a channel
90 """Create a channel
91
91
92 Parameters
92 Parameters
93 ----------
93 ----------
94 context : :class:`zmq.Context`
94 context : :class:`zmq.Context`
95 The ZMQ context to use.
95 The ZMQ context to use.
96 session : :class:`session.Session`
96 session : :class:`session.Session`
97 The session to use.
97 The session to use.
98 address : tuple
98 address : tuple
99 Standard (ip, port) tuple that the kernel is listening on.
99 Standard (ip, port) tuple that the kernel is listening on.
100 """
100 """
101 super(ZmqSocketChannel, self).__init__()
101 super(ZmqSocketChannel, self).__init__()
102 self.daemon = True
102 self.daemon = True
103
103
104 self.context = context
104 self.context = context
105 self.session = session
105 self.session = session
106 if address[1] == 0:
106 if address[1] == 0:
107 message = 'The port number for a channel cannot be 0.'
107 message = 'The port number for a channel cannot be 0.'
108 raise InvalidPortNumber(message)
108 raise InvalidPortNumber(message)
109 self._address = address
109 self._address = address
110
110
111 def stop(self):
111 def stop(self):
112 """Stop the channel's activity.
112 """Stop the channel's activity.
113
113
114 This calls :method:`Thread.join` and returns when the thread
114 This calls :method:`Thread.join` and returns when the thread
115 terminates. :class:`RuntimeError` will be raised if
115 terminates. :class:`RuntimeError` will be raised if
116 :method:`self.start` is called again.
116 :method:`self.start` is called again.
117 """
117 """
118 self.join()
118 self.join()
119
119
120 @property
120 @property
121 def address(self):
121 def address(self):
122 """Get the channel's address as an (ip, port) tuple.
122 """Get the channel's address as an (ip, port) tuple.
123
123
124 By the default, the address is (localhost, 0), where 0 means a random
124 By the default, the address is (localhost, 0), where 0 means a random
125 port.
125 port.
126 """
126 """
127 return self._address
127 return self._address
128
128
129 def add_io_state(self, state):
129 def add_io_state(self, state):
130 """Add IO state to the eventloop.
130 """Add IO state to the eventloop.
131
131
132 Parameters
132 Parameters
133 ----------
133 ----------
134 state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR
134 state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR
135 The IO state flag to set.
135 The IO state flag to set.
136
136
137 This is thread safe as it uses the thread safe IOLoop.add_callback.
137 This is thread safe as it uses the thread safe IOLoop.add_callback.
138 """
138 """
139 def add_io_state_callback():
139 def add_io_state_callback():
140 if not self.iostate & state:
140 if not self.iostate & state:
141 self.iostate = self.iostate | state
141 self.iostate = self.iostate | state
142 self.ioloop.update_handler(self.socket, self.iostate)
142 self.ioloop.update_handler(self.socket, self.iostate)
143 self.ioloop.add_callback(add_io_state_callback)
143 self.ioloop.add_callback(add_io_state_callback)
144
144
145 def drop_io_state(self, state):
145 def drop_io_state(self, state):
146 """Drop IO state from the eventloop.
146 """Drop IO state from the eventloop.
147
147
148 Parameters
148 Parameters
149 ----------
149 ----------
150 state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR
150 state : zmq.POLLIN|zmq.POLLOUT|zmq.POLLERR
151 The IO state flag to set.
151 The IO state flag to set.
152
152
153 This is thread safe as it uses the thread safe IOLoop.add_callback.
153 This is thread safe as it uses the thread safe IOLoop.add_callback.
154 """
154 """
155 def drop_io_state_callback():
155 def drop_io_state_callback():
156 if self.iostate & state:
156 if self.iostate & state:
157 self.iostate = self.iostate & (~state)
157 self.iostate = self.iostate & (~state)
158 self.ioloop.update_handler(self.socket, self.iostate)
158 self.ioloop.update_handler(self.socket, self.iostate)
159 self.ioloop.add_callback(drop_io_state_callback)
159 self.ioloop.add_callback(drop_io_state_callback)
160
160
161
161
162 class XReqSocketChannel(ZmqSocketChannel):
162 class XReqSocketChannel(ZmqSocketChannel):
163 """The XREQ channel for issues request/replies to the kernel.
163 """The XREQ channel for issues request/replies to the kernel.
164 """
164 """
165
165
166 command_queue = None
166 command_queue = None
167
167
168 def __init__(self, context, session, address):
168 def __init__(self, context, session, address):
169 super(XReqSocketChannel, self).__init__(context, session, address)
169 super(XReqSocketChannel, self).__init__(context, session, address)
170 self.command_queue = Queue()
170 self.command_queue = Queue()
171 self.ioloop = ioloop.IOLoop()
171 self.ioloop = ioloop.IOLoop()
172
172
173 def run(self):
173 def run(self):
174 """The thread's main activity. Call start() instead."""
174 """The thread's main activity. Call start() instead."""
175 self.socket = self.context.socket(zmq.XREQ)
175 self.socket = self.context.socket(zmq.XREQ)
176 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
176 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
177 self.socket.connect('tcp://%s:%i' % self.address)
177 self.socket.connect('tcp://%s:%i' % self.address)
178 self.iostate = POLLERR|POLLIN
178 self.iostate = POLLERR|POLLIN
179 self.ioloop.add_handler(self.socket, self._handle_events,
179 self.ioloop.add_handler(self.socket, self._handle_events,
180 self.iostate)
180 self.iostate)
181 self.ioloop.start()
181 self.ioloop.start()
182
182
183 def stop(self):
183 def stop(self):
184 self.ioloop.stop()
184 self.ioloop.stop()
185 super(XReqSocketChannel, self).stop()
185 super(XReqSocketChannel, self).stop()
186
186
187 def call_handlers(self, msg):
187 def call_handlers(self, msg):
188 """This method is called in the ioloop thread when a message arrives.
188 """This method is called in the ioloop thread when a message arrives.
189
189
190 Subclasses should override this method to handle incoming messages.
190 Subclasses should override this method to handle incoming messages.
191 It is important to remember that this method is called in the thread
191 It is important to remember that this method is called in the thread
192 so that some logic must be done to ensure that the application leve
192 so that some logic must be done to ensure that the application leve
193 handlers are called in the application thread.
193 handlers are called in the application thread.
194 """
194 """
195 raise NotImplementedError('call_handlers must be defined in a subclass.')
195 raise NotImplementedError('call_handlers must be defined in a subclass.')
196
196
197 def execute(self, code, silent=False,
197 def execute(self, code, silent=False,
198 user_variables=None, user_expressions=None):
198 user_variables=None, user_expressions=None):
199 """Execute code in the kernel.
199 """Execute code in the kernel.
200
200
201 Parameters
201 Parameters
202 ----------
202 ----------
203 code : str
203 code : str
204 A string of Python code.
204 A string of Python code.
205
205
206 silent : bool, optional (default False)
206 silent : bool, optional (default False)
207 If set, the kernel will execute the code as quietly possible.
207 If set, the kernel will execute the code as quietly possible.
208
208
209 user_variables : list, optional
209 user_variables : list, optional
210 A list of variable names to pull from the user's namespace. They
210 A list of variable names to pull from the user's namespace. They
211 will come back as a dict with these names as keys and their
211 will come back as a dict with these names as keys and their
212 :func:`repr` as values.
212 :func:`repr` as values.
213
213
214 user_expressions : dict, optional
214 user_expressions : dict, optional
215 A dict with string keys and to pull from the user's
215 A dict with string keys and to pull from the user's
216 namespace. They will come back as a dict with these names as keys
216 namespace. They will come back as a dict with these names as keys
217 and their :func:`repr` as values.
217 and their :func:`repr` as values.
218
218
219 Returns
219 Returns
220 -------
220 -------
221 The msg_id of the message sent.
221 The msg_id of the message sent.
222 """
222 """
223 if user_variables is None:
223 if user_variables is None:
224 user_variables = []
224 user_variables = []
225 if user_expressions is None:
225 if user_expressions is None:
226 user_expressions = {}
226 user_expressions = {}
227
227
228 # Don't waste network traffic if inputs are invalid
228 # Don't waste network traffic if inputs are invalid
229 if not isinstance(code, basestring):
229 if not isinstance(code, basestring):
230 raise ValueError('code %r must be a string' % code)
230 raise ValueError('code %r must be a string' % code)
231 validate_string_list(user_variables)
231 validate_string_list(user_variables)
232 validate_string_dict(user_expressions)
232 validate_string_dict(user_expressions)
233
233
234 # Create class for content/msg creation. Related to, but possibly
234 # Create class for content/msg creation. Related to, but possibly
235 # not in Session.
235 # not in Session.
236 content = dict(code=code, silent=silent,
236 content = dict(code=code, silent=silent,
237 user_variables=user_variables,
237 user_variables=user_variables,
238 user_expressions=user_expressions)
238 user_expressions=user_expressions)
239 msg = self.session.msg('execute_request', content)
239 msg = self.session.msg('execute_request', content)
240 self._queue_request(msg)
240 self._queue_request(msg)
241 return msg['header']['msg_id']
241 return msg['header']['msg_id']
242
242
243 def complete(self, text, line, cursor_pos, block=None):
243 def complete(self, text, line, cursor_pos, block=None):
244 """Tab complete text in the kernel's namespace.
244 """Tab complete text in the kernel's namespace.
245
245
246 Parameters
246 Parameters
247 ----------
247 ----------
248 text : str
248 text : str
249 The text to complete.
249 The text to complete.
250 line : str
250 line : str
251 The full line of text that is the surrounding context for the
251 The full line of text that is the surrounding context for the
252 text to complete.
252 text to complete.
253 cursor_pos : int
253 cursor_pos : int
254 The position of the cursor in the line where the completion was
254 The position of the cursor in the line where the completion was
255 requested.
255 requested.
256 block : str, optional
256 block : str, optional
257 The full block of code in which the completion is being requested.
257 The full block of code in which the completion is being requested.
258
258
259 Returns
259 Returns
260 -------
260 -------
261 The msg_id of the message sent.
261 The msg_id of the message sent.
262 """
262 """
263 content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos)
263 content = dict(text=text, line=line, block=block, cursor_pos=cursor_pos)
264 msg = self.session.msg('complete_request', content)
264 msg = self.session.msg('complete_request', content)
265 self._queue_request(msg)
265 self._queue_request(msg)
266 return msg['header']['msg_id']
266 return msg['header']['msg_id']
267
267
268 def object_info(self, oname):
268 def object_info(self, oname):
269 """Get metadata information about an object.
269 """Get metadata information about an object.
270
270
271 Parameters
271 Parameters
272 ----------
272 ----------
273 oname : str
273 oname : str
274 A string specifying the object name.
274 A string specifying the object name.
275
275
276 Returns
276 Returns
277 -------
277 -------
278 The msg_id of the message sent.
278 The msg_id of the message sent.
279 """
279 """
280 content = dict(oname=oname)
280 content = dict(oname=oname)
281 msg = self.session.msg('object_info_request', content)
281 msg = self.session.msg('object_info_request', content)
282 self._queue_request(msg)
282 self._queue_request(msg)
283 return msg['header']['msg_id']
283 return msg['header']['msg_id']
284
284
285 def history(self, index=None, raw=False, output=True):
285 def history_tail(self, n=10, raw=True, output=False):
286 """Get the history list.
286 """Get the history list.
287
287
288 Parameters
288 Parameters
289 ----------
289 ----------
290 index : n or (n1, n2) or None
290 n : int
291 If n, then the last entries. If a tuple, then all in
291 The number of lines of history to get.
292 range(n1, n2). If None, then all entries. Raises IndexError if
293 the format of index is incorrect.
294 raw : bool
292 raw : bool
295 If True, return the raw input.
293 If True, return the raw input.
296 output : bool
294 output : bool
297 If True, then return the output as well.
295 If True, then return the output as well.
298
296
299 Returns
297 Returns
300 -------
298 -------
301 The msg_id of the message sent.
299 The msg_id of the message sent.
302 """
300 """
303 content = dict(index=index, raw=raw, output=output)
301 content = dict(n=n, raw=raw, output=output)
304 msg = self.session.msg('history_request', content)
302 msg = self.session.msg('history_tail_request', content)
305 self._queue_request(msg)
303 self._queue_request(msg)
306 return msg['header']['msg_id']
304 return msg['header']['msg_id']
307
305
308 def shutdown(self, restart=False):
306 def shutdown(self, restart=False):
309 """Request an immediate kernel shutdown.
307 """Request an immediate kernel shutdown.
310
308
311 Upon receipt of the (empty) reply, client code can safely assume that
309 Upon receipt of the (empty) reply, client code can safely assume that
312 the kernel has shut down and it's safe to forcefully terminate it if
310 the kernel has shut down and it's safe to forcefully terminate it if
313 it's still alive.
311 it's still alive.
314
312
315 The kernel will send the reply via a function registered with Python's
313 The kernel will send the reply via a function registered with Python's
316 atexit module, ensuring it's truly done as the kernel is done with all
314 atexit module, ensuring it's truly done as the kernel is done with all
317 normal operation.
315 normal operation.
318 """
316 """
319 # Send quit message to kernel. Once we implement kernel-side setattr,
317 # Send quit message to kernel. Once we implement kernel-side setattr,
320 # this should probably be done that way, but for now this will do.
318 # this should probably be done that way, but for now this will do.
321 msg = self.session.msg('shutdown_request', {'restart':restart})
319 msg = self.session.msg('shutdown_request', {'restart':restart})
322 self._queue_request(msg)
320 self._queue_request(msg)
323 return msg['header']['msg_id']
321 return msg['header']['msg_id']
324
322
325 def _handle_events(self, socket, events):
323 def _handle_events(self, socket, events):
326 if events & POLLERR:
324 if events & POLLERR:
327 self._handle_err()
325 self._handle_err()
328 if events & POLLOUT:
326 if events & POLLOUT:
329 self._handle_send()
327 self._handle_send()
330 if events & POLLIN:
328 if events & POLLIN:
331 self._handle_recv()
329 self._handle_recv()
332
330
333 def _handle_recv(self):
331 def _handle_recv(self):
334 ident,msg = self.session.recv(self.socket, 0)
332 ident,msg = self.session.recv(self.socket, 0)
335 self.call_handlers(msg)
333 self.call_handlers(msg)
336
334
337 def _handle_send(self):
335 def _handle_send(self):
338 try:
336 try:
339 msg = self.command_queue.get(False)
337 msg = self.command_queue.get(False)
340 except Empty:
338 except Empty:
341 pass
339 pass
342 else:
340 else:
343 self.session.send(self.socket,msg)
341 self.session.send(self.socket,msg)
344 if self.command_queue.empty():
342 if self.command_queue.empty():
345 self.drop_io_state(POLLOUT)
343 self.drop_io_state(POLLOUT)
346
344
347 def _handle_err(self):
345 def _handle_err(self):
348 # We don't want to let this go silently, so eventually we should log.
346 # We don't want to let this go silently, so eventually we should log.
349 raise zmq.ZMQError()
347 raise zmq.ZMQError()
350
348
351 def _queue_request(self, msg):
349 def _queue_request(self, msg):
352 self.command_queue.put(msg)
350 self.command_queue.put(msg)
353 self.add_io_state(POLLOUT)
351 self.add_io_state(POLLOUT)
354
352
355
353
356 class SubSocketChannel(ZmqSocketChannel):
354 class SubSocketChannel(ZmqSocketChannel):
357 """The SUB channel which listens for messages that the kernel publishes.
355 """The SUB channel which listens for messages that the kernel publishes.
358 """
356 """
359
357
360 def __init__(self, context, session, address):
358 def __init__(self, context, session, address):
361 super(SubSocketChannel, self).__init__(context, session, address)
359 super(SubSocketChannel, self).__init__(context, session, address)
362 self.ioloop = ioloop.IOLoop()
360 self.ioloop = ioloop.IOLoop()
363
361
364 def run(self):
362 def run(self):
365 """The thread's main activity. Call start() instead."""
363 """The thread's main activity. Call start() instead."""
366 self.socket = self.context.socket(zmq.SUB)
364 self.socket = self.context.socket(zmq.SUB)
367 self.socket.setsockopt(zmq.SUBSCRIBE,'')
365 self.socket.setsockopt(zmq.SUBSCRIBE,'')
368 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
366 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
369 self.socket.connect('tcp://%s:%i' % self.address)
367 self.socket.connect('tcp://%s:%i' % self.address)
370 self.iostate = POLLIN|POLLERR
368 self.iostate = POLLIN|POLLERR
371 self.ioloop.add_handler(self.socket, self._handle_events,
369 self.ioloop.add_handler(self.socket, self._handle_events,
372 self.iostate)
370 self.iostate)
373 self.ioloop.start()
371 self.ioloop.start()
374
372
375 def stop(self):
373 def stop(self):
376 self.ioloop.stop()
374 self.ioloop.stop()
377 super(SubSocketChannel, self).stop()
375 super(SubSocketChannel, self).stop()
378
376
379 def call_handlers(self, msg):
377 def call_handlers(self, msg):
380 """This method is called in the ioloop thread when a message arrives.
378 """This method is called in the ioloop thread when a message arrives.
381
379
382 Subclasses should override this method to handle incoming messages.
380 Subclasses should override this method to handle incoming messages.
383 It is important to remember that this method is called in the thread
381 It is important to remember that this method is called in the thread
384 so that some logic must be done to ensure that the application leve
382 so that some logic must be done to ensure that the application leve
385 handlers are called in the application thread.
383 handlers are called in the application thread.
386 """
384 """
387 raise NotImplementedError('call_handlers must be defined in a subclass.')
385 raise NotImplementedError('call_handlers must be defined in a subclass.')
388
386
389 def flush(self, timeout=1.0):
387 def flush(self, timeout=1.0):
390 """Immediately processes all pending messages on the SUB channel.
388 """Immediately processes all pending messages on the SUB channel.
391
389
392 Callers should use this method to ensure that :method:`call_handlers`
390 Callers should use this method to ensure that :method:`call_handlers`
393 has been called for all messages that have been received on the
391 has been called for all messages that have been received on the
394 0MQ SUB socket of this channel.
392 0MQ SUB socket of this channel.
395
393
396 This method is thread safe.
394 This method is thread safe.
397
395
398 Parameters
396 Parameters
399 ----------
397 ----------
400 timeout : float, optional
398 timeout : float, optional
401 The maximum amount of time to spend flushing, in seconds. The
399 The maximum amount of time to spend flushing, in seconds. The
402 default is one second.
400 default is one second.
403 """
401 """
404 # We do the IOLoop callback process twice to ensure that the IOLoop
402 # We do the IOLoop callback process twice to ensure that the IOLoop
405 # gets to perform at least one full poll.
403 # gets to perform at least one full poll.
406 stop_time = time.time() + timeout
404 stop_time = time.time() + timeout
407 for i in xrange(2):
405 for i in xrange(2):
408 self._flushed = False
406 self._flushed = False
409 self.ioloop.add_callback(self._flush)
407 self.ioloop.add_callback(self._flush)
410 while not self._flushed and time.time() < stop_time:
408 while not self._flushed and time.time() < stop_time:
411 time.sleep(0.01)
409 time.sleep(0.01)
412
410
413 def _handle_events(self, socket, events):
411 def _handle_events(self, socket, events):
414 # Turn on and off POLLOUT depending on if we have made a request
412 # Turn on and off POLLOUT depending on if we have made a request
415 if events & POLLERR:
413 if events & POLLERR:
416 self._handle_err()
414 self._handle_err()
417 if events & POLLIN:
415 if events & POLLIN:
418 self._handle_recv()
416 self._handle_recv()
419
417
420 def _handle_err(self):
418 def _handle_err(self):
421 # We don't want to let this go silently, so eventually we should log.
419 # We don't want to let this go silently, so eventually we should log.
422 raise zmq.ZMQError()
420 raise zmq.ZMQError()
423
421
424 def _handle_recv(self):
422 def _handle_recv(self):
425 # Get all of the messages we can
423 # Get all of the messages we can
426 while True:
424 while True:
427 try:
425 try:
428 ident,msg = self.session.recv(self.socket)
426 ident,msg = self.session.recv(self.socket)
429 except zmq.ZMQError:
427 except zmq.ZMQError:
430 # Check the errno?
428 # Check the errno?
431 # Will this trigger POLLERR?
429 # Will this trigger POLLERR?
432 break
430 break
433 else:
431 else:
434 if msg is None:
432 if msg is None:
435 break
433 break
436 self.call_handlers(msg)
434 self.call_handlers(msg)
437
435
438 def _flush(self):
436 def _flush(self):
439 """Callback for :method:`self.flush`."""
437 """Callback for :method:`self.flush`."""
440 self._flushed = True
438 self._flushed = True
441
439
442
440
443 class RepSocketChannel(ZmqSocketChannel):
441 class RepSocketChannel(ZmqSocketChannel):
444 """A reply channel to handle raw_input requests that the kernel makes."""
442 """A reply channel to handle raw_input requests that the kernel makes."""
445
443
446 msg_queue = None
444 msg_queue = None
447
445
448 def __init__(self, context, session, address):
446 def __init__(self, context, session, address):
449 super(RepSocketChannel, self).__init__(context, session, address)
447 super(RepSocketChannel, self).__init__(context, session, address)
450 self.ioloop = ioloop.IOLoop()
448 self.ioloop = ioloop.IOLoop()
451 self.msg_queue = Queue()
449 self.msg_queue = Queue()
452
450
453 def run(self):
451 def run(self):
454 """The thread's main activity. Call start() instead."""
452 """The thread's main activity. Call start() instead."""
455 self.socket = self.context.socket(zmq.XREQ)
453 self.socket = self.context.socket(zmq.XREQ)
456 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
454 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
457 self.socket.connect('tcp://%s:%i' % self.address)
455 self.socket.connect('tcp://%s:%i' % self.address)
458 self.iostate = POLLERR|POLLIN
456 self.iostate = POLLERR|POLLIN
459 self.ioloop.add_handler(self.socket, self._handle_events,
457 self.ioloop.add_handler(self.socket, self._handle_events,
460 self.iostate)
458 self.iostate)
461 self.ioloop.start()
459 self.ioloop.start()
462
460
463 def stop(self):
461 def stop(self):
464 self.ioloop.stop()
462 self.ioloop.stop()
465 super(RepSocketChannel, self).stop()
463 super(RepSocketChannel, self).stop()
466
464
467 def call_handlers(self, msg):
465 def call_handlers(self, msg):
468 """This method is called in the ioloop thread when a message arrives.
466 """This method is called in the ioloop thread when a message arrives.
469
467
470 Subclasses should override this method to handle incoming messages.
468 Subclasses should override this method to handle incoming messages.
471 It is important to remember that this method is called in the thread
469 It is important to remember that this method is called in the thread
472 so that some logic must be done to ensure that the application leve
470 so that some logic must be done to ensure that the application leve
473 handlers are called in the application thread.
471 handlers are called in the application thread.
474 """
472 """
475 raise NotImplementedError('call_handlers must be defined in a subclass.')
473 raise NotImplementedError('call_handlers must be defined in a subclass.')
476
474
477 def input(self, string):
475 def input(self, string):
478 """Send a string of raw input to the kernel."""
476 """Send a string of raw input to the kernel."""
479 content = dict(value=string)
477 content = dict(value=string)
480 msg = self.session.msg('input_reply', content)
478 msg = self.session.msg('input_reply', content)
481 self._queue_reply(msg)
479 self._queue_reply(msg)
482
480
483 def _handle_events(self, socket, events):
481 def _handle_events(self, socket, events):
484 if events & POLLERR:
482 if events & POLLERR:
485 self._handle_err()
483 self._handle_err()
486 if events & POLLOUT:
484 if events & POLLOUT:
487 self._handle_send()
485 self._handle_send()
488 if events & POLLIN:
486 if events & POLLIN:
489 self._handle_recv()
487 self._handle_recv()
490
488
491 def _handle_recv(self):
489 def _handle_recv(self):
492 ident,msg = self.session.recv(self.socket, 0)
490 ident,msg = self.session.recv(self.socket, 0)
493 self.call_handlers(msg)
491 self.call_handlers(msg)
494
492
495 def _handle_send(self):
493 def _handle_send(self):
496 try:
494 try:
497 msg = self.msg_queue.get(False)
495 msg = self.msg_queue.get(False)
498 except Empty:
496 except Empty:
499 pass
497 pass
500 else:
498 else:
501 self.session.send(self.socket,msg)
499 self.session.send(self.socket,msg)
502 if self.msg_queue.empty():
500 if self.msg_queue.empty():
503 self.drop_io_state(POLLOUT)
501 self.drop_io_state(POLLOUT)
504
502
505 def _handle_err(self):
503 def _handle_err(self):
506 # We don't want to let this go silently, so eventually we should log.
504 # We don't want to let this go silently, so eventually we should log.
507 raise zmq.ZMQError()
505 raise zmq.ZMQError()
508
506
509 def _queue_reply(self, msg):
507 def _queue_reply(self, msg):
510 self.msg_queue.put(msg)
508 self.msg_queue.put(msg)
511 self.add_io_state(POLLOUT)
509 self.add_io_state(POLLOUT)
512
510
513
511
514 class HBSocketChannel(ZmqSocketChannel):
512 class HBSocketChannel(ZmqSocketChannel):
515 """The heartbeat channel which monitors the kernel heartbeat.
513 """The heartbeat channel which monitors the kernel heartbeat.
516
514
517 Note that the heartbeat channel is paused by default. As long as you start
515 Note that the heartbeat channel is paused by default. As long as you start
518 this channel, the kernel manager will ensure that it is paused and un-paused
516 this channel, the kernel manager will ensure that it is paused and un-paused
519 as appropriate.
517 as appropriate.
520 """
518 """
521
519
522 time_to_dead = 3.0
520 time_to_dead = 3.0
523 socket = None
521 socket = None
524 poller = None
522 poller = None
525 _running = None
523 _running = None
526 _pause = None
524 _pause = None
527
525
528 def __init__(self, context, session, address):
526 def __init__(self, context, session, address):
529 super(HBSocketChannel, self).__init__(context, session, address)
527 super(HBSocketChannel, self).__init__(context, session, address)
530 self._running = False
528 self._running = False
531 self._pause = True
529 self._pause = True
532
530
533 def _create_socket(self):
531 def _create_socket(self):
534 self.socket = self.context.socket(zmq.REQ)
532 self.socket = self.context.socket(zmq.REQ)
535 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
533 self.socket.setsockopt(zmq.IDENTITY, self.session.session)
536 self.socket.connect('tcp://%s:%i' % self.address)
534 self.socket.connect('tcp://%s:%i' % self.address)
537 self.poller = zmq.Poller()
535 self.poller = zmq.Poller()
538 self.poller.register(self.socket, zmq.POLLIN)
536 self.poller.register(self.socket, zmq.POLLIN)
539
537
540 def run(self):
538 def run(self):
541 """The thread's main activity. Call start() instead."""
539 """The thread's main activity. Call start() instead."""
542 self._create_socket()
540 self._create_socket()
543 self._running = True
541 self._running = True
544 while self._running:
542 while self._running:
545 if self._pause:
543 if self._pause:
546 time.sleep(self.time_to_dead)
544 time.sleep(self.time_to_dead)
547 else:
545 else:
548 since_last_heartbeat = 0.0
546 since_last_heartbeat = 0.0
549 request_time = time.time()
547 request_time = time.time()
550 try:
548 try:
551 #io.rprint('Ping from HB channel') # dbg
549 #io.rprint('Ping from HB channel') # dbg
552 self.socket.send(b'ping')
550 self.socket.send(b'ping')
553 except zmq.ZMQError, e:
551 except zmq.ZMQError, e:
554 #io.rprint('*** HB Error:', e) # dbg
552 #io.rprint('*** HB Error:', e) # dbg
555 if e.errno == zmq.EFSM:
553 if e.errno == zmq.EFSM:
556 #io.rprint('sleep...', self.time_to_dead) # dbg
554 #io.rprint('sleep...', self.time_to_dead) # dbg
557 time.sleep(self.time_to_dead)
555 time.sleep(self.time_to_dead)
558 self._create_socket()
556 self._create_socket()
559 else:
557 else:
560 raise
558 raise
561 else:
559 else:
562 while True:
560 while True:
563 try:
561 try:
564 self.socket.recv(zmq.NOBLOCK)
562 self.socket.recv(zmq.NOBLOCK)
565 except zmq.ZMQError, e:
563 except zmq.ZMQError, e:
566 #io.rprint('*** HB Error 2:', e) # dbg
564 #io.rprint('*** HB Error 2:', e) # dbg
567 if e.errno == zmq.EAGAIN:
565 if e.errno == zmq.EAGAIN:
568 before_poll = time.time()
566 before_poll = time.time()
569 until_dead = self.time_to_dead - (before_poll -
567 until_dead = self.time_to_dead - (before_poll -
570 request_time)
568 request_time)
571
569
572 # When the return value of poll() is an empty
570 # When the return value of poll() is an empty
573 # list, that is when things have gone wrong
571 # list, that is when things have gone wrong
574 # (zeromq bug). As long as it is not an empty
572 # (zeromq bug). As long as it is not an empty
575 # list, poll is working correctly even if it
573 # list, poll is working correctly even if it
576 # returns quickly. Note: poll timeout is in
574 # returns quickly. Note: poll timeout is in
577 # milliseconds.
575 # milliseconds.
578 self.poller.poll(1000*until_dead)
576 self.poller.poll(1000*until_dead)
579
577
580 since_last_heartbeat = time.time()-request_time
578 since_last_heartbeat = time.time()-request_time
581 if since_last_heartbeat > self.time_to_dead:
579 if since_last_heartbeat > self.time_to_dead:
582 self.call_handlers(since_last_heartbeat)
580 self.call_handlers(since_last_heartbeat)
583 break
581 break
584 else:
582 else:
585 # FIXME: We should probably log this instead.
583 # FIXME: We should probably log this instead.
586 raise
584 raise
587 else:
585 else:
588 until_dead = self.time_to_dead - (time.time() -
586 until_dead = self.time_to_dead - (time.time() -
589 request_time)
587 request_time)
590 if until_dead > 0.0:
588 if until_dead > 0.0:
591 #io.rprint('sleep...', self.time_to_dead) # dbg
589 #io.rprint('sleep...', self.time_to_dead) # dbg
592 time.sleep(until_dead)
590 time.sleep(until_dead)
593 break
591 break
594
592
595 def pause(self):
593 def pause(self):
596 """Pause the heartbeat."""
594 """Pause the heartbeat."""
597 self._pause = True
595 self._pause = True
598
596
599 def unpause(self):
597 def unpause(self):
600 """Unpause the heartbeat."""
598 """Unpause the heartbeat."""
601 self._pause = False
599 self._pause = False
602
600
603 def is_beating(self):
601 def is_beating(self):
604 """Is the heartbeat running and not paused."""
602 """Is the heartbeat running and not paused."""
605 if self.is_alive() and not self._pause:
603 if self.is_alive() and not self._pause:
606 return True
604 return True
607 else:
605 else:
608 return False
606 return False
609
607
610 def stop(self):
608 def stop(self):
611 self._running = False
609 self._running = False
612 super(HBSocketChannel, self).stop()
610 super(HBSocketChannel, self).stop()
613
611
614 def call_handlers(self, since_last_heartbeat):
612 def call_handlers(self, since_last_heartbeat):
615 """This method is called in the ioloop thread when a message arrives.
613 """This method is called in the ioloop thread when a message arrives.
616
614
617 Subclasses should override this method to handle incoming messages.
615 Subclasses should override this method to handle incoming messages.
618 It is important to remember that this method is called in the thread
616 It is important to remember that this method is called in the thread
619 so that some logic must be done to ensure that the application leve
617 so that some logic must be done to ensure that the application leve
620 handlers are called in the application thread.
618 handlers are called in the application thread.
621 """
619 """
622 raise NotImplementedError('call_handlers must be defined in a subclass.')
620 raise NotImplementedError('call_handlers must be defined in a subclass.')
623
621
624
622
625 #-----------------------------------------------------------------------------
623 #-----------------------------------------------------------------------------
626 # Main kernel manager class
624 # Main kernel manager class
627 #-----------------------------------------------------------------------------
625 #-----------------------------------------------------------------------------
628
626
629 class KernelManager(HasTraits):
627 class KernelManager(HasTraits):
630 """ Manages a kernel for a frontend.
628 """ Manages a kernel for a frontend.
631
629
632 The SUB channel is for the frontend to receive messages published by the
630 The SUB channel is for the frontend to receive messages published by the
633 kernel.
631 kernel.
634
632
635 The REQ channel is for the frontend to make requests of the kernel.
633 The REQ channel is for the frontend to make requests of the kernel.
636
634
637 The REP channel is for the kernel to request stdin (raw_input) from the
635 The REP channel is for the kernel to request stdin (raw_input) from the
638 frontend.
636 frontend.
639 """
637 """
640 # The PyZMQ Context to use for communication with the kernel.
638 # The PyZMQ Context to use for communication with the kernel.
641 context = Instance(zmq.Context,(),{})
639 context = Instance(zmq.Context,(),{})
642
640
643 # The Session to use for communication with the kernel.
641 # The Session to use for communication with the kernel.
644 session = Instance(Session,(),{})
642 session = Instance(Session,(),{})
645
643
646 # The kernel process with which the KernelManager is communicating.
644 # The kernel process with which the KernelManager is communicating.
647 kernel = Instance(Popen)
645 kernel = Instance(Popen)
648
646
649 # The addresses for the communication channels.
647 # The addresses for the communication channels.
650 xreq_address = TCPAddress((LOCALHOST, 0))
648 xreq_address = TCPAddress((LOCALHOST, 0))
651 sub_address = TCPAddress((LOCALHOST, 0))
649 sub_address = TCPAddress((LOCALHOST, 0))
652 rep_address = TCPAddress((LOCALHOST, 0))
650 rep_address = TCPAddress((LOCALHOST, 0))
653 hb_address = TCPAddress((LOCALHOST, 0))
651 hb_address = TCPAddress((LOCALHOST, 0))
654
652
655 # The classes to use for the various channels.
653 # The classes to use for the various channels.
656 xreq_channel_class = Type(XReqSocketChannel)
654 xreq_channel_class = Type(XReqSocketChannel)
657 sub_channel_class = Type(SubSocketChannel)
655 sub_channel_class = Type(SubSocketChannel)
658 rep_channel_class = Type(RepSocketChannel)
656 rep_channel_class = Type(RepSocketChannel)
659 hb_channel_class = Type(HBSocketChannel)
657 hb_channel_class = Type(HBSocketChannel)
660
658
661 # Protected traits.
659 # Protected traits.
662 _launch_args = Any
660 _launch_args = Any
663 _xreq_channel = Any
661 _xreq_channel = Any
664 _sub_channel = Any
662 _sub_channel = Any
665 _rep_channel = Any
663 _rep_channel = Any
666 _hb_channel = Any
664 _hb_channel = Any
667
665
668 def __init__(self, **kwargs):
666 def __init__(self, **kwargs):
669 super(KernelManager, self).__init__(**kwargs)
667 super(KernelManager, self).__init__(**kwargs)
670 # Uncomment this to try closing the context.
668 # Uncomment this to try closing the context.
671 # atexit.register(self.context.close)
669 # atexit.register(self.context.close)
672
670
673 #--------------------------------------------------------------------------
671 #--------------------------------------------------------------------------
674 # Channel management methods:
672 # Channel management methods:
675 #--------------------------------------------------------------------------
673 #--------------------------------------------------------------------------
676
674
677 def start_channels(self, xreq=True, sub=True, rep=True, hb=True):
675 def start_channels(self, xreq=True, sub=True, rep=True, hb=True):
678 """Starts the channels for this kernel.
676 """Starts the channels for this kernel.
679
677
680 This will create the channels if they do not exist and then start
678 This will create the channels if they do not exist and then start
681 them. If port numbers of 0 are being used (random ports) then you
679 them. If port numbers of 0 are being used (random ports) then you
682 must first call :method:`start_kernel`. If the channels have been
680 must first call :method:`start_kernel`. If the channels have been
683 stopped and you call this, :class:`RuntimeError` will be raised.
681 stopped and you call this, :class:`RuntimeError` will be raised.
684 """
682 """
685 if xreq:
683 if xreq:
686 self.xreq_channel.start()
684 self.xreq_channel.start()
687 if sub:
685 if sub:
688 self.sub_channel.start()
686 self.sub_channel.start()
689 if rep:
687 if rep:
690 self.rep_channel.start()
688 self.rep_channel.start()
691 if hb:
689 if hb:
692 self.hb_channel.start()
690 self.hb_channel.start()
693
691
694 def stop_channels(self):
692 def stop_channels(self):
695 """Stops all the running channels for this kernel.
693 """Stops all the running channels for this kernel.
696 """
694 """
697 if self.xreq_channel.is_alive():
695 if self.xreq_channel.is_alive():
698 self.xreq_channel.stop()
696 self.xreq_channel.stop()
699 if self.sub_channel.is_alive():
697 if self.sub_channel.is_alive():
700 self.sub_channel.stop()
698 self.sub_channel.stop()
701 if self.rep_channel.is_alive():
699 if self.rep_channel.is_alive():
702 self.rep_channel.stop()
700 self.rep_channel.stop()
703 if self.hb_channel.is_alive():
701 if self.hb_channel.is_alive():
704 self.hb_channel.stop()
702 self.hb_channel.stop()
705
703
706 @property
704 @property
707 def channels_running(self):
705 def channels_running(self):
708 """Are any of the channels created and running?"""
706 """Are any of the channels created and running?"""
709 return (self.xreq_channel.is_alive() or self.sub_channel.is_alive() or
707 return (self.xreq_channel.is_alive() or self.sub_channel.is_alive() or
710 self.rep_channel.is_alive() or self.hb_channel.is_alive())
708 self.rep_channel.is_alive() or self.hb_channel.is_alive())
711
709
712 #--------------------------------------------------------------------------
710 #--------------------------------------------------------------------------
713 # Kernel process management methods:
711 # Kernel process management methods:
714 #--------------------------------------------------------------------------
712 #--------------------------------------------------------------------------
715
713
716 def start_kernel(self, **kw):
714 def start_kernel(self, **kw):
717 """Starts a kernel process and configures the manager to use it.
715 """Starts a kernel process and configures the manager to use it.
718
716
719 If random ports (port=0) are being used, this method must be called
717 If random ports (port=0) are being used, this method must be called
720 before the channels are created.
718 before the channels are created.
721
719
722 Parameters:
720 Parameters:
723 -----------
721 -----------
724 ipython : bool, optional (default True)
722 ipython : bool, optional (default True)
725 Whether to use an IPython kernel instead of a plain Python kernel.
723 Whether to use an IPython kernel instead of a plain Python kernel.
726 """
724 """
727 xreq, sub, rep, hb = self.xreq_address, self.sub_address, \
725 xreq, sub, rep, hb = self.xreq_address, self.sub_address, \
728 self.rep_address, self.hb_address
726 self.rep_address, self.hb_address
729 if xreq[0] not in LOCAL_IPS or sub[0] not in LOCAL_IPS or \
727 if xreq[0] not in LOCAL_IPS or sub[0] not in LOCAL_IPS or \
730 rep[0] not in LOCAL_IPS or hb[0] not in LOCAL_IPS:
728 rep[0] not in LOCAL_IPS or hb[0] not in LOCAL_IPS:
731 raise RuntimeError("Can only launch a kernel on a local interface. "
729 raise RuntimeError("Can only launch a kernel on a local interface. "
732 "Make sure that the '*_address' attributes are "
730 "Make sure that the '*_address' attributes are "
733 "configured properly. "
731 "configured properly. "
734 "Currently valid addresses are: %s"%LOCAL_IPS
732 "Currently valid addresses are: %s"%LOCAL_IPS
735 )
733 )
736
734
737 self._launch_args = kw.copy()
735 self._launch_args = kw.copy()
738 if kw.pop('ipython', True):
736 if kw.pop('ipython', True):
739 from ipkernel import launch_kernel
737 from ipkernel import launch_kernel
740 else:
738 else:
741 from pykernel import launch_kernel
739 from pykernel import launch_kernel
742 self.kernel, xrep, pub, req, _hb = launch_kernel(
740 self.kernel, xrep, pub, req, _hb = launch_kernel(
743 xrep_port=xreq[1], pub_port=sub[1],
741 xrep_port=xreq[1], pub_port=sub[1],
744 req_port=rep[1], hb_port=hb[1], **kw)
742 req_port=rep[1], hb_port=hb[1], **kw)
745 self.xreq_address = (xreq[0], xrep)
743 self.xreq_address = (xreq[0], xrep)
746 self.sub_address = (sub[0], pub)
744 self.sub_address = (sub[0], pub)
747 self.rep_address = (rep[0], req)
745 self.rep_address = (rep[0], req)
748 self.hb_address = (hb[0], _hb)
746 self.hb_address = (hb[0], _hb)
749
747
750 def shutdown_kernel(self, restart=False):
748 def shutdown_kernel(self, restart=False):
751 """ Attempts to the stop the kernel process cleanly. If the kernel
749 """ Attempts to the stop the kernel process cleanly. If the kernel
752 cannot be stopped, it is killed, if possible.
750 cannot be stopped, it is killed, if possible.
753 """
751 """
754 # FIXME: Shutdown does not work on Windows due to ZMQ errors!
752 # FIXME: Shutdown does not work on Windows due to ZMQ errors!
755 if sys.platform == 'win32':
753 if sys.platform == 'win32':
756 self.kill_kernel()
754 self.kill_kernel()
757 return
755 return
758
756
759 # Pause the heart beat channel if it exists.
757 # Pause the heart beat channel if it exists.
760 if self._hb_channel is not None:
758 if self._hb_channel is not None:
761 self._hb_channel.pause()
759 self._hb_channel.pause()
762
760
763 # Don't send any additional kernel kill messages immediately, to give
761 # Don't send any additional kernel kill messages immediately, to give
764 # the kernel a chance to properly execute shutdown actions. Wait for at
762 # the kernel a chance to properly execute shutdown actions. Wait for at
765 # most 1s, checking every 0.1s.
763 # most 1s, checking every 0.1s.
766 self.xreq_channel.shutdown(restart=restart)
764 self.xreq_channel.shutdown(restart=restart)
767 for i in range(10):
765 for i in range(10):
768 if self.is_alive:
766 if self.is_alive:
769 time.sleep(0.1)
767 time.sleep(0.1)
770 else:
768 else:
771 break
769 break
772 else:
770 else:
773 # OK, we've waited long enough.
771 # OK, we've waited long enough.
774 if self.has_kernel:
772 if self.has_kernel:
775 self.kill_kernel()
773 self.kill_kernel()
776
774
777 def restart_kernel(self, now=False):
775 def restart_kernel(self, now=False):
778 """Restarts a kernel with the same arguments that were used to launch
776 """Restarts a kernel with the same arguments that were used to launch
779 it. If the old kernel was launched with random ports, the same ports
777 it. If the old kernel was launched with random ports, the same ports
780 will be used for the new kernel.
778 will be used for the new kernel.
781
779
782 Parameters
780 Parameters
783 ----------
781 ----------
784 now : bool, optional
782 now : bool, optional
785 If True, the kernel is forcefully restarted *immediately*, without
783 If True, the kernel is forcefully restarted *immediately*, without
786 having a chance to do any cleanup action. Otherwise the kernel is
784 having a chance to do any cleanup action. Otherwise the kernel is
787 given 1s to clean up before a forceful restart is issued.
785 given 1s to clean up before a forceful restart is issued.
788
786
789 In all cases the kernel is restarted, the only difference is whether
787 In all cases the kernel is restarted, the only difference is whether
790 it is given a chance to perform a clean shutdown or not.
788 it is given a chance to perform a clean shutdown or not.
791 """
789 """
792 if self._launch_args is None:
790 if self._launch_args is None:
793 raise RuntimeError("Cannot restart the kernel. "
791 raise RuntimeError("Cannot restart the kernel. "
794 "No previous call to 'start_kernel'.")
792 "No previous call to 'start_kernel'.")
795 else:
793 else:
796 if self.has_kernel:
794 if self.has_kernel:
797 if now:
795 if now:
798 self.kill_kernel()
796 self.kill_kernel()
799 else:
797 else:
800 self.shutdown_kernel(restart=True)
798 self.shutdown_kernel(restart=True)
801 self.start_kernel(**self._launch_args)
799 self.start_kernel(**self._launch_args)
802
800
803 # FIXME: Messages get dropped in Windows due to probable ZMQ bug
801 # FIXME: Messages get dropped in Windows due to probable ZMQ bug
804 # unless there is some delay here.
802 # unless there is some delay here.
805 if sys.platform == 'win32':
803 if sys.platform == 'win32':
806 time.sleep(0.2)
804 time.sleep(0.2)
807
805
808 @property
806 @property
809 def has_kernel(self):
807 def has_kernel(self):
810 """Returns whether a kernel process has been specified for the kernel
808 """Returns whether a kernel process has been specified for the kernel
811 manager.
809 manager.
812 """
810 """
813 return self.kernel is not None
811 return self.kernel is not None
814
812
815 def kill_kernel(self):
813 def kill_kernel(self):
816 """ Kill the running kernel. """
814 """ Kill the running kernel. """
817 if self.has_kernel:
815 if self.has_kernel:
818 # Pause the heart beat channel if it exists.
816 # Pause the heart beat channel if it exists.
819 if self._hb_channel is not None:
817 if self._hb_channel is not None:
820 self._hb_channel.pause()
818 self._hb_channel.pause()
821
819
822 # Attempt to kill the kernel.
820 # Attempt to kill the kernel.
823 try:
821 try:
824 self.kernel.kill()
822 self.kernel.kill()
825 except OSError, e:
823 except OSError, e:
826 # In Windows, we will get an Access Denied error if the process
824 # In Windows, we will get an Access Denied error if the process
827 # has already terminated. Ignore it.
825 # has already terminated. Ignore it.
828 if not (sys.platform == 'win32' and e.winerror == 5):
826 if not (sys.platform == 'win32' and e.winerror == 5):
829 raise
827 raise
830 self.kernel = None
828 self.kernel = None
831 else:
829 else:
832 raise RuntimeError("Cannot kill kernel. No kernel is running!")
830 raise RuntimeError("Cannot kill kernel. No kernel is running!")
833
831
834 def interrupt_kernel(self):
832 def interrupt_kernel(self):
835 """ Interrupts the kernel. Unlike ``signal_kernel``, this operation is
833 """ Interrupts the kernel. Unlike ``signal_kernel``, this operation is
836 well supported on all platforms.
834 well supported on all platforms.
837 """
835 """
838 if self.has_kernel:
836 if self.has_kernel:
839 if sys.platform == 'win32':
837 if sys.platform == 'win32':
840 from parentpoller import ParentPollerWindows as Poller
838 from parentpoller import ParentPollerWindows as Poller
841 Poller.send_interrupt(self.kernel.win32_interrupt_event)
839 Poller.send_interrupt(self.kernel.win32_interrupt_event)
842 else:
840 else:
843 self.kernel.send_signal(signal.SIGINT)
841 self.kernel.send_signal(signal.SIGINT)
844 else:
842 else:
845 raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
843 raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
846
844
847 def signal_kernel(self, signum):
845 def signal_kernel(self, signum):
848 """ Sends a signal to the kernel. Note that since only SIGTERM is
846 """ Sends a signal to the kernel. Note that since only SIGTERM is
849 supported on Windows, this function is only useful on Unix systems.
847 supported on Windows, this function is only useful on Unix systems.
850 """
848 """
851 if self.has_kernel:
849 if self.has_kernel:
852 self.kernel.send_signal(signum)
850 self.kernel.send_signal(signum)
853 else:
851 else:
854 raise RuntimeError("Cannot signal kernel. No kernel is running!")
852 raise RuntimeError("Cannot signal kernel. No kernel is running!")
855
853
856 @property
854 @property
857 def is_alive(self):
855 def is_alive(self):
858 """Is the kernel process still running?"""
856 """Is the kernel process still running?"""
859 # FIXME: not using a heartbeat means this method is broken for any
857 # FIXME: not using a heartbeat means this method is broken for any
860 # remote kernel, it's only capable of handling local kernels.
858 # remote kernel, it's only capable of handling local kernels.
861 if self.has_kernel:
859 if self.has_kernel:
862 if self.kernel.poll() is None:
860 if self.kernel.poll() is None:
863 return True
861 return True
864 else:
862 else:
865 return False
863 return False
866 else:
864 else:
867 # We didn't start the kernel with this KernelManager so we don't
865 # We didn't start the kernel with this KernelManager so we don't
868 # know if it is running. We should use a heartbeat for this case.
866 # know if it is running. We should use a heartbeat for this case.
869 return True
867 return True
870
868
871 #--------------------------------------------------------------------------
869 #--------------------------------------------------------------------------
872 # Channels used for communication with the kernel:
870 # Channels used for communication with the kernel:
873 #--------------------------------------------------------------------------
871 #--------------------------------------------------------------------------
874
872
875 @property
873 @property
876 def xreq_channel(self):
874 def xreq_channel(self):
877 """Get the REQ socket channel object to make requests of the kernel."""
875 """Get the REQ socket channel object to make requests of the kernel."""
878 if self._xreq_channel is None:
876 if self._xreq_channel is None:
879 self._xreq_channel = self.xreq_channel_class(self.context,
877 self._xreq_channel = self.xreq_channel_class(self.context,
880 self.session,
878 self.session,
881 self.xreq_address)
879 self.xreq_address)
882 return self._xreq_channel
880 return self._xreq_channel
883
881
884 @property
882 @property
885 def sub_channel(self):
883 def sub_channel(self):
886 """Get the SUB socket channel object."""
884 """Get the SUB socket channel object."""
887 if self._sub_channel is None:
885 if self._sub_channel is None:
888 self._sub_channel = self.sub_channel_class(self.context,
886 self._sub_channel = self.sub_channel_class(self.context,
889 self.session,
887 self.session,
890 self.sub_address)
888 self.sub_address)
891 return self._sub_channel
889 return self._sub_channel
892
890
893 @property
891 @property
894 def rep_channel(self):
892 def rep_channel(self):
895 """Get the REP socket channel object to handle stdin (raw_input)."""
893 """Get the REP socket channel object to handle stdin (raw_input)."""
896 if self._rep_channel is None:
894 if self._rep_channel is None:
897 self._rep_channel = self.rep_channel_class(self.context,
895 self._rep_channel = self.rep_channel_class(self.context,
898 self.session,
896 self.session,
899 self.rep_address)
897 self.rep_address)
900 return self._rep_channel
898 return self._rep_channel
901
899
902 @property
900 @property
903 def hb_channel(self):
901 def hb_channel(self):
904 """Get the heartbeat socket channel object to check that the
902 """Get the heartbeat socket channel object to check that the
905 kernel is alive."""
903 kernel is alive."""
906 if self._hb_channel is None:
904 if self._hb_channel is None:
907 self._hb_channel = self.hb_channel_class(self.context,
905 self._hb_channel = self.hb_channel_class(self.context,
908 self.session,
906 self.session,
909 self.hb_address)
907 self.hb_address)
910 return self._hb_channel
908 return self._hb_channel
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now