##// END OF EJS Templates
Refactor multiline input and prompt management.
Fernando Perez -
Show More
1 NO CONTENT: modified file chmod 100644 => 100755
@@ -1,288 +1,297 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 Authors:
5 5
6 6 * Fernando Perez
7 7 * Brian Granger
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2008-2010 The IPython Development Team
12 12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import __builtin__
23 23 from pprint import PrettyPrinter
24 24 pformat = PrettyPrinter().pformat
25 25
26 26 from IPython.config.configurable import Configurable
27 27 from IPython.core import prompts
28 28 import IPython.utils.generics
29 29 import IPython.utils.io
30 30 from IPython.utils.traitlets import Instance, Int
31 31 from IPython.utils.warn import warn
32 32
33 33 #-----------------------------------------------------------------------------
34 34 # Main displayhook class
35 35 #-----------------------------------------------------------------------------
36 36
37 37 # TODO: The DisplayHook class should be split into two classes, one that
38 38 # manages the prompts and their synchronization and another that just does the
39 39 # displayhook logic and calls into the prompt manager.
40 40
41 41 # TODO: Move the various attributes (cache_size, colors, input_sep,
42 42 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
43 43 # attributes of InteractiveShell. They should be on ONE object only and the
44 44 # other objects should ask that one object for their values.
45 45
46 46 class DisplayHook(Configurable):
47 47 """The custom IPython displayhook to replace sys.displayhook.
48 48
49 49 This class does many things, but the basic idea is that it is a callable
50 50 that gets called anytime user code returns a value.
51 51
52 52 Currently this class does more than just the displayhook logic and that
53 53 extra logic should eventually be moved out of here.
54 54 """
55 55
56 56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
57
57 58 # Each call to the In[] prompt raises it by 1, even the first.
58 prompt_count = Int(0)
59 #prompt_count = Int(0)
59 60
60 61 def __init__(self, shell=None, cache_size=1000,
61 62 colors='NoColor', input_sep='\n',
62 63 output_sep='\n', output_sep2='',
63 64 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
64 65 config=None):
65 66 super(DisplayHook, self).__init__(shell=shell, config=config)
66 67
67 68 cache_size_min = 3
68 69 if cache_size <= 0:
69 70 self.do_full_cache = 0
70 71 cache_size = 0
71 72 elif cache_size < cache_size_min:
72 73 self.do_full_cache = 0
73 74 cache_size = 0
74 75 warn('caching was disabled (min value for cache size is %s).' %
75 76 cache_size_min,level=3)
76 77 else:
77 78 self.do_full_cache = 1
78 79
79 80 self.cache_size = cache_size
80 81 self.input_sep = input_sep
81 82
82 83 # we need a reference to the user-level namespace
83 84 self.shell = shell
84 85
85 86 # Set input prompt strings and colors
86 87 if cache_size == 0:
87 88 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
88 89 or ps1.find(r'\N') > -1:
89 90 ps1 = '>>> '
90 91 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
91 92 or ps2.find(r'\N') > -1:
92 93 ps2 = '... '
93 94 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
94 95 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
95 96 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
96 97
97 98 self.color_table = prompts.PromptColors
98 99 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
99 100 pad_left=pad_left)
100 101 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
101 102 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
102 103 pad_left=pad_left)
103 104 self.set_colors(colors)
104 105
105 106 # Store the last prompt string each time, we need it for aligning
106 107 # continuation and auto-rewrite prompts
107 108 self.last_prompt = ''
108 109 self.output_sep = output_sep
109 110 self.output_sep2 = output_sep2
110 111 self._,self.__,self.___ = '','',''
111 112 self.pprint_types = map(type,[(),[],{}])
112 113
113 114 # these are deliberately global:
114 115 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
115 116 self.shell.user_ns.update(to_user_ns)
116 117
118 @property
119 def prompt_count(self):
120 return self.shell.execution_count
121
122 @prompt_count.setter
123 def _set_prompt_count(self, val):
124 raise ValueError('prompt count is read only')
125
117 126 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
118 127 if p_str is None:
119 128 if self.do_full_cache:
120 129 return cache_def
121 130 else:
122 131 return no_cache_def
123 132 else:
124 133 return p_str
125 134
126 135 def set_colors(self, colors):
127 136 """Set the active color scheme and configure colors for the three
128 137 prompt subsystems."""
129 138
130 139 # FIXME: This modifying of the global prompts.prompt_specials needs
131 140 # to be fixed. We need to refactor all of the prompts stuff to use
132 141 # proper configuration and traits notifications.
133 142 if colors.lower()=='nocolor':
134 143 prompts.prompt_specials = prompts.prompt_specials_nocolor
135 144 else:
136 145 prompts.prompt_specials = prompts.prompt_specials_color
137 146
138 147 self.color_table.set_active_scheme(colors)
139 148 self.prompt1.set_colors()
140 149 self.prompt2.set_colors()
141 150 self.prompt_out.set_colors()
142 151
143 152 #-------------------------------------------------------------------------
144 153 # Methods used in __call__. Override these methods to modify the behavior
145 154 # of the displayhook.
146 155 #-------------------------------------------------------------------------
147 156
148 157 def check_for_underscore(self):
149 158 """Check if the user has set the '_' variable by hand."""
150 159 # If something injected a '_' variable in __builtin__, delete
151 160 # ipython's automatic one so we don't clobber that. gettext() in
152 161 # particular uses _, so we need to stay away from it.
153 162 if '_' in __builtin__.__dict__:
154 163 try:
155 164 del self.shell.user_ns['_']
156 165 except KeyError:
157 166 pass
158 167
159 168 def quiet(self):
160 169 """Should we silence the display hook because of ';'?"""
161 170 # do not print output if input ends in ';'
162 171 try:
163 172 if self.shell.input_hist[self.prompt_count].endswith(';\n'):
164 173 return True
165 174 except IndexError:
166 175 # some uses of ipshellembed may fail here
167 176 pass
168 177 return False
169 178
170 179 def start_displayhook(self):
171 180 """Start the displayhook, initializing resources."""
172 181 pass
173 182
174 183 def write_output_prompt(self):
175 184 """Write the output prompt."""
176 185 # Use write, not print which adds an extra space.
177 186 IPython.utils.io.Term.cout.write(self.output_sep)
178 187 outprompt = str(self.prompt_out)
179 188 if self.do_full_cache:
180 189 IPython.utils.io.Term.cout.write(outprompt)
181 190
182 191 # TODO: Make this method an extension point. The previous implementation
183 192 # has both a result_display hook as well as a result_display generic
184 193 # function to customize the repr on a per class basis. We need to rethink
185 194 # the hooks mechanism before doing this though.
186 195 def compute_result_repr(self, result):
187 196 """Compute and return the repr of the object to be displayed.
188 197
189 198 This method only compute the string form of the repr and should NOT
190 199 actual print or write that to a stream. This method may also transform
191 200 the result itself, but the default implementation passes the original
192 201 through.
193 202 """
194 203 try:
195 204 if self.shell.pprint:
196 205 result_repr = pformat(result)
197 206 if '\n' in result_repr:
198 207 # So that multi-line strings line up with the left column of
199 208 # the screen, instead of having the output prompt mess up
200 209 # their first line.
201 210 result_repr = '\n' + result_repr
202 211 else:
203 212 result_repr = repr(result)
204 213 except TypeError:
205 214 # This happens when result.__repr__ doesn't return a string,
206 215 # such as when it returns None.
207 216 result_repr = '\n'
208 217 return result, result_repr
209 218
210 219 def write_result_repr(self, result_repr):
211 220 # We want to print because we want to always make sure we have a
212 221 # newline, even if all the prompt separators are ''. This is the
213 222 # standard IPython behavior.
214 223 print >>IPython.utils.io.Term.cout, result_repr
215 224
216 225 def update_user_ns(self, result):
217 226 """Update user_ns with various things like _, __, _1, etc."""
218 227
219 228 # Avoid recursive reference when displaying _oh/Out
220 229 if result is not self.shell.user_ns['_oh']:
221 230 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
222 231 warn('Output cache limit (currently '+
223 232 `self.cache_size`+' entries) hit.\n'
224 233 'Flushing cache and resetting history counter...\n'
225 234 'The only history variables available will be _,__,___ and _1\n'
226 235 'with the current result.')
227 236
228 237 self.flush()
229 238 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
230 239 # we cause buggy behavior for things like gettext).
231 240 if '_' not in __builtin__.__dict__:
232 241 self.___ = self.__
233 242 self.__ = self._
234 243 self._ = result
235 244 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
236 245
237 246 # hackish access to top-level namespace to create _1,_2... dynamically
238 247 to_main = {}
239 248 if self.do_full_cache:
240 249 new_result = '_'+`self.prompt_count`
241 250 to_main[new_result] = result
242 251 self.shell.user_ns.update(to_main)
243 252 self.shell.user_ns['_oh'][self.prompt_count] = result
244 253
245 254 def log_output(self, result):
246 255 """Log the output."""
247 256 if self.shell.logger.log_output:
248 257 self.shell.logger.log_write(repr(result),'output')
249 258
250 259 def finish_displayhook(self):
251 260 """Finish up all displayhook activities."""
252 261 IPython.utils.io.Term.cout.write(self.output_sep2)
253 262 IPython.utils.io.Term.cout.flush()
254 263
255 264 def __call__(self, result=None):
256 265 """Printing with history cache management.
257 266
258 267 This is invoked everytime the interpreter needs to print, and is
259 268 activated by setting the variable sys.displayhook to it.
260 269 """
261 270 self.check_for_underscore()
262 271 if result is not None and not self.quiet():
263 272 self.start_displayhook()
264 273 self.write_output_prompt()
265 274 result, result_repr = self.compute_result_repr(result)
266 275 self.write_result_repr(result_repr)
267 276 self.update_user_ns(result)
268 277 self.log_output(result)
269 278 self.finish_displayhook()
270 279
271 280 def flush(self):
272 281 if not self.do_full_cache:
273 282 raise ValueError,"You shouldn't have reached the cache flush "\
274 283 "if full caching is not enabled!"
275 284 # delete auto-generated vars from global namespace
276 285
277 286 for n in range(1,self.prompt_count + 1):
278 287 key = '_'+`n`
279 288 try:
280 289 del self.shell.user_ns[key]
281 290 except: pass
282 291 self.shell.user_ns['_oh'].clear()
283 292
284 293 if '_' not in __builtin__.__dict__:
285 294 self.shell.user_ns.update({'_':None,'__':None, '___':None})
286 295 import gc
287 296 gc.collect() # xxx needed?
288 297
@@ -1,2586 +1,2619 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.display_trap import DisplayTrap
44 44 from IPython.core.displayhook import DisplayHook
45 45 from IPython.core.error import TryNext, UsageError
46 46 from IPython.core.extensions import ExtensionManager
47 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 48 from IPython.core.inputlist import InputList
49 49 from IPython.core.inputsplitter import IPythonInputSplitter
50 50 from IPython.core.logger import Logger
51 51 from IPython.core.magic import Magic
52 52 from IPython.core.payload import PayloadManager
53 53 from IPython.core.plugin import PluginManager
54 54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 55 from IPython.external.Itpl import ItplNS
56 56 from IPython.utils import PyColorize
57 57 from IPython.utils import io
58 58 from IPython.utils import pickleshare
59 59 from IPython.utils.doctestreload import doctest_reload
60 60 from IPython.utils.io import ask_yes_no, rprint
61 61 from IPython.utils.ipstruct import Struct
62 62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 63 from IPython.utils.process import system, getoutput
64 64 from IPython.utils.strdispatch import StrDispatch
65 65 from IPython.utils.syspathcontext import prepended_to_syspath
66 66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
67 67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 68 List, Unicode, Instance, Type)
69 69 from IPython.utils.warn import warn, error, fatal
70 70 import IPython.core.hooks
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Globals
74 74 #-----------------------------------------------------------------------------
75 75
76 76 # compiled regexps for autoindent management
77 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 78
79 79 #-----------------------------------------------------------------------------
80 80 # Utilities
81 81 #-----------------------------------------------------------------------------
82 82
83 83 # store the builtin raw_input globally, and use this always, in case user code
84 84 # overwrites it (like wx.py.PyShell does)
85 85 raw_input_original = raw_input
86 86
87 87 def softspace(file, newvalue):
88 88 """Copied from code.py, to remove the dependency"""
89 89
90 90 oldvalue = 0
91 91 try:
92 92 oldvalue = file.softspace
93 93 except AttributeError:
94 94 pass
95 95 try:
96 96 file.softspace = newvalue
97 97 except (AttributeError, TypeError):
98 98 # "attribute-less object" or "read-only attributes"
99 99 pass
100 100 return oldvalue
101 101
102 102
103 103 def no_op(*a, **kw): pass
104 104
105 105 class SpaceInInput(exceptions.Exception): pass
106 106
107 107 class Bunch: pass
108 108
109 109
110 110 def get_default_colors():
111 111 if sys.platform=='darwin':
112 112 return "LightBG"
113 113 elif os.name=='nt':
114 114 return 'Linux'
115 115 else:
116 116 return 'Linux'
117 117
118 118
119 119 class SeparateStr(Str):
120 120 """A Str subclass to validate separate_in, separate_out, etc.
121 121
122 122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 123 """
124 124
125 125 def validate(self, obj, value):
126 126 if value == '0': value = ''
127 127 value = value.replace('\\n','\n')
128 128 return super(SeparateStr, self).validate(obj, value)
129 129
130 130 class MultipleInstanceError(Exception):
131 131 pass
132 132
133 133
134 134 #-----------------------------------------------------------------------------
135 135 # Main IPython class
136 136 #-----------------------------------------------------------------------------
137 137
138 138
139 139 class InteractiveShell(Configurable, Magic):
140 140 """An enhanced, interactive shell for Python."""
141 141
142 142 _instance = None
143 143 autocall = Enum((0,1,2), default_value=1, config=True)
144 144 # TODO: remove all autoindent logic and put into frontends.
145 145 # We can't do this yet because even runlines uses the autoindent.
146 146 autoindent = CBool(True, config=True)
147 147 automagic = CBool(True, config=True)
148 148 cache_size = Int(1000, config=True)
149 149 color_info = CBool(True, config=True)
150 150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 151 default_value=get_default_colors(), config=True)
152 152 debug = CBool(False, config=True)
153 153 deep_reload = CBool(False, config=True)
154 154 displayhook_class = Type(DisplayHook)
155 155 exit_now = CBool(False)
156 156 filename = Str("<ipython console>")
157 157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 158
159 159 # Input splitter, to split entire cells of input into either individual
160 160 # interactive statements or whole blocks.
161 161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 162 (), {})
163 163 logstart = CBool(False, config=True)
164 164 logfile = Str('', config=True)
165 165 logappend = Str('', config=True)
166 166 object_info_string_level = Enum((0,1,2), default_value=0,
167 167 config=True)
168 168 pdb = CBool(False, config=True)
169 169
170 170 pprint = CBool(True, config=True)
171 171 profile = Str('', config=True)
172 172 prompt_in1 = Str('In [\\#]: ', config=True)
173 173 prompt_in2 = Str(' .\\D.: ', config=True)
174 174 prompt_out = Str('Out[\\#]: ', config=True)
175 175 prompts_pad_left = CBool(True, config=True)
176 176 quiet = CBool(False, config=True)
177 177
178 178 # The readline stuff will eventually be moved to the terminal subclass
179 179 # but for now, we can't do that as readline is welded in everywhere.
180 180 readline_use = CBool(True, config=True)
181 181 readline_merge_completions = CBool(True, config=True)
182 182 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
183 183 readline_remove_delims = Str('-/~', config=True)
184 184 readline_parse_and_bind = List([
185 185 'tab: complete',
186 186 '"\C-l": clear-screen',
187 187 'set show-all-if-ambiguous on',
188 188 '"\C-o": tab-insert',
189 189 '"\M-i": " "',
190 190 '"\M-o": "\d\d\d\d"',
191 191 '"\M-I": "\d\d\d\d"',
192 192 '"\C-r": reverse-search-history',
193 193 '"\C-s": forward-search-history',
194 194 '"\C-p": history-search-backward',
195 195 '"\C-n": history-search-forward',
196 196 '"\e[A": history-search-backward',
197 197 '"\e[B": history-search-forward',
198 198 '"\C-k": kill-line',
199 199 '"\C-u": unix-line-discard',
200 200 ], allow_none=False, config=True)
201 201
202 202 # TODO: this part of prompt management should be moved to the frontends.
203 203 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
204 204 separate_in = SeparateStr('\n', config=True)
205 205 separate_out = SeparateStr('', config=True)
206 206 separate_out2 = SeparateStr('', config=True)
207 207 wildcards_case_sensitive = CBool(True, config=True)
208 208 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
209 209 default_value='Context', config=True)
210 210
211 211 # Subcomponents of InteractiveShell
212 212 alias_manager = Instance('IPython.core.alias.AliasManager')
213 213 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
214 214 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
215 215 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
216 216 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 217 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 218 payload_manager = Instance('IPython.core.payload.PayloadManager')
219 219
220 220 # Private interface
221 221 _post_execute = set()
222 222
223 223 def __init__(self, config=None, ipython_dir=None,
224 224 user_ns=None, user_global_ns=None,
225 225 custom_exceptions=((), None)):
226 226
227 227 # This is where traits with a config_key argument are updated
228 228 # from the values on config.
229 229 super(InteractiveShell, self).__init__(config=config)
230 230
231 231 # These are relatively independent and stateless
232 232 self.init_ipython_dir(ipython_dir)
233 233 self.init_instance_attrs()
234 234 self.init_environment()
235 235
236 236 # Create namespaces (user_ns, user_global_ns, etc.)
237 237 self.init_create_namespaces(user_ns, user_global_ns)
238 238 # This has to be done after init_create_namespaces because it uses
239 239 # something in self.user_ns, but before init_sys_modules, which
240 240 # is the first thing to modify sys.
241 241 # TODO: When we override sys.stdout and sys.stderr before this class
242 242 # is created, we are saving the overridden ones here. Not sure if this
243 243 # is what we want to do.
244 244 self.save_sys_module_state()
245 245 self.init_sys_modules()
246 246
247 247 self.init_history()
248 248 self.init_encoding()
249 249 self.init_prefilter()
250 250
251 251 Magic.__init__(self, self)
252 252
253 253 self.init_syntax_highlighting()
254 254 self.init_hooks()
255 255 self.init_pushd_popd_magic()
256 256 # self.init_traceback_handlers use to be here, but we moved it below
257 257 # because it and init_io have to come after init_readline.
258 258 self.init_user_ns()
259 259 self.init_logger()
260 260 self.init_alias()
261 261 self.init_builtins()
262 262
263 263 # pre_config_initialization
264 264 self.init_shadow_hist()
265 265
266 266 # The next section should contain everything that was in ipmaker.
267 267 self.init_logstart()
268 268
269 269 # The following was in post_config_initialization
270 270 self.init_inspector()
271 271 # init_readline() must come before init_io(), because init_io uses
272 272 # readline related things.
273 273 self.init_readline()
274 274 # init_completer must come after init_readline, because it needs to
275 275 # know whether readline is present or not system-wide to configure the
276 276 # completers, since the completion machinery can now operate
277 277 # independently of readline (e.g. over the network)
278 278 self.init_completer()
279 279 # TODO: init_io() needs to happen before init_traceback handlers
280 280 # because the traceback handlers hardcode the stdout/stderr streams.
281 281 # This logic in in debugger.Pdb and should eventually be changed.
282 282 self.init_io()
283 283 self.init_traceback_handlers(custom_exceptions)
284 284 self.init_prompts()
285 285 self.init_displayhook()
286 286 self.init_reload_doctest()
287 287 self.init_magics()
288 288 self.init_pdb()
289 289 self.init_extension_manager()
290 290 self.init_plugin_manager()
291 291 self.init_payload()
292 292 self.hooks.late_startup_hook()
293 293 atexit.register(self.atexit_operations)
294 294
295 295 @classmethod
296 296 def instance(cls, *args, **kwargs):
297 297 """Returns a global InteractiveShell instance."""
298 298 if cls._instance is None:
299 299 inst = cls(*args, **kwargs)
300 300 # Now make sure that the instance will also be returned by
301 301 # the subclasses instance attribute.
302 302 for subclass in cls.mro():
303 303 if issubclass(cls, subclass) and \
304 304 issubclass(subclass, InteractiveShell):
305 305 subclass._instance = inst
306 306 else:
307 307 break
308 308 if isinstance(cls._instance, cls):
309 309 return cls._instance
310 310 else:
311 311 raise MultipleInstanceError(
312 312 'Multiple incompatible subclass instances of '
313 313 'InteractiveShell are being created.'
314 314 )
315 315
316 316 @classmethod
317 317 def initialized(cls):
318 318 return hasattr(cls, "_instance")
319 319
320 320 def get_ipython(self):
321 321 """Return the currently running IPython instance."""
322 322 return self
323 323
324 324 #-------------------------------------------------------------------------
325 325 # Trait changed handlers
326 326 #-------------------------------------------------------------------------
327 327
328 328 def _ipython_dir_changed(self, name, new):
329 329 if not os.path.isdir(new):
330 330 os.makedirs(new, mode = 0777)
331 331
332 332 def set_autoindent(self,value=None):
333 333 """Set the autoindent flag, checking for readline support.
334 334
335 335 If called with no arguments, it acts as a toggle."""
336 336
337 337 if not self.has_readline:
338 338 if os.name == 'posix':
339 339 warn("The auto-indent feature requires the readline library")
340 340 self.autoindent = 0
341 341 return
342 342 if value is None:
343 343 self.autoindent = not self.autoindent
344 344 else:
345 345 self.autoindent = value
346 346
347 347 #-------------------------------------------------------------------------
348 348 # init_* methods called by __init__
349 349 #-------------------------------------------------------------------------
350 350
351 351 def init_ipython_dir(self, ipython_dir):
352 352 if ipython_dir is not None:
353 353 self.ipython_dir = ipython_dir
354 354 self.config.Global.ipython_dir = self.ipython_dir
355 355 return
356 356
357 357 if hasattr(self.config.Global, 'ipython_dir'):
358 358 self.ipython_dir = self.config.Global.ipython_dir
359 359 else:
360 360 self.ipython_dir = get_ipython_dir()
361 361
362 362 # All children can just read this
363 363 self.config.Global.ipython_dir = self.ipython_dir
364 364
365 365 def init_instance_attrs(self):
366 366 self.more = False
367 367
368 368 # command compiler
369 369 self.compile = codeop.CommandCompiler()
370 370
371 371 # User input buffer
372 372 self.buffer = []
373 373
374 374 # Make an empty namespace, which extension writers can rely on both
375 375 # existing and NEVER being used by ipython itself. This gives them a
376 376 # convenient location for storing additional information and state
377 377 # their extensions may require, without fear of collisions with other
378 378 # ipython names that may develop later.
379 379 self.meta = Struct()
380 380
381 381 # Object variable to store code object waiting execution. This is
382 382 # used mainly by the multithreaded shells, but it can come in handy in
383 383 # other situations. No need to use a Queue here, since it's a single
384 384 # item which gets cleared once run.
385 385 self.code_to_run = None
386 386
387 387 # Temporary files used for various purposes. Deleted at exit.
388 388 self.tempfiles = []
389 389
390 390 # Keep track of readline usage (later set by init_readline)
391 391 self.has_readline = False
392 392
393 393 # keep track of where we started running (mainly for crash post-mortem)
394 394 # This is not being used anywhere currently.
395 395 self.starting_dir = os.getcwd()
396 396
397 397 # Indentation management
398 398 self.indent_current_nsp = 0
399 399
400 # Increasing execution counter
401 self.execution_count = 0
402
400 403 def init_environment(self):
401 404 """Any changes we need to make to the user's environment."""
402 405 pass
403 406
404 407 def init_encoding(self):
405 408 # Get system encoding at startup time. Certain terminals (like Emacs
406 409 # under Win32 have it set to None, and we need to have a known valid
407 410 # encoding to use in the raw_input() method
408 411 try:
409 412 self.stdin_encoding = sys.stdin.encoding or 'ascii'
410 413 except AttributeError:
411 414 self.stdin_encoding = 'ascii'
412 415
413 416 def init_syntax_highlighting(self):
414 417 # Python source parser/formatter for syntax highlighting
415 418 pyformat = PyColorize.Parser().format
416 419 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
417 420
418 421 def init_pushd_popd_magic(self):
419 422 # for pushd/popd management
420 423 try:
421 424 self.home_dir = get_home_dir()
422 425 except HomeDirError, msg:
423 426 fatal(msg)
424 427
425 428 self.dir_stack = []
426 429
427 430 def init_logger(self):
428 431 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
429 432 # local shortcut, this is used a LOT
430 433 self.log = self.logger.log
431 434
432 435 def init_logstart(self):
433 436 if self.logappend:
434 437 self.magic_logstart(self.logappend + ' append')
435 438 elif self.logfile:
436 439 self.magic_logstart(self.logfile)
437 440 elif self.logstart:
438 441 self.magic_logstart()
439 442
440 443 def init_builtins(self):
441 444 self.builtin_trap = BuiltinTrap(shell=self)
442 445
443 446 def init_inspector(self):
444 447 # Object inspector
445 448 self.inspector = oinspect.Inspector(oinspect.InspectColors,
446 449 PyColorize.ANSICodeColors,
447 450 'NoColor',
448 451 self.object_info_string_level)
449 452
450 453 def init_io(self):
451 454 # This will just use sys.stdout and sys.stderr. If you want to
452 455 # override sys.stdout and sys.stderr themselves, you need to do that
453 456 # *before* instantiating this class, because Term holds onto
454 457 # references to the underlying streams.
455 458 if sys.platform == 'win32' and self.has_readline:
456 459 Term = io.IOTerm(cout=self.readline._outputfile,
457 460 cerr=self.readline._outputfile)
458 461 else:
459 462 Term = io.IOTerm()
460 463 io.Term = Term
461 464
462 465 def init_prompts(self):
463 466 # TODO: This is a pass for now because the prompts are managed inside
464 467 # the DisplayHook. Once there is a separate prompt manager, this
465 468 # will initialize that object and all prompt related information.
466 469 pass
467 470
468 471 def init_displayhook(self):
469 472 # Initialize displayhook, set in/out prompts and printing system
470 473 self.displayhook = self.displayhook_class(
471 474 shell=self,
472 475 cache_size=self.cache_size,
473 476 input_sep = self.separate_in,
474 477 output_sep = self.separate_out,
475 478 output_sep2 = self.separate_out2,
476 479 ps1 = self.prompt_in1,
477 480 ps2 = self.prompt_in2,
478 481 ps_out = self.prompt_out,
479 482 pad_left = self.prompts_pad_left
480 483 )
481 484 # This is a context manager that installs/revmoes the displayhook at
482 485 # the appropriate time.
483 486 self.display_trap = DisplayTrap(hook=self.displayhook)
484 487
485 488 def init_reload_doctest(self):
486 489 # Do a proper resetting of doctest, including the necessary displayhook
487 490 # monkeypatching
488 491 try:
489 492 doctest_reload()
490 493 except ImportError:
491 494 warn("doctest module does not exist.")
492 495
493 496 #-------------------------------------------------------------------------
494 497 # Things related to injections into the sys module
495 498 #-------------------------------------------------------------------------
496 499
497 500 def save_sys_module_state(self):
498 501 """Save the state of hooks in the sys module.
499 502
500 503 This has to be called after self.user_ns is created.
501 504 """
502 505 self._orig_sys_module_state = {}
503 506 self._orig_sys_module_state['stdin'] = sys.stdin
504 507 self._orig_sys_module_state['stdout'] = sys.stdout
505 508 self._orig_sys_module_state['stderr'] = sys.stderr
506 509 self._orig_sys_module_state['excepthook'] = sys.excepthook
507 510 try:
508 511 self._orig_sys_modules_main_name = self.user_ns['__name__']
509 512 except KeyError:
510 513 pass
511 514
512 515 def restore_sys_module_state(self):
513 516 """Restore the state of the sys module."""
514 517 try:
515 518 for k, v in self._orig_sys_module_state.items():
516 519 setattr(sys, k, v)
517 520 except AttributeError:
518 521 pass
519 522 # Reset what what done in self.init_sys_modules
520 523 try:
521 524 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
522 525 except (AttributeError, KeyError):
523 526 pass
524 527
525 528 #-------------------------------------------------------------------------
526 529 # Things related to hooks
527 530 #-------------------------------------------------------------------------
528 531
529 532 def init_hooks(self):
530 533 # hooks holds pointers used for user-side customizations
531 534 self.hooks = Struct()
532 535
533 536 self.strdispatchers = {}
534 537
535 538 # Set all default hooks, defined in the IPython.hooks module.
536 539 hooks = IPython.core.hooks
537 540 for hook_name in hooks.__all__:
538 541 # default hooks have priority 100, i.e. low; user hooks should have
539 542 # 0-100 priority
540 543 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
541 544
542 545 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
543 546 """set_hook(name,hook) -> sets an internal IPython hook.
544 547
545 548 IPython exposes some of its internal API as user-modifiable hooks. By
546 549 adding your function to one of these hooks, you can modify IPython's
547 550 behavior to call at runtime your own routines."""
548 551
549 552 # At some point in the future, this should validate the hook before it
550 553 # accepts it. Probably at least check that the hook takes the number
551 554 # of args it's supposed to.
552 555
553 556 f = new.instancemethod(hook,self,self.__class__)
554 557
555 558 # check if the hook is for strdispatcher first
556 559 if str_key is not None:
557 560 sdp = self.strdispatchers.get(name, StrDispatch())
558 561 sdp.add_s(str_key, f, priority )
559 562 self.strdispatchers[name] = sdp
560 563 return
561 564 if re_key is not None:
562 565 sdp = self.strdispatchers.get(name, StrDispatch())
563 566 sdp.add_re(re.compile(re_key), f, priority )
564 567 self.strdispatchers[name] = sdp
565 568 return
566 569
567 570 dp = getattr(self.hooks, name, None)
568 571 if name not in IPython.core.hooks.__all__:
569 572 print "Warning! Hook '%s' is not one of %s" % \
570 573 (name, IPython.core.hooks.__all__ )
571 574 if not dp:
572 575 dp = IPython.core.hooks.CommandChainDispatcher()
573 576
574 577 try:
575 578 dp.add(f,priority)
576 579 except AttributeError:
577 580 # it was not commandchain, plain old func - replace
578 581 dp = f
579 582
580 583 setattr(self.hooks,name, dp)
581 584
582 585 def register_post_execute(self, func):
583 586 """Register a function for calling after code execution.
584 587 """
585 588 if not callable(func):
586 589 raise ValueError('argument %s must be callable' % func)
587 590 self._post_execute.add(func)
588 591
589 592 #-------------------------------------------------------------------------
590 593 # Things related to the "main" module
591 594 #-------------------------------------------------------------------------
592 595
593 596 def new_main_mod(self,ns=None):
594 597 """Return a new 'main' module object for user code execution.
595 598 """
596 599 main_mod = self._user_main_module
597 600 init_fakemod_dict(main_mod,ns)
598 601 return main_mod
599 602
600 603 def cache_main_mod(self,ns,fname):
601 604 """Cache a main module's namespace.
602 605
603 606 When scripts are executed via %run, we must keep a reference to the
604 607 namespace of their __main__ module (a FakeModule instance) around so
605 608 that Python doesn't clear it, rendering objects defined therein
606 609 useless.
607 610
608 611 This method keeps said reference in a private dict, keyed by the
609 612 absolute path of the module object (which corresponds to the script
610 613 path). This way, for multiple executions of the same script we only
611 614 keep one copy of the namespace (the last one), thus preventing memory
612 615 leaks from old references while allowing the objects from the last
613 616 execution to be accessible.
614 617
615 618 Note: we can not allow the actual FakeModule instances to be deleted,
616 619 because of how Python tears down modules (it hard-sets all their
617 620 references to None without regard for reference counts). This method
618 621 must therefore make a *copy* of the given namespace, to allow the
619 622 original module's __dict__ to be cleared and reused.
620 623
621 624
622 625 Parameters
623 626 ----------
624 627 ns : a namespace (a dict, typically)
625 628
626 629 fname : str
627 630 Filename associated with the namespace.
628 631
629 632 Examples
630 633 --------
631 634
632 635 In [10]: import IPython
633 636
634 637 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
635 638
636 639 In [12]: IPython.__file__ in _ip._main_ns_cache
637 640 Out[12]: True
638 641 """
639 642 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
640 643
641 644 def clear_main_mod_cache(self):
642 645 """Clear the cache of main modules.
643 646
644 647 Mainly for use by utilities like %reset.
645 648
646 649 Examples
647 650 --------
648 651
649 652 In [15]: import IPython
650 653
651 654 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652 655
653 656 In [17]: len(_ip._main_ns_cache) > 0
654 657 Out[17]: True
655 658
656 659 In [18]: _ip.clear_main_mod_cache()
657 660
658 661 In [19]: len(_ip._main_ns_cache) == 0
659 662 Out[19]: True
660 663 """
661 664 self._main_ns_cache.clear()
662 665
663 666 #-------------------------------------------------------------------------
664 667 # Things related to debugging
665 668 #-------------------------------------------------------------------------
666 669
667 670 def init_pdb(self):
668 671 # Set calling of pdb on exceptions
669 672 # self.call_pdb is a property
670 673 self.call_pdb = self.pdb
671 674
672 675 def _get_call_pdb(self):
673 676 return self._call_pdb
674 677
675 678 def _set_call_pdb(self,val):
676 679
677 680 if val not in (0,1,False,True):
678 681 raise ValueError,'new call_pdb value must be boolean'
679 682
680 683 # store value in instance
681 684 self._call_pdb = val
682 685
683 686 # notify the actual exception handlers
684 687 self.InteractiveTB.call_pdb = val
685 688
686 689 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
687 690 'Control auto-activation of pdb at exceptions')
688 691
689 692 def debugger(self,force=False):
690 693 """Call the pydb/pdb debugger.
691 694
692 695 Keywords:
693 696
694 697 - force(False): by default, this routine checks the instance call_pdb
695 698 flag and does not actually invoke the debugger if the flag is false.
696 699 The 'force' option forces the debugger to activate even if the flag
697 700 is false.
698 701 """
699 702
700 703 if not (force or self.call_pdb):
701 704 return
702 705
703 706 if not hasattr(sys,'last_traceback'):
704 707 error('No traceback has been produced, nothing to debug.')
705 708 return
706 709
707 710 # use pydb if available
708 711 if debugger.has_pydb:
709 712 from pydb import pm
710 713 else:
711 714 # fallback to our internal debugger
712 715 pm = lambda : self.InteractiveTB.debugger(force=True)
713 716 self.history_saving_wrapper(pm)()
714 717
715 718 #-------------------------------------------------------------------------
716 719 # Things related to IPython's various namespaces
717 720 #-------------------------------------------------------------------------
718 721
719 722 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
720 723 # Create the namespace where the user will operate. user_ns is
721 724 # normally the only one used, and it is passed to the exec calls as
722 725 # the locals argument. But we do carry a user_global_ns namespace
723 726 # given as the exec 'globals' argument, This is useful in embedding
724 727 # situations where the ipython shell opens in a context where the
725 728 # distinction between locals and globals is meaningful. For
726 729 # non-embedded contexts, it is just the same object as the user_ns dict.
727 730
728 731 # FIXME. For some strange reason, __builtins__ is showing up at user
729 732 # level as a dict instead of a module. This is a manual fix, but I
730 733 # should really track down where the problem is coming from. Alex
731 734 # Schmolck reported this problem first.
732 735
733 736 # A useful post by Alex Martelli on this topic:
734 737 # Re: inconsistent value from __builtins__
735 738 # Von: Alex Martelli <aleaxit@yahoo.com>
736 739 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
737 740 # Gruppen: comp.lang.python
738 741
739 742 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
740 743 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
741 744 # > <type 'dict'>
742 745 # > >>> print type(__builtins__)
743 746 # > <type 'module'>
744 747 # > Is this difference in return value intentional?
745 748
746 749 # Well, it's documented that '__builtins__' can be either a dictionary
747 750 # or a module, and it's been that way for a long time. Whether it's
748 751 # intentional (or sensible), I don't know. In any case, the idea is
749 752 # that if you need to access the built-in namespace directly, you
750 753 # should start with "import __builtin__" (note, no 's') which will
751 754 # definitely give you a module. Yeah, it's somewhat confusing:-(.
752 755
753 756 # These routines return properly built dicts as needed by the rest of
754 757 # the code, and can also be used by extension writers to generate
755 758 # properly initialized namespaces.
756 759 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
757 760 user_global_ns)
758 761
759 762 # Assign namespaces
760 763 # This is the namespace where all normal user variables live
761 764 self.user_ns = user_ns
762 765 self.user_global_ns = user_global_ns
763 766
764 767 # An auxiliary namespace that checks what parts of the user_ns were
765 768 # loaded at startup, so we can list later only variables defined in
766 769 # actual interactive use. Since it is always a subset of user_ns, it
767 770 # doesn't need to be separately tracked in the ns_table.
768 771 self.user_ns_hidden = {}
769 772
770 773 # A namespace to keep track of internal data structures to prevent
771 774 # them from cluttering user-visible stuff. Will be updated later
772 775 self.internal_ns = {}
773 776
774 777 # Now that FakeModule produces a real module, we've run into a nasty
775 778 # problem: after script execution (via %run), the module where the user
776 779 # code ran is deleted. Now that this object is a true module (needed
777 780 # so docetst and other tools work correctly), the Python module
778 781 # teardown mechanism runs over it, and sets to None every variable
779 782 # present in that module. Top-level references to objects from the
780 783 # script survive, because the user_ns is updated with them. However,
781 784 # calling functions defined in the script that use other things from
782 785 # the script will fail, because the function's closure had references
783 786 # to the original objects, which are now all None. So we must protect
784 787 # these modules from deletion by keeping a cache.
785 788 #
786 789 # To avoid keeping stale modules around (we only need the one from the
787 790 # last run), we use a dict keyed with the full path to the script, so
788 791 # only the last version of the module is held in the cache. Note,
789 792 # however, that we must cache the module *namespace contents* (their
790 793 # __dict__). Because if we try to cache the actual modules, old ones
791 794 # (uncached) could be destroyed while still holding references (such as
792 795 # those held by GUI objects that tend to be long-lived)>
793 796 #
794 797 # The %reset command will flush this cache. See the cache_main_mod()
795 798 # and clear_main_mod_cache() methods for details on use.
796 799
797 800 # This is the cache used for 'main' namespaces
798 801 self._main_ns_cache = {}
799 802 # And this is the single instance of FakeModule whose __dict__ we keep
800 803 # copying and clearing for reuse on each %run
801 804 self._user_main_module = FakeModule()
802 805
803 806 # A table holding all the namespaces IPython deals with, so that
804 807 # introspection facilities can search easily.
805 808 self.ns_table = {'user':user_ns,
806 809 'user_global':user_global_ns,
807 810 'internal':self.internal_ns,
808 811 'builtin':__builtin__.__dict__
809 812 }
810 813
811 814 # Similarly, track all namespaces where references can be held and that
812 815 # we can safely clear (so it can NOT include builtin). This one can be
813 816 # a simple list.
814 817 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
815 818 self.internal_ns, self._main_ns_cache ]
816 819
817 820 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
818 821 """Return a valid local and global user interactive namespaces.
819 822
820 823 This builds a dict with the minimal information needed to operate as a
821 824 valid IPython user namespace, which you can pass to the various
822 825 embedding classes in ipython. The default implementation returns the
823 826 same dict for both the locals and the globals to allow functions to
824 827 refer to variables in the namespace. Customized implementations can
825 828 return different dicts. The locals dictionary can actually be anything
826 829 following the basic mapping protocol of a dict, but the globals dict
827 830 must be a true dict, not even a subclass. It is recommended that any
828 831 custom object for the locals namespace synchronize with the globals
829 832 dict somehow.
830 833
831 834 Raises TypeError if the provided globals namespace is not a true dict.
832 835
833 836 Parameters
834 837 ----------
835 838 user_ns : dict-like, optional
836 839 The current user namespace. The items in this namespace should
837 840 be included in the output. If None, an appropriate blank
838 841 namespace should be created.
839 842 user_global_ns : dict, optional
840 843 The current user global namespace. The items in this namespace
841 844 should be included in the output. If None, an appropriate
842 845 blank namespace should be created.
843 846
844 847 Returns
845 848 -------
846 849 A pair of dictionary-like object to be used as the local namespace
847 850 of the interpreter and a dict to be used as the global namespace.
848 851 """
849 852
850 853
851 854 # We must ensure that __builtin__ (without the final 's') is always
852 855 # available and pointing to the __builtin__ *module*. For more details:
853 856 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
854 857
855 858 if user_ns is None:
856 859 # Set __name__ to __main__ to better match the behavior of the
857 860 # normal interpreter.
858 861 user_ns = {'__name__' :'__main__',
859 862 '__builtin__' : __builtin__,
860 863 '__builtins__' : __builtin__,
861 864 }
862 865 else:
863 866 user_ns.setdefault('__name__','__main__')
864 867 user_ns.setdefault('__builtin__',__builtin__)
865 868 user_ns.setdefault('__builtins__',__builtin__)
866 869
867 870 if user_global_ns is None:
868 871 user_global_ns = user_ns
869 872 if type(user_global_ns) is not dict:
870 873 raise TypeError("user_global_ns must be a true dict; got %r"
871 874 % type(user_global_ns))
872 875
873 876 return user_ns, user_global_ns
874 877
875 878 def init_sys_modules(self):
876 879 # We need to insert into sys.modules something that looks like a
877 880 # module but which accesses the IPython namespace, for shelve and
878 881 # pickle to work interactively. Normally they rely on getting
879 882 # everything out of __main__, but for embedding purposes each IPython
880 883 # instance has its own private namespace, so we can't go shoving
881 884 # everything into __main__.
882 885
883 886 # note, however, that we should only do this for non-embedded
884 887 # ipythons, which really mimic the __main__.__dict__ with their own
885 888 # namespace. Embedded instances, on the other hand, should not do
886 889 # this because they need to manage the user local/global namespaces
887 890 # only, but they live within a 'normal' __main__ (meaning, they
888 891 # shouldn't overtake the execution environment of the script they're
889 892 # embedded in).
890 893
891 894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
892 895
893 896 try:
894 897 main_name = self.user_ns['__name__']
895 898 except KeyError:
896 899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
897 900 else:
898 901 sys.modules[main_name] = FakeModule(self.user_ns)
899 902
900 903 def init_user_ns(self):
901 904 """Initialize all user-visible namespaces to their minimum defaults.
902 905
903 906 Certain history lists are also initialized here, as they effectively
904 907 act as user namespaces.
905 908
906 909 Notes
907 910 -----
908 911 All data structures here are only filled in, they are NOT reset by this
909 912 method. If they were not empty before, data will simply be added to
910 913 therm.
911 914 """
912 915 # This function works in two parts: first we put a few things in
913 916 # user_ns, and we sync that contents into user_ns_hidden so that these
914 917 # initial variables aren't shown by %who. After the sync, we add the
915 918 # rest of what we *do* want the user to see with %who even on a new
916 919 # session (probably nothing, so theye really only see their own stuff)
917 920
918 921 # The user dict must *always* have a __builtin__ reference to the
919 922 # Python standard __builtin__ namespace, which must be imported.
920 923 # This is so that certain operations in prompt evaluation can be
921 924 # reliably executed with builtins. Note that we can NOT use
922 925 # __builtins__ (note the 's'), because that can either be a dict or a
923 926 # module, and can even mutate at runtime, depending on the context
924 927 # (Python makes no guarantees on it). In contrast, __builtin__ is
925 928 # always a module object, though it must be explicitly imported.
926 929
927 930 # For more details:
928 931 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
929 932 ns = dict(__builtin__ = __builtin__)
930 933
931 934 # Put 'help' in the user namespace
932 935 try:
933 936 from site import _Helper
934 937 ns['help'] = _Helper()
935 938 except ImportError:
936 939 warn('help() not available - check site.py')
937 940
938 941 # make global variables for user access to the histories
939 942 ns['_ih'] = self.input_hist
940 943 ns['_oh'] = self.output_hist
941 944 ns['_dh'] = self.dir_hist
942 945
943 946 ns['_sh'] = shadowns
944 947
945 948 # user aliases to input and output histories. These shouldn't show up
946 949 # in %who, as they can have very large reprs.
947 950 ns['In'] = self.input_hist
948 951 ns['Out'] = self.output_hist
949 952
950 953 # Store myself as the public api!!!
951 954 ns['get_ipython'] = self.get_ipython
952 955
953 956 # Sync what we've added so far to user_ns_hidden so these aren't seen
954 957 # by %who
955 958 self.user_ns_hidden.update(ns)
956 959
957 960 # Anything put into ns now would show up in %who. Think twice before
958 961 # putting anything here, as we really want %who to show the user their
959 962 # stuff, not our variables.
960 963
961 964 # Finally, update the real user's namespace
962 965 self.user_ns.update(ns)
963 966
964 967
965 968 def reset(self):
966 969 """Clear all internal namespaces.
967 970
968 971 Note that this is much more aggressive than %reset, since it clears
969 972 fully all namespaces, as well as all input/output lists.
970 973 """
971 974 for ns in self.ns_refs_table:
972 975 ns.clear()
973 976
974 977 self.alias_manager.clear_aliases()
975 978
976 979 # Clear input and output histories
977 980 self.input_hist[:] = []
978 981 self.input_hist_raw[:] = []
979 982 self.output_hist.clear()
980 983
984 # Reset counter used to index all histories
985 self.execution_count = 0
986
981 987 # Restore the user namespaces to minimal usability
982 988 self.init_user_ns()
983 989
984 990 # Restore the default and user aliases
985 991 self.alias_manager.init_aliases()
986 992
987 993 def reset_selective(self, regex=None):
988 994 """Clear selective variables from internal namespaces based on a
989 995 specified regular expression.
990 996
991 997 Parameters
992 998 ----------
993 999 regex : string or compiled pattern, optional
994 1000 A regular expression pattern that will be used in searching
995 1001 variable names in the users namespaces.
996 1002 """
997 1003 if regex is not None:
998 1004 try:
999 1005 m = re.compile(regex)
1000 1006 except TypeError:
1001 1007 raise TypeError('regex must be a string or compiled pattern')
1002 1008 # Search for keys in each namespace that match the given regex
1003 1009 # If a match is found, delete the key/value pair.
1004 1010 for ns in self.ns_refs_table:
1005 1011 for var in ns:
1006 1012 if m.search(var):
1007 1013 del ns[var]
1008 1014
1009 1015 def push(self, variables, interactive=True):
1010 1016 """Inject a group of variables into the IPython user namespace.
1011 1017
1012 1018 Parameters
1013 1019 ----------
1014 1020 variables : dict, str or list/tuple of str
1015 1021 The variables to inject into the user's namespace. If a dict, a
1016 1022 simple update is done. If a str, the string is assumed to have
1017 1023 variable names separated by spaces. A list/tuple of str can also
1018 1024 be used to give the variable names. If just the variable names are
1019 1025 give (list/tuple/str) then the variable values looked up in the
1020 1026 callers frame.
1021 1027 interactive : bool
1022 1028 If True (default), the variables will be listed with the ``who``
1023 1029 magic.
1024 1030 """
1025 1031 vdict = None
1026 1032
1027 1033 # We need a dict of name/value pairs to do namespace updates.
1028 1034 if isinstance(variables, dict):
1029 1035 vdict = variables
1030 1036 elif isinstance(variables, (basestring, list, tuple)):
1031 1037 if isinstance(variables, basestring):
1032 1038 vlist = variables.split()
1033 1039 else:
1034 1040 vlist = variables
1035 1041 vdict = {}
1036 1042 cf = sys._getframe(1)
1037 1043 for name in vlist:
1038 1044 try:
1039 1045 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1040 1046 except:
1041 1047 print ('Could not get variable %s from %s' %
1042 1048 (name,cf.f_code.co_name))
1043 1049 else:
1044 1050 raise ValueError('variables must be a dict/str/list/tuple')
1045 1051
1046 1052 # Propagate variables to user namespace
1047 1053 self.user_ns.update(vdict)
1048 1054
1049 1055 # And configure interactive visibility
1050 1056 config_ns = self.user_ns_hidden
1051 1057 if interactive:
1052 1058 for name, val in vdict.iteritems():
1053 1059 config_ns.pop(name, None)
1054 1060 else:
1055 1061 for name,val in vdict.iteritems():
1056 1062 config_ns[name] = val
1057 1063
1058 1064 #-------------------------------------------------------------------------
1059 1065 # Things related to object introspection
1060 1066 #-------------------------------------------------------------------------
1061 1067
1062 1068 def _ofind(self, oname, namespaces=None):
1063 1069 """Find an object in the available namespaces.
1064 1070
1065 1071 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1066 1072
1067 1073 Has special code to detect magic functions.
1068 1074 """
1069 1075 #oname = oname.strip()
1070 1076 #print '1- oname: <%r>' % oname # dbg
1071 1077 try:
1072 1078 oname = oname.strip().encode('ascii')
1073 1079 #print '2- oname: <%r>' % oname # dbg
1074 1080 except UnicodeEncodeError:
1075 1081 print 'Python identifiers can only contain ascii characters.'
1076 1082 return dict(found=False)
1077 1083
1078 1084 alias_ns = None
1079 1085 if namespaces is None:
1080 1086 # Namespaces to search in:
1081 1087 # Put them in a list. The order is important so that we
1082 1088 # find things in the same order that Python finds them.
1083 1089 namespaces = [ ('Interactive', self.user_ns),
1084 1090 ('IPython internal', self.internal_ns),
1085 1091 ('Python builtin', __builtin__.__dict__),
1086 1092 ('Alias', self.alias_manager.alias_table),
1087 1093 ]
1088 1094 alias_ns = self.alias_manager.alias_table
1089 1095
1090 1096 # initialize results to 'null'
1091 1097 found = False; obj = None; ospace = None; ds = None;
1092 1098 ismagic = False; isalias = False; parent = None
1093 1099
1094 1100 # We need to special-case 'print', which as of python2.6 registers as a
1095 1101 # function but should only be treated as one if print_function was
1096 1102 # loaded with a future import. In this case, just bail.
1097 1103 if (oname == 'print' and not (self.compile.compiler.flags &
1098 1104 __future__.CO_FUTURE_PRINT_FUNCTION)):
1099 1105 return {'found':found, 'obj':obj, 'namespace':ospace,
1100 1106 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1101 1107
1102 1108 # Look for the given name by splitting it in parts. If the head is
1103 1109 # found, then we look for all the remaining parts as members, and only
1104 1110 # declare success if we can find them all.
1105 1111 oname_parts = oname.split('.')
1106 1112 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1107 1113 for nsname,ns in namespaces:
1108 1114 try:
1109 1115 obj = ns[oname_head]
1110 1116 except KeyError:
1111 1117 continue
1112 1118 else:
1113 1119 #print 'oname_rest:', oname_rest # dbg
1114 1120 for part in oname_rest:
1115 1121 try:
1116 1122 parent = obj
1117 1123 obj = getattr(obj,part)
1118 1124 except:
1119 1125 # Blanket except b/c some badly implemented objects
1120 1126 # allow __getattr__ to raise exceptions other than
1121 1127 # AttributeError, which then crashes IPython.
1122 1128 break
1123 1129 else:
1124 1130 # If we finish the for loop (no break), we got all members
1125 1131 found = True
1126 1132 ospace = nsname
1127 1133 if ns == alias_ns:
1128 1134 isalias = True
1129 1135 break # namespace loop
1130 1136
1131 1137 # Try to see if it's magic
1132 1138 if not found:
1133 1139 if oname.startswith(ESC_MAGIC):
1134 1140 oname = oname[1:]
1135 1141 obj = getattr(self,'magic_'+oname,None)
1136 1142 if obj is not None:
1137 1143 found = True
1138 1144 ospace = 'IPython internal'
1139 1145 ismagic = True
1140 1146
1141 1147 # Last try: special-case some literals like '', [], {}, etc:
1142 1148 if not found and oname_head in ["''",'""','[]','{}','()']:
1143 1149 obj = eval(oname_head)
1144 1150 found = True
1145 1151 ospace = 'Interactive'
1146 1152
1147 1153 return {'found':found, 'obj':obj, 'namespace':ospace,
1148 1154 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1149 1155
1150 1156 def _ofind_property(self, oname, info):
1151 1157 """Second part of object finding, to look for property details."""
1152 1158 if info.found:
1153 1159 # Get the docstring of the class property if it exists.
1154 1160 path = oname.split('.')
1155 1161 root = '.'.join(path[:-1])
1156 1162 if info.parent is not None:
1157 1163 try:
1158 1164 target = getattr(info.parent, '__class__')
1159 1165 # The object belongs to a class instance.
1160 1166 try:
1161 1167 target = getattr(target, path[-1])
1162 1168 # The class defines the object.
1163 1169 if isinstance(target, property):
1164 1170 oname = root + '.__class__.' + path[-1]
1165 1171 info = Struct(self._ofind(oname))
1166 1172 except AttributeError: pass
1167 1173 except AttributeError: pass
1168 1174
1169 1175 # We return either the new info or the unmodified input if the object
1170 1176 # hadn't been found
1171 1177 return info
1172 1178
1173 1179 def _object_find(self, oname, namespaces=None):
1174 1180 """Find an object and return a struct with info about it."""
1175 1181 inf = Struct(self._ofind(oname, namespaces))
1176 1182 return Struct(self._ofind_property(oname, inf))
1177 1183
1178 1184 def _inspect(self, meth, oname, namespaces=None, **kw):
1179 1185 """Generic interface to the inspector system.
1180 1186
1181 1187 This function is meant to be called by pdef, pdoc & friends."""
1182 1188 info = self._object_find(oname)
1183 1189 if info.found:
1184 1190 pmethod = getattr(self.inspector, meth)
1185 1191 formatter = format_screen if info.ismagic else None
1186 1192 if meth == 'pdoc':
1187 1193 pmethod(info.obj, oname, formatter)
1188 1194 elif meth == 'pinfo':
1189 1195 pmethod(info.obj, oname, formatter, info, **kw)
1190 1196 else:
1191 1197 pmethod(info.obj, oname)
1192 1198 else:
1193 1199 print 'Object `%s` not found.' % oname
1194 1200 return 'not found' # so callers can take other action
1195 1201
1196 1202 def object_inspect(self, oname):
1197 1203 info = self._object_find(oname)
1198 1204 if info.found:
1199 1205 return self.inspector.info(info.obj, oname, info=info)
1200 1206 else:
1201 1207 return oinspect.object_info(name=oname, found=False)
1202 1208
1203 1209 #-------------------------------------------------------------------------
1204 1210 # Things related to history management
1205 1211 #-------------------------------------------------------------------------
1206 1212
1207 1213 def init_history(self):
1208 1214 # List of input with multi-line handling.
1209 1215 self.input_hist = InputList()
1210 1216 # This one will hold the 'raw' input history, without any
1211 1217 # pre-processing. This will allow users to retrieve the input just as
1212 1218 # it was exactly typed in by the user, with %hist -r.
1213 1219 self.input_hist_raw = InputList()
1214 1220
1215 1221 # list of visited directories
1216 1222 try:
1217 1223 self.dir_hist = [os.getcwd()]
1218 1224 except OSError:
1219 1225 self.dir_hist = []
1220 1226
1221 1227 # dict of output history
1222 1228 self.output_hist = {}
1223 1229
1224 1230 # Now the history file
1225 1231 if self.profile:
1226 1232 histfname = 'history-%s' % self.profile
1227 1233 else:
1228 1234 histfname = 'history'
1229 1235 self.histfile = os.path.join(self.ipython_dir, histfname)
1230 1236
1231 1237 # Fill the history zero entry, user counter starts at 1
1232 1238 self.input_hist.append('\n')
1233 1239 self.input_hist_raw.append('\n')
1234 1240
1235 1241 def init_shadow_hist(self):
1236 1242 try:
1237 1243 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1238 1244 except exceptions.UnicodeDecodeError:
1239 1245 print "Your ipython_dir can't be decoded to unicode!"
1240 1246 print "Please set HOME environment variable to something that"
1241 1247 print r"only has ASCII characters, e.g. c:\home"
1242 1248 print "Now it is", self.ipython_dir
1243 1249 sys.exit()
1244 1250 self.shadowhist = ipcorehist.ShadowHist(self.db)
1245 1251
1246 1252 def savehist(self):
1247 1253 """Save input history to a file (via readline library)."""
1248 1254
1249 1255 try:
1250 1256 self.readline.write_history_file(self.histfile)
1251 1257 except:
1252 1258 print 'Unable to save IPython command history to file: ' + \
1253 1259 `self.histfile`
1254 1260
1255 1261 def reloadhist(self):
1256 1262 """Reload the input history from disk file."""
1257 1263
1258 1264 try:
1259 1265 self.readline.clear_history()
1260 1266 self.readline.read_history_file(self.shell.histfile)
1261 1267 except AttributeError:
1262 1268 pass
1263 1269
1264 1270 def history_saving_wrapper(self, func):
1265 1271 """ Wrap func for readline history saving
1266 1272
1267 1273 Convert func into callable that saves & restores
1268 1274 history around the call """
1269 1275
1270 1276 if self.has_readline:
1271 1277 from IPython.utils import rlineimpl as readline
1272 1278 else:
1273 1279 return func
1274 1280
1275 1281 def wrapper():
1276 1282 self.savehist()
1277 1283 try:
1278 1284 func()
1279 1285 finally:
1280 1286 readline.read_history_file(self.histfile)
1281 1287 return wrapper
1282 1288
1283 1289 def get_history(self, index=None, raw=False, output=True):
1284 1290 """Get the history list.
1285 1291
1286 1292 Get the input and output history.
1287 1293
1288 1294 Parameters
1289 1295 ----------
1290 1296 index : n or (n1, n2) or None
1291 1297 If n, then the last entries. If a tuple, then all in
1292 1298 range(n1, n2). If None, then all entries. Raises IndexError if
1293 1299 the format of index is incorrect.
1294 1300 raw : bool
1295 1301 If True, return the raw input.
1296 1302 output : bool
1297 1303 If True, then return the output as well.
1298 1304
1299 1305 Returns
1300 1306 -------
1301 1307 If output is True, then return a dict of tuples, keyed by the prompt
1302 1308 numbers and with values of (input, output). If output is False, then
1303 1309 a dict, keyed by the prompt number with the values of input. Raises
1304 1310 IndexError if no history is found.
1305 1311 """
1306 1312 if raw:
1307 1313 input_hist = self.input_hist_raw
1308 1314 else:
1309 1315 input_hist = self.input_hist
1310 1316 if output:
1311 1317 output_hist = self.user_ns['Out']
1312 1318 n = len(input_hist)
1313 1319 if index is None:
1314 1320 start=0; stop=n
1315 1321 elif isinstance(index, int):
1316 1322 start=n-index; stop=n
1317 1323 elif isinstance(index, tuple) and len(index) == 2:
1318 1324 start=index[0]; stop=index[1]
1319 1325 else:
1320 1326 raise IndexError('Not a valid index for the input history: %r'
1321 1327 % index)
1322 1328 hist = {}
1323 1329 for i in range(start, stop):
1324 1330 if output:
1325 1331 hist[i] = (input_hist[i], output_hist.get(i))
1326 1332 else:
1327 1333 hist[i] = input_hist[i]
1328 1334 if len(hist)==0:
1329 1335 raise IndexError('No history for range of indices: %r' % index)
1330 1336 return hist
1331 1337
1332 1338 #-------------------------------------------------------------------------
1333 1339 # Things related to exception handling and tracebacks (not debugging)
1334 1340 #-------------------------------------------------------------------------
1335 1341
1336 1342 def init_traceback_handlers(self, custom_exceptions):
1337 1343 # Syntax error handler.
1338 1344 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1339 1345
1340 1346 # The interactive one is initialized with an offset, meaning we always
1341 1347 # want to remove the topmost item in the traceback, which is our own
1342 1348 # internal code. Valid modes: ['Plain','Context','Verbose']
1343 1349 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1344 1350 color_scheme='NoColor',
1345 1351 tb_offset = 1)
1346 1352
1347 1353 # The instance will store a pointer to the system-wide exception hook,
1348 1354 # so that runtime code (such as magics) can access it. This is because
1349 1355 # during the read-eval loop, it may get temporarily overwritten.
1350 1356 self.sys_excepthook = sys.excepthook
1351 1357
1352 1358 # and add any custom exception handlers the user may have specified
1353 1359 self.set_custom_exc(*custom_exceptions)
1354 1360
1355 1361 # Set the exception mode
1356 1362 self.InteractiveTB.set_mode(mode=self.xmode)
1357 1363
1358 1364 def set_custom_exc(self, exc_tuple, handler):
1359 1365 """set_custom_exc(exc_tuple,handler)
1360 1366
1361 1367 Set a custom exception handler, which will be called if any of the
1362 1368 exceptions in exc_tuple occur in the mainloop (specifically, in the
1363 1369 runcode() method.
1364 1370
1365 1371 Inputs:
1366 1372
1367 1373 - exc_tuple: a *tuple* of valid exceptions to call the defined
1368 1374 handler for. It is very important that you use a tuple, and NOT A
1369 1375 LIST here, because of the way Python's except statement works. If
1370 1376 you only want to trap a single exception, use a singleton tuple:
1371 1377
1372 1378 exc_tuple == (MyCustomException,)
1373 1379
1374 1380 - handler: this must be defined as a function with the following
1375 1381 basic interface::
1376 1382
1377 1383 def my_handler(self, etype, value, tb, tb_offset=None)
1378 1384 ...
1379 1385 # The return value must be
1380 1386 return structured_traceback
1381 1387
1382 1388 This will be made into an instance method (via new.instancemethod)
1383 1389 of IPython itself, and it will be called if any of the exceptions
1384 1390 listed in the exc_tuple are caught. If the handler is None, an
1385 1391 internal basic one is used, which just prints basic info.
1386 1392
1387 1393 WARNING: by putting in your own exception handler into IPython's main
1388 1394 execution loop, you run a very good chance of nasty crashes. This
1389 1395 facility should only be used if you really know what you are doing."""
1390 1396
1391 1397 assert type(exc_tuple)==type(()) , \
1392 1398 "The custom exceptions must be given AS A TUPLE."
1393 1399
1394 1400 def dummy_handler(self,etype,value,tb):
1395 1401 print '*** Simple custom exception handler ***'
1396 1402 print 'Exception type :',etype
1397 1403 print 'Exception value:',value
1398 1404 print 'Traceback :',tb
1399 1405 print 'Source code :','\n'.join(self.buffer)
1400 1406
1401 1407 if handler is None: handler = dummy_handler
1402 1408
1403 1409 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1404 1410 self.custom_exceptions = exc_tuple
1405 1411
1406 1412 def excepthook(self, etype, value, tb):
1407 1413 """One more defense for GUI apps that call sys.excepthook.
1408 1414
1409 1415 GUI frameworks like wxPython trap exceptions and call
1410 1416 sys.excepthook themselves. I guess this is a feature that
1411 1417 enables them to keep running after exceptions that would
1412 1418 otherwise kill their mainloop. This is a bother for IPython
1413 1419 which excepts to catch all of the program exceptions with a try:
1414 1420 except: statement.
1415 1421
1416 1422 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1417 1423 any app directly invokes sys.excepthook, it will look to the user like
1418 1424 IPython crashed. In order to work around this, we can disable the
1419 1425 CrashHandler and replace it with this excepthook instead, which prints a
1420 1426 regular traceback using our InteractiveTB. In this fashion, apps which
1421 1427 call sys.excepthook will generate a regular-looking exception from
1422 1428 IPython, and the CrashHandler will only be triggered by real IPython
1423 1429 crashes.
1424 1430
1425 1431 This hook should be used sparingly, only in places which are not likely
1426 1432 to be true IPython errors.
1427 1433 """
1428 1434 self.showtraceback((etype,value,tb),tb_offset=0)
1429 1435
1430 1436 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1431 1437 exception_only=False):
1432 1438 """Display the exception that just occurred.
1433 1439
1434 1440 If nothing is known about the exception, this is the method which
1435 1441 should be used throughout the code for presenting user tracebacks,
1436 1442 rather than directly invoking the InteractiveTB object.
1437 1443
1438 1444 A specific showsyntaxerror() also exists, but this method can take
1439 1445 care of calling it if needed, so unless you are explicitly catching a
1440 1446 SyntaxError exception, don't try to analyze the stack manually and
1441 1447 simply call this method."""
1442 1448
1443 1449 try:
1444 1450 if exc_tuple is None:
1445 1451 etype, value, tb = sys.exc_info()
1446 1452 else:
1447 1453 etype, value, tb = exc_tuple
1448 1454
1449 1455 if etype is None:
1450 1456 if hasattr(sys, 'last_type'):
1451 1457 etype, value, tb = sys.last_type, sys.last_value, \
1452 1458 sys.last_traceback
1453 1459 else:
1454 1460 self.write_err('No traceback available to show.\n')
1455 1461 return
1456 1462
1457 1463 if etype is SyntaxError:
1458 1464 # Though this won't be called by syntax errors in the input
1459 1465 # line, there may be SyntaxError cases whith imported code.
1460 1466 self.showsyntaxerror(filename)
1461 1467 elif etype is UsageError:
1462 1468 print "UsageError:", value
1463 1469 else:
1464 1470 # WARNING: these variables are somewhat deprecated and not
1465 1471 # necessarily safe to use in a threaded environment, but tools
1466 1472 # like pdb depend on their existence, so let's set them. If we
1467 1473 # find problems in the field, we'll need to revisit their use.
1468 1474 sys.last_type = etype
1469 1475 sys.last_value = value
1470 1476 sys.last_traceback = tb
1471 1477
1472 1478 if etype in self.custom_exceptions:
1473 1479 # FIXME: Old custom traceback objects may just return a
1474 1480 # string, in that case we just put it into a list
1475 1481 stb = self.CustomTB(etype, value, tb, tb_offset)
1476 1482 if isinstance(ctb, basestring):
1477 1483 stb = [stb]
1478 1484 else:
1479 1485 if exception_only:
1480 1486 stb = ['An exception has occurred, use %tb to see '
1481 1487 'the full traceback.\n']
1482 1488 stb.extend(self.InteractiveTB.get_exception_only(etype,
1483 1489 value))
1484 1490 else:
1485 1491 stb = self.InteractiveTB.structured_traceback(etype,
1486 1492 value, tb, tb_offset=tb_offset)
1487 1493 # FIXME: the pdb calling should be done by us, not by
1488 1494 # the code computing the traceback.
1489 1495 if self.InteractiveTB.call_pdb:
1490 1496 # pdb mucks up readline, fix it back
1491 1497 self.set_readline_completer()
1492 1498
1493 1499 # Actually show the traceback
1494 1500 self._showtraceback(etype, value, stb)
1495 1501
1496 1502 except KeyboardInterrupt:
1497 1503 self.write_err("\nKeyboardInterrupt\n")
1498 1504
1499 1505 def _showtraceback(self, etype, evalue, stb):
1500 1506 """Actually show a traceback.
1501 1507
1502 1508 Subclasses may override this method to put the traceback on a different
1503 1509 place, like a side channel.
1504 1510 """
1505 1511 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1506 1512
1507 1513 def showsyntaxerror(self, filename=None):
1508 1514 """Display the syntax error that just occurred.
1509 1515
1510 1516 This doesn't display a stack trace because there isn't one.
1511 1517
1512 1518 If a filename is given, it is stuffed in the exception instead
1513 1519 of what was there before (because Python's parser always uses
1514 1520 "<string>" when reading from a string).
1515 1521 """
1516 1522 etype, value, last_traceback = sys.exc_info()
1517 1523
1518 1524 # See note about these variables in showtraceback() above
1519 1525 sys.last_type = etype
1520 1526 sys.last_value = value
1521 1527 sys.last_traceback = last_traceback
1522 1528
1523 1529 if filename and etype is SyntaxError:
1524 1530 # Work hard to stuff the correct filename in the exception
1525 1531 try:
1526 1532 msg, (dummy_filename, lineno, offset, line) = value
1527 1533 except:
1528 1534 # Not the format we expect; leave it alone
1529 1535 pass
1530 1536 else:
1531 1537 # Stuff in the right filename
1532 1538 try:
1533 1539 # Assume SyntaxError is a class exception
1534 1540 value = SyntaxError(msg, (filename, lineno, offset, line))
1535 1541 except:
1536 1542 # If that failed, assume SyntaxError is a string
1537 1543 value = msg, (filename, lineno, offset, line)
1538 1544 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1539 1545 self._showtraceback(etype, value, stb)
1540 1546
1541 1547 #-------------------------------------------------------------------------
1542 1548 # Things related to readline
1543 1549 #-------------------------------------------------------------------------
1544 1550
1545 1551 def init_readline(self):
1546 1552 """Command history completion/saving/reloading."""
1547 1553
1548 1554 if self.readline_use:
1549 1555 import IPython.utils.rlineimpl as readline
1550 1556
1551 1557 self.rl_next_input = None
1552 1558 self.rl_do_indent = False
1553 1559
1554 1560 if not self.readline_use or not readline.have_readline:
1555 1561 self.has_readline = False
1556 1562 self.readline = None
1557 1563 # Set a number of methods that depend on readline to be no-op
1558 1564 self.savehist = no_op
1559 1565 self.reloadhist = no_op
1560 1566 self.set_readline_completer = no_op
1561 1567 self.set_custom_completer = no_op
1562 1568 self.set_completer_frame = no_op
1563 1569 warn('Readline services not available or not loaded.')
1564 1570 else:
1565 1571 self.has_readline = True
1566 1572 self.readline = readline
1567 1573 sys.modules['readline'] = readline
1568 1574
1569 1575 # Platform-specific configuration
1570 1576 if os.name == 'nt':
1571 1577 # FIXME - check with Frederick to see if we can harmonize
1572 1578 # naming conventions with pyreadline to avoid this
1573 1579 # platform-dependent check
1574 1580 self.readline_startup_hook = readline.set_pre_input_hook
1575 1581 else:
1576 1582 self.readline_startup_hook = readline.set_startup_hook
1577 1583
1578 1584 # Load user's initrc file (readline config)
1579 1585 # Or if libedit is used, load editrc.
1580 1586 inputrc_name = os.environ.get('INPUTRC')
1581 1587 if inputrc_name is None:
1582 1588 home_dir = get_home_dir()
1583 1589 if home_dir is not None:
1584 1590 inputrc_name = '.inputrc'
1585 1591 if readline.uses_libedit:
1586 1592 inputrc_name = '.editrc'
1587 1593 inputrc_name = os.path.join(home_dir, inputrc_name)
1588 1594 if os.path.isfile(inputrc_name):
1589 1595 try:
1590 1596 readline.read_init_file(inputrc_name)
1591 1597 except:
1592 1598 warn('Problems reading readline initialization file <%s>'
1593 1599 % inputrc_name)
1594 1600
1595 1601 # Configure readline according to user's prefs
1596 1602 # This is only done if GNU readline is being used. If libedit
1597 1603 # is being used (as on Leopard) the readline config is
1598 1604 # not run as the syntax for libedit is different.
1599 1605 if not readline.uses_libedit:
1600 1606 for rlcommand in self.readline_parse_and_bind:
1601 1607 #print "loading rl:",rlcommand # dbg
1602 1608 readline.parse_and_bind(rlcommand)
1603 1609
1604 1610 # Remove some chars from the delimiters list. If we encounter
1605 1611 # unicode chars, discard them.
1606 1612 delims = readline.get_completer_delims().encode("ascii", "ignore")
1607 1613 delims = delims.translate(string._idmap,
1608 1614 self.readline_remove_delims)
1609 1615 delims = delims.replace(ESC_MAGIC, '')
1610 1616 readline.set_completer_delims(delims)
1611 1617 # otherwise we end up with a monster history after a while:
1612 1618 readline.set_history_length(1000)
1613 1619 try:
1614 1620 #print '*** Reading readline history' # dbg
1615 1621 readline.read_history_file(self.histfile)
1616 1622 except IOError:
1617 1623 pass # It doesn't exist yet.
1618 1624
1619 1625 # If we have readline, we want our history saved upon ipython
1620 1626 # exiting.
1621 1627 atexit.register(self.savehist)
1622 1628
1623 1629 # Configure auto-indent for all platforms
1624 1630 self.set_autoindent(self.autoindent)
1625 1631
1626 1632 def set_next_input(self, s):
1627 1633 """ Sets the 'default' input string for the next command line.
1628 1634
1629 1635 Requires readline.
1630 1636
1631 1637 Example:
1632 1638
1633 1639 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1634 1640 [D:\ipython]|2> Hello Word_ # cursor is here
1635 1641 """
1636 1642
1637 1643 self.rl_next_input = s
1638 1644
1639 1645 # Maybe move this to the terminal subclass?
1640 1646 def pre_readline(self):
1641 1647 """readline hook to be used at the start of each line.
1642 1648
1643 1649 Currently it handles auto-indent only."""
1644 1650
1645 1651 if self.rl_do_indent:
1646 1652 self.readline.insert_text(self._indent_current_str())
1647 1653 if self.rl_next_input is not None:
1648 1654 self.readline.insert_text(self.rl_next_input)
1649 1655 self.rl_next_input = None
1650 1656
1651 1657 def _indent_current_str(self):
1652 1658 """return the current level of indentation as a string"""
1653 1659 return self.indent_current_nsp * ' '
1654 1660
1655 1661 #-------------------------------------------------------------------------
1656 1662 # Things related to text completion
1657 1663 #-------------------------------------------------------------------------
1658 1664
1659 1665 def init_completer(self):
1660 1666 """Initialize the completion machinery.
1661 1667
1662 1668 This creates completion machinery that can be used by client code,
1663 1669 either interactively in-process (typically triggered by the readline
1664 1670 library), programatically (such as in test suites) or out-of-prcess
1665 1671 (typically over the network by remote frontends).
1666 1672 """
1667 1673 from IPython.core.completer import IPCompleter
1668 1674 from IPython.core.completerlib import (module_completer,
1669 1675 magic_run_completer, cd_completer)
1670 1676
1671 1677 self.Completer = IPCompleter(self,
1672 1678 self.user_ns,
1673 1679 self.user_global_ns,
1674 1680 self.readline_omit__names,
1675 1681 self.alias_manager.alias_table,
1676 1682 self.has_readline)
1677 1683
1678 1684 # Add custom completers to the basic ones built into IPCompleter
1679 1685 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1680 1686 self.strdispatchers['complete_command'] = sdisp
1681 1687 self.Completer.custom_completers = sdisp
1682 1688
1683 1689 self.set_hook('complete_command', module_completer, str_key = 'import')
1684 1690 self.set_hook('complete_command', module_completer, str_key = 'from')
1685 1691 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1686 1692 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1687 1693
1688 1694 # Only configure readline if we truly are using readline. IPython can
1689 1695 # do tab-completion over the network, in GUIs, etc, where readline
1690 1696 # itself may be absent
1691 1697 if self.has_readline:
1692 1698 self.set_readline_completer()
1693 1699
1694 1700 def complete(self, text, line=None, cursor_pos=None):
1695 1701 """Return the completed text and a list of completions.
1696 1702
1697 1703 Parameters
1698 1704 ----------
1699 1705
1700 1706 text : string
1701 1707 A string of text to be completed on. It can be given as empty and
1702 1708 instead a line/position pair are given. In this case, the
1703 1709 completer itself will split the line like readline does.
1704 1710
1705 1711 line : string, optional
1706 1712 The complete line that text is part of.
1707 1713
1708 1714 cursor_pos : int, optional
1709 1715 The position of the cursor on the input line.
1710 1716
1711 1717 Returns
1712 1718 -------
1713 1719 text : string
1714 1720 The actual text that was completed.
1715 1721
1716 1722 matches : list
1717 1723 A sorted list with all possible completions.
1718 1724
1719 1725 The optional arguments allow the completion to take more context into
1720 1726 account, and are part of the low-level completion API.
1721 1727
1722 1728 This is a wrapper around the completion mechanism, similar to what
1723 1729 readline does at the command line when the TAB key is hit. By
1724 1730 exposing it as a method, it can be used by other non-readline
1725 1731 environments (such as GUIs) for text completion.
1726 1732
1727 1733 Simple usage example:
1728 1734
1729 1735 In [1]: x = 'hello'
1730 1736
1731 1737 In [2]: _ip.complete('x.l')
1732 1738 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1733 1739 """
1734 1740
1735 1741 # Inject names into __builtin__ so we can complete on the added names.
1736 1742 with self.builtin_trap:
1737 1743 return self.Completer.complete(text, line, cursor_pos)
1738 1744
1739 1745 def set_custom_completer(self, completer, pos=0):
1740 1746 """Adds a new custom completer function.
1741 1747
1742 1748 The position argument (defaults to 0) is the index in the completers
1743 1749 list where you want the completer to be inserted."""
1744 1750
1745 1751 newcomp = new.instancemethod(completer,self.Completer,
1746 1752 self.Completer.__class__)
1747 1753 self.Completer.matchers.insert(pos,newcomp)
1748 1754
1749 1755 def set_readline_completer(self):
1750 1756 """Reset readline's completer to be our own."""
1751 1757 self.readline.set_completer(self.Completer.rlcomplete)
1752 1758
1753 1759 def set_completer_frame(self, frame=None):
1754 1760 """Set the frame of the completer."""
1755 1761 if frame:
1756 1762 self.Completer.namespace = frame.f_locals
1757 1763 self.Completer.global_namespace = frame.f_globals
1758 1764 else:
1759 1765 self.Completer.namespace = self.user_ns
1760 1766 self.Completer.global_namespace = self.user_global_ns
1761 1767
1762 1768 #-------------------------------------------------------------------------
1763 1769 # Things related to magics
1764 1770 #-------------------------------------------------------------------------
1765 1771
1766 1772 def init_magics(self):
1767 1773 # FIXME: Move the color initialization to the DisplayHook, which
1768 1774 # should be split into a prompt manager and displayhook. We probably
1769 1775 # even need a centralize colors management object.
1770 1776 self.magic_colors(self.colors)
1771 1777 # History was moved to a separate module
1772 1778 from . import history
1773 1779 history.init_ipython(self)
1774 1780
1775 1781 def magic(self,arg_s):
1776 1782 """Call a magic function by name.
1777 1783
1778 1784 Input: a string containing the name of the magic function to call and
1779 1785 any additional arguments to be passed to the magic.
1780 1786
1781 1787 magic('name -opt foo bar') is equivalent to typing at the ipython
1782 1788 prompt:
1783 1789
1784 1790 In[1]: %name -opt foo bar
1785 1791
1786 1792 To call a magic without arguments, simply use magic('name').
1787 1793
1788 1794 This provides a proper Python function to call IPython's magics in any
1789 1795 valid Python code you can type at the interpreter, including loops and
1790 1796 compound statements.
1791 1797 """
1792 1798 args = arg_s.split(' ',1)
1793 1799 magic_name = args[0]
1794 1800 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1795 1801
1796 1802 try:
1797 1803 magic_args = args[1]
1798 1804 except IndexError:
1799 1805 magic_args = ''
1800 1806 fn = getattr(self,'magic_'+magic_name,None)
1801 1807 if fn is None:
1802 1808 error("Magic function `%s` not found." % magic_name)
1803 1809 else:
1804 1810 magic_args = self.var_expand(magic_args,1)
1805 1811 with nested(self.builtin_trap,):
1806 1812 result = fn(magic_args)
1807 1813 return result
1808 1814
1809 1815 def define_magic(self, magicname, func):
1810 1816 """Expose own function as magic function for ipython
1811 1817
1812 1818 def foo_impl(self,parameter_s=''):
1813 1819 'My very own magic!. (Use docstrings, IPython reads them).'
1814 1820 print 'Magic function. Passed parameter is between < >:'
1815 1821 print '<%s>' % parameter_s
1816 1822 print 'The self object is:',self
1817 1823
1818 1824 self.define_magic('foo',foo_impl)
1819 1825 """
1820 1826
1821 1827 import new
1822 1828 im = new.instancemethod(func,self, self.__class__)
1823 1829 old = getattr(self, "magic_" + magicname, None)
1824 1830 setattr(self, "magic_" + magicname, im)
1825 1831 return old
1826 1832
1827 1833 #-------------------------------------------------------------------------
1828 1834 # Things related to macros
1829 1835 #-------------------------------------------------------------------------
1830 1836
1831 1837 def define_macro(self, name, themacro):
1832 1838 """Define a new macro
1833 1839
1834 1840 Parameters
1835 1841 ----------
1836 1842 name : str
1837 1843 The name of the macro.
1838 1844 themacro : str or Macro
1839 1845 The action to do upon invoking the macro. If a string, a new
1840 1846 Macro object is created by passing the string to it.
1841 1847 """
1842 1848
1843 1849 from IPython.core import macro
1844 1850
1845 1851 if isinstance(themacro, basestring):
1846 1852 themacro = macro.Macro(themacro)
1847 1853 if not isinstance(themacro, macro.Macro):
1848 1854 raise ValueError('A macro must be a string or a Macro instance.')
1849 1855 self.user_ns[name] = themacro
1850 1856
1851 1857 #-------------------------------------------------------------------------
1852 1858 # Things related to the running of system commands
1853 1859 #-------------------------------------------------------------------------
1854 1860
1855 1861 def system(self, cmd):
1856 1862 """Call the given cmd in a subprocess.
1857 1863
1858 1864 Parameters
1859 1865 ----------
1860 1866 cmd : str
1861 1867 Command to execute (can not end in '&', as bacground processes are
1862 1868 not supported.
1863 1869 """
1864 1870 # We do not support backgrounding processes because we either use
1865 1871 # pexpect or pipes to read from. Users can always just call
1866 1872 # os.system() if they really want a background process.
1867 1873 if cmd.endswith('&'):
1868 1874 raise OSError("Background processes not supported.")
1869 1875
1870 1876 return system(self.var_expand(cmd, depth=2))
1871 1877
1872 1878 def getoutput(self, cmd, split=True):
1873 1879 """Get output (possibly including stderr) from a subprocess.
1874 1880
1875 1881 Parameters
1876 1882 ----------
1877 1883 cmd : str
1878 1884 Command to execute (can not end in '&', as background processes are
1879 1885 not supported.
1880 1886 split : bool, optional
1881 1887
1882 1888 If True, split the output into an IPython SList. Otherwise, an
1883 1889 IPython LSString is returned. These are objects similar to normal
1884 1890 lists and strings, with a few convenience attributes for easier
1885 1891 manipulation of line-based output. You can use '?' on them for
1886 1892 details.
1887 1893 """
1888 1894 if cmd.endswith('&'):
1889 1895 raise OSError("Background processes not supported.")
1890 1896 out = getoutput(self.var_expand(cmd, depth=2))
1891 1897 if split:
1892 1898 out = SList(out.splitlines())
1893 1899 else:
1894 1900 out = LSString(out)
1895 1901 return out
1896 1902
1897 1903 #-------------------------------------------------------------------------
1898 1904 # Things related to aliases
1899 1905 #-------------------------------------------------------------------------
1900 1906
1901 1907 def init_alias(self):
1902 1908 self.alias_manager = AliasManager(shell=self, config=self.config)
1903 1909 self.ns_table['alias'] = self.alias_manager.alias_table,
1904 1910
1905 1911 #-------------------------------------------------------------------------
1906 1912 # Things related to extensions and plugins
1907 1913 #-------------------------------------------------------------------------
1908 1914
1909 1915 def init_extension_manager(self):
1910 1916 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1911 1917
1912 1918 def init_plugin_manager(self):
1913 1919 self.plugin_manager = PluginManager(config=self.config)
1914 1920
1915 1921 #-------------------------------------------------------------------------
1916 1922 # Things related to payloads
1917 1923 #-------------------------------------------------------------------------
1918 1924
1919 1925 def init_payload(self):
1920 1926 self.payload_manager = PayloadManager(config=self.config)
1921 1927
1922 1928 #-------------------------------------------------------------------------
1923 1929 # Things related to the prefilter
1924 1930 #-------------------------------------------------------------------------
1925 1931
1926 1932 def init_prefilter(self):
1927 1933 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1928 1934 # Ultimately this will be refactored in the new interpreter code, but
1929 1935 # for now, we should expose the main prefilter method (there's legacy
1930 1936 # code out there that may rely on this).
1931 1937 self.prefilter = self.prefilter_manager.prefilter_lines
1932 1938
1933 1939
1934 1940 def auto_rewrite_input(self, cmd):
1935 1941 """Print to the screen the rewritten form of the user's command.
1936 1942
1937 1943 This shows visual feedback by rewriting input lines that cause
1938 1944 automatic calling to kick in, like::
1939 1945
1940 1946 /f x
1941 1947
1942 1948 into::
1943 1949
1944 1950 ------> f(x)
1945 1951
1946 1952 after the user's input prompt. This helps the user understand that the
1947 1953 input line was transformed automatically by IPython.
1948 1954 """
1949 1955 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1950 1956
1951 1957 try:
1952 1958 # plain ascii works better w/ pyreadline, on some machines, so
1953 1959 # we use it and only print uncolored rewrite if we have unicode
1954 1960 rw = str(rw)
1955 1961 print >> IPython.utils.io.Term.cout, rw
1956 1962 except UnicodeEncodeError:
1957 1963 print "------> " + cmd
1958 1964
1959 1965 #-------------------------------------------------------------------------
1960 1966 # Things related to extracting values/expressions from kernel and user_ns
1961 1967 #-------------------------------------------------------------------------
1962 1968
1963 1969 def _simple_error(self):
1964 1970 etype, value = sys.exc_info()[:2]
1965 1971 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1966 1972
1967 1973 def user_variables(self, names):
1968 1974 """Get a list of variable names from the user's namespace.
1969 1975
1970 1976 Parameters
1971 1977 ----------
1972 1978 names : list of strings
1973 1979 A list of names of variables to be read from the user namespace.
1974 1980
1975 1981 Returns
1976 1982 -------
1977 1983 A dict, keyed by the input names and with the repr() of each value.
1978 1984 """
1979 1985 out = {}
1980 1986 user_ns = self.user_ns
1981 1987 for varname in names:
1982 1988 try:
1983 1989 value = repr(user_ns[varname])
1984 1990 except:
1985 1991 value = self._simple_error()
1986 1992 out[varname] = value
1987 1993 return out
1988 1994
1989 1995 def user_expressions(self, expressions):
1990 1996 """Evaluate a dict of expressions in the user's namespace.
1991 1997
1992 1998 Parameters
1993 1999 ----------
1994 2000 expressions : dict
1995 2001 A dict with string keys and string values. The expression values
1996 2002 should be valid Python expressions, each of which will be evaluated
1997 2003 in the user namespace.
1998 2004
1999 2005 Returns
2000 2006 -------
2001 2007 A dict, keyed like the input expressions dict, with the repr() of each
2002 2008 value.
2003 2009 """
2004 2010 out = {}
2005 2011 user_ns = self.user_ns
2006 2012 global_ns = self.user_global_ns
2007 2013 for key, expr in expressions.iteritems():
2008 2014 try:
2009 2015 value = repr(eval(expr, global_ns, user_ns))
2010 2016 except:
2011 2017 value = self._simple_error()
2012 2018 out[key] = value
2013 2019 return out
2014 2020
2015 2021 #-------------------------------------------------------------------------
2016 2022 # Things related to the running of code
2017 2023 #-------------------------------------------------------------------------
2018 2024
2019 2025 def ex(self, cmd):
2020 2026 """Execute a normal python statement in user namespace."""
2021 2027 with nested(self.builtin_trap,):
2022 2028 exec cmd in self.user_global_ns, self.user_ns
2023 2029
2024 2030 def ev(self, expr):
2025 2031 """Evaluate python expression expr in user namespace.
2026 2032
2027 2033 Returns the result of evaluation
2028 2034 """
2029 2035 with nested(self.builtin_trap,):
2030 2036 return eval(expr, self.user_global_ns, self.user_ns)
2031 2037
2032 2038 def safe_execfile(self, fname, *where, **kw):
2033 2039 """A safe version of the builtin execfile().
2034 2040
2035 2041 This version will never throw an exception, but instead print
2036 2042 helpful error messages to the screen. This only works on pure
2037 2043 Python files with the .py extension.
2038 2044
2039 2045 Parameters
2040 2046 ----------
2041 2047 fname : string
2042 2048 The name of the file to be executed.
2043 2049 where : tuple
2044 2050 One or two namespaces, passed to execfile() as (globals,locals).
2045 2051 If only one is given, it is passed as both.
2046 2052 exit_ignore : bool (False)
2047 2053 If True, then silence SystemExit for non-zero status (it is always
2048 2054 silenced for zero status, as it is so common).
2049 2055 """
2050 2056 kw.setdefault('exit_ignore', False)
2051 2057
2052 2058 fname = os.path.abspath(os.path.expanduser(fname))
2053 2059
2054 2060 # Make sure we have a .py file
2055 2061 if not fname.endswith('.py'):
2056 2062 warn('File must end with .py to be run using execfile: <%s>' % fname)
2057 2063
2058 2064 # Make sure we can open the file
2059 2065 try:
2060 2066 with open(fname) as thefile:
2061 2067 pass
2062 2068 except:
2063 2069 warn('Could not open file <%s> for safe execution.' % fname)
2064 2070 return
2065 2071
2066 2072 # Find things also in current directory. This is needed to mimic the
2067 2073 # behavior of running a script from the system command line, where
2068 2074 # Python inserts the script's directory into sys.path
2069 2075 dname = os.path.dirname(fname)
2070 2076
2071 2077 with prepended_to_syspath(dname):
2072 2078 try:
2073 2079 execfile(fname,*where)
2074 2080 except SystemExit, status:
2075 2081 # If the call was made with 0 or None exit status (sys.exit(0)
2076 2082 # or sys.exit() ), don't bother showing a traceback, as both of
2077 2083 # these are considered normal by the OS:
2078 2084 # > python -c'import sys;sys.exit(0)'; echo $?
2079 2085 # 0
2080 2086 # > python -c'import sys;sys.exit()'; echo $?
2081 2087 # 0
2082 2088 # For other exit status, we show the exception unless
2083 2089 # explicitly silenced, but only in short form.
2084 2090 if status.code not in (0, None) and not kw['exit_ignore']:
2085 2091 self.showtraceback(exception_only=True)
2086 2092 except:
2087 2093 self.showtraceback()
2088 2094
2089 2095 def safe_execfile_ipy(self, fname):
2090 2096 """Like safe_execfile, but for .ipy files with IPython syntax.
2091 2097
2092 2098 Parameters
2093 2099 ----------
2094 2100 fname : str
2095 2101 The name of the file to execute. The filename must have a
2096 2102 .ipy extension.
2097 2103 """
2098 2104 fname = os.path.abspath(os.path.expanduser(fname))
2099 2105
2100 2106 # Make sure we have a .py file
2101 2107 if not fname.endswith('.ipy'):
2102 2108 warn('File must end with .py to be run using execfile: <%s>' % fname)
2103 2109
2104 2110 # Make sure we can open the file
2105 2111 try:
2106 2112 with open(fname) as thefile:
2107 2113 pass
2108 2114 except:
2109 2115 warn('Could not open file <%s> for safe execution.' % fname)
2110 2116 return
2111 2117
2112 2118 # Find things also in current directory. This is needed to mimic the
2113 2119 # behavior of running a script from the system command line, where
2114 2120 # Python inserts the script's directory into sys.path
2115 2121 dname = os.path.dirname(fname)
2116 2122
2117 2123 with prepended_to_syspath(dname):
2118 2124 try:
2119 2125 with open(fname) as thefile:
2120 2126 script = thefile.read()
2121 2127 # self.runlines currently captures all exceptions
2122 2128 # raise in user code. It would be nice if there were
2123 2129 # versions of runlines, execfile that did raise, so
2124 2130 # we could catch the errors.
2125 2131 self.runlines(script, clean=True)
2126 2132 except:
2127 2133 self.showtraceback()
2128 2134 warn('Unknown failure executing file: <%s>' % fname)
2129 2135
2130 2136 def run_cell(self, cell):
2131 2137 """Run the contents of an entire multiline 'cell' of code.
2132 2138
2133 2139 The cell is split into separate blocks which can be executed
2134 2140 individually. Then, based on how many blocks there are, they are
2135 2141 executed as follows:
2136 2142
2137 2143 - A single block: 'single' mode.
2138 2144
2139 2145 If there's more than one block, it depends:
2140 2146
2141 2147 - if the last one is no more than two lines long, run all but the last
2142 2148 in 'exec' mode and the very last one in 'single' mode. This makes it
2143 2149 easy to type simple expressions at the end to see computed values. -
2144 2150 otherwise (last one is also multiline), run all in 'exec' mode
2145 2151
2146 2152 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2147 2153 results are displayed and output prompts are computed. In 'exec' mode,
2148 2154 no results are displayed unless :func:`print` is called explicitly;
2149 2155 this mode is more akin to running a script.
2150 2156
2151 2157 Parameters
2152 2158 ----------
2153 2159 cell : str
2154 2160 A single or multiline string.
2155 2161 """
2156 2162 #################################################################
2157 2163 # FIXME
2158 2164 # =====
2159 2165 # This execution logic should stop calling runlines altogether, and
2160 2166 # instead we should do what runlines does, in a controlled manner, here
2161 2167 # (runlines mutates lots of state as it goes calling sub-methods that
2162 2168 # also mutate state). Basically we should:
2163 2169 # - apply dynamic transforms for single-line input (the ones that
2164 2170 # split_blocks won't apply since they need context).
2165 2171 # - increment the global execution counter (we need to pull that out
2166 2172 # from outputcache's control; outputcache should instead read it from
2167 2173 # the main object).
2168 2174 # - do any logging of input
2169 2175 # - update histories (raw/translated)
2170 2176 # - then, call plain runsource (for single blocks, so displayhook is
2171 2177 # triggered) or runcode (for multiline blocks in exec mode).
2172 2178 #
2173 2179 # Once this is done, we'll be able to stop using runlines and we'll
2174 2180 # also have a much cleaner separation of logging, input history and
2175 2181 # output cache management.
2176 2182 #################################################################
2177 2183
2178 2184 # We need to break up the input into executable blocks that can be run
2179 2185 # in 'single' mode, to provide comfortable user behavior.
2180 2186 blocks = self.input_splitter.split_blocks(cell)
2181 2187
2182 2188 if not blocks:
2183 2189 return
2184 2190
2185 2191 # Store the 'ipython' version of the cell as well, since that's what
2186 2192 # needs to go into the translated history and get executed (the
2187 2193 # original cell may contain non-python syntax).
2188 2194 ipy_cell = ''.join(blocks)
2189
2190 # Single-block input should behave like an interactive prompt
2191 if len(blocks) == 1:
2192 self.runlines(blocks[0])
2193 return
2194 2195
2195 # In multi-block input, if the last block is a simple (one-two lines)
2196 # expression, run it in single mode so it produces output. Otherwise
2197 # just feed the whole thing to runcode.
2198 # This seems like a reasonable usability design.
2199 last = blocks[-1]
2200 last_nlines = len(last.splitlines())
2201
2202 # Note: below, whenever we call runcode, we must sync history
2203 # ourselves, because runcode is NOT meant to manage history at all.
2204 if last_nlines < 2:
2205 # Here we consider the cell split between 'body' and 'last', store
2206 # all history and execute 'body', and if successful, then proceed
2207 # to execute 'last'.
2208
2209 # Raw history must contain the unmodified cell
2210 raw_body = '\n'.join(cell.splitlines()[:-last_nlines])+'\n'
2211 self.input_hist_raw.append(raw_body)
2212 # Get the main body to run as a cell
2213 ipy_body = ''.join(blocks[:-1])
2214 self.input_hist.append(ipy_body)
2215 retcode = self.runcode(ipy_body, post_execute=False)
2216 if retcode==0:
2217 # And the last expression via runlines so it produces output
2218 self.runlines(last)
2196 # Each cell is a *single* input, regardless of how many lines it has
2197 self.execution_count += 1
2198
2199 # Store raw and processed history
2200 self.input_hist_raw.append(cell)
2201 self.input_hist.append(ipy_cell)
2202
2203 # All user code execution must happen with our context managers active
2204 with nested(self.builtin_trap, self.display_trap):
2205 # Single-block input should behave like an interactive prompt
2206 if len(blocks) == 1:
2207 return self.run_one_block(blocks[0])
2208
2209 # In multi-block input, if the last block is a simple (one-two
2210 # lines) expression, run it in single mode so it produces output.
2211 # Otherwise just feed the whole thing to runcode. This seems like
2212 # a reasonable usability design.
2213 last = blocks[-1]
2214 last_nlines = len(last.splitlines())
2215
2216 # Note: below, whenever we call runcode, we must sync history
2217 # ourselves, because runcode is NOT meant to manage history at all.
2218 if last_nlines < 2:
2219 # Here we consider the cell split between 'body' and 'last',
2220 # store all history and execute 'body', and if successful, then
2221 # proceed to execute 'last'.
2222
2223 # Get the main body to run as a cell
2224 ipy_body = ''.join(blocks[:-1])
2225 retcode = self.runcode(ipy_body, post_execute=False)
2226 if retcode==0:
2227 # And the last expression via runlines so it produces output
2228 self.run_one_block(last)
2229 else:
2230 # Run the whole cell as one entity, storing both raw and
2231 # processed input in history
2232 self.runcode(ipy_cell)
2233
2234 def run_one_block(self, block):
2235 """Run a single interactive block.
2236
2237 If the block is single-line, dynamic transformations are applied to it
2238 (like automagics, autocall and alias recognition).
2239 """
2240 if len(block.splitlines()) <= 1:
2241 out = self.run_single_line(block)
2219 2242 else:
2220 # Run the whole cell as one entity, storing both raw and processed
2221 # input in history
2222 self.input_hist_raw.append(cell)
2223 self.input_hist.append(ipy_cell)
2224 self.runcode(ipy_cell)
2243 out = self.runcode(block)
2244 return out
2245
2246 def run_single_line(self, line):
2247 """Run a single-line interactive statement.
2248
2249 This assumes the input has been transformed to IPython syntax by
2250 applying all static transformations (those with an explicit prefix like
2251 % or !), but it will further try to apply the dynamic ones.
2252
2253 It does not update history.
2254 """
2255 tline = self.prefilter_manager.prefilter_line(line)
2256 return self.runsource(tline)
2225 2257
2226 2258 def runlines(self, lines, clean=False):
2227 2259 """Run a string of one or more lines of source.
2228 2260
2229 2261 This method is capable of running a string containing multiple source
2230 2262 lines, as if they had been entered at the IPython prompt. Since it
2231 2263 exposes IPython's processing machinery, the given strings can contain
2232 2264 magic calls (%magic), special shell access (!cmd), etc.
2233 2265 """
2234 2266
2235 2267 if isinstance(lines, (list, tuple)):
2236 2268 lines = '\n'.join(lines)
2237 2269
2238 2270 if clean:
2239 2271 lines = self._cleanup_ipy_script(lines)
2240 2272
2241 2273 # We must start with a clean buffer, in case this is run from an
2242 2274 # interactive IPython session (via a magic, for example).
2243 2275 self.resetbuffer()
2244 2276 lines = lines.splitlines()
2245 2277 more = 0
2246 2278 with nested(self.builtin_trap, self.display_trap):
2247 2279 for line in lines:
2248 2280 # skip blank lines so we don't mess up the prompt counter, but
2249 2281 # do NOT skip even a blank line if we are in a code block (more
2250 2282 # is true)
2251 2283
2252 2284 if line or more:
2253 2285 # push to raw history, so hist line numbers stay in sync
2254 2286 self.input_hist_raw.append(line + '\n')
2255 2287 prefiltered = self.prefilter_manager.prefilter_lines(line,
2256 2288 more)
2257 2289 more = self.push_line(prefiltered)
2258 2290 # IPython's runsource returns None if there was an error
2259 2291 # compiling the code. This allows us to stop processing
2260 2292 # right away, so the user gets the error message at the
2261 2293 # right place.
2262 2294 if more is None:
2263 2295 break
2264 2296 else:
2265 2297 self.input_hist_raw.append("\n")
2266 2298 # final newline in case the input didn't have it, so that the code
2267 2299 # actually does get executed
2268 2300 if more:
2269 2301 self.push_line('\n')
2270 2302
2271 2303 def runsource(self, source, filename='<input>', symbol='single'):
2272 2304 """Compile and run some source in the interpreter.
2273 2305
2274 2306 Arguments are as for compile_command().
2275 2307
2276 2308 One several things can happen:
2277 2309
2278 2310 1) The input is incorrect; compile_command() raised an
2279 2311 exception (SyntaxError or OverflowError). A syntax traceback
2280 2312 will be printed by calling the showsyntaxerror() method.
2281 2313
2282 2314 2) The input is incomplete, and more input is required;
2283 2315 compile_command() returned None. Nothing happens.
2284 2316
2285 2317 3) The input is complete; compile_command() returned a code
2286 2318 object. The code is executed by calling self.runcode() (which
2287 2319 also handles run-time exceptions, except for SystemExit).
2288 2320
2289 2321 The return value is:
2290 2322
2291 2323 - True in case 2
2292 2324
2293 2325 - False in the other cases, unless an exception is raised, where
2294 2326 None is returned instead. This can be used by external callers to
2295 2327 know whether to continue feeding input or not.
2296 2328
2297 2329 The return value can be used to decide whether to use sys.ps1 or
2298 2330 sys.ps2 to prompt the next line."""
2299 2331
2300 2332 # We need to ensure that the source is unicode from here on.
2301 2333 if type(source)==str:
2302 2334 source = source.decode(self.stdin_encoding)
2303 2335
2304 2336 # if the source code has leading blanks, add 'if 1:\n' to it
2305 2337 # this allows execution of indented pasted code. It is tempting
2306 2338 # to add '\n' at the end of source to run commands like ' a=1'
2307 2339 # directly, but this fails for more complicated scenarios
2308 2340
2309 2341 if source[:1] in [' ', '\t']:
2310 2342 source = u'if 1:\n%s' % source
2311 2343
2312 2344 try:
2313 2345 code = self.compile(source,filename,symbol)
2314 2346 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2315 2347 # Case 1
2316 2348 self.showsyntaxerror(filename)
2317 2349 return None
2318 2350
2319 2351 if code is None:
2320 2352 # Case 2
2321 2353 return True
2322 2354
2323 2355 # Case 3
2324 2356 # We store the code object so that threaded shells and
2325 2357 # custom exception handlers can access all this info if needed.
2326 2358 # The source corresponding to this can be obtained from the
2327 2359 # buffer attribute as '\n'.join(self.buffer).
2328 2360 self.code_to_run = code
2329 2361 # now actually execute the code object
2330 2362 if self.runcode(code) == 0:
2331 2363 return False
2332 2364 else:
2333 2365 return None
2334 2366
2335 2367 def runcode(self, code_obj, post_execute=True):
2336 2368 """Execute a code object.
2337 2369
2338 2370 When an exception occurs, self.showtraceback() is called to display a
2339 2371 traceback.
2340 2372
2341 2373 Return value: a flag indicating whether the code to be run completed
2342 2374 successfully:
2343 2375
2344 2376 - 0: successful execution.
2345 2377 - 1: an error occurred.
2346 2378 """
2347 2379
2348 2380 # Set our own excepthook in case the user code tries to call it
2349 2381 # directly, so that the IPython crash handler doesn't get triggered
2350 2382 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2351 2383
2352 2384 # we save the original sys.excepthook in the instance, in case config
2353 2385 # code (such as magics) needs access to it.
2354 2386 self.sys_excepthook = old_excepthook
2355 2387 outflag = 1 # happens in more places, so it's easier as default
2356 2388 try:
2357 2389 try:
2358 2390 self.hooks.pre_runcode_hook()
2359 2391 #rprint('Running code') # dbg
2360 2392 exec code_obj in self.user_global_ns, self.user_ns
2361 2393 finally:
2362 2394 # Reset our crash handler in place
2363 2395 sys.excepthook = old_excepthook
2364 2396 except SystemExit:
2365 2397 self.resetbuffer()
2366 2398 self.showtraceback(exception_only=True)
2367 2399 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2368 2400 except self.custom_exceptions:
2369 2401 etype,value,tb = sys.exc_info()
2370 2402 self.CustomTB(etype,value,tb)
2371 2403 except:
2372 2404 self.showtraceback()
2373 2405 else:
2374 2406 outflag = 0
2375 2407 if softspace(sys.stdout, 0):
2376 2408 print
2377 2409
2378 2410 # Execute any registered post-execution functions. Here, any errors
2379 2411 # are reported only minimally and just on the terminal, because the
2380 2412 # main exception channel may be occupied with a user traceback.
2381 2413 # FIXME: we need to think this mechanism a little more carefully.
2382 2414 if post_execute:
2383 2415 for func in self._post_execute:
2384 2416 try:
2385 2417 func()
2386 2418 except:
2387 2419 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2388 2420 func
2389 2421 print >> io.Term.cout, head
2390 2422 print >> io.Term.cout, self._simple_error()
2391 2423 print >> io.Term.cout, 'Removing from post_execute'
2392 2424 self._post_execute.remove(func)
2393 2425
2394 2426 # Flush out code object which has been run (and source)
2395 2427 self.code_to_run = None
2396 2428 return outflag
2397 2429
2398 2430 def push_line(self, line):
2399 2431 """Push a line to the interpreter.
2400 2432
2401 2433 The line should not have a trailing newline; it may have
2402 2434 internal newlines. The line is appended to a buffer and the
2403 2435 interpreter's runsource() method is called with the
2404 2436 concatenated contents of the buffer as source. If this
2405 2437 indicates that the command was executed or invalid, the buffer
2406 2438 is reset; otherwise, the command is incomplete, and the buffer
2407 2439 is left as it was after the line was appended. The return
2408 2440 value is 1 if more input is required, 0 if the line was dealt
2409 2441 with in some way (this is the same as runsource()).
2410 2442 """
2411 2443
2412 2444 # autoindent management should be done here, and not in the
2413 2445 # interactive loop, since that one is only seen by keyboard input. We
2414 2446 # need this done correctly even for code run via runlines (which uses
2415 2447 # push).
2416 2448
2417 2449 #print 'push line: <%s>' % line # dbg
2418 2450 for subline in line.splitlines():
2419 2451 self._autoindent_update(subline)
2420 2452 self.buffer.append(line)
2421 2453 more = self.runsource('\n'.join(self.buffer), self.filename)
2422 2454 if not more:
2423 2455 self.resetbuffer()
2456 self.execution_count += 1
2424 2457 return more
2425 2458
2426 2459 def resetbuffer(self):
2427 2460 """Reset the input buffer."""
2428 2461 self.buffer[:] = []
2429 2462
2430 2463 def _is_secondary_block_start(self, s):
2431 2464 if not s.endswith(':'):
2432 2465 return False
2433 2466 if (s.startswith('elif') or
2434 2467 s.startswith('else') or
2435 2468 s.startswith('except') or
2436 2469 s.startswith('finally')):
2437 2470 return True
2438 2471
2439 2472 def _cleanup_ipy_script(self, script):
2440 2473 """Make a script safe for self.runlines()
2441 2474
2442 2475 Currently, IPython is lines based, with blocks being detected by
2443 2476 empty lines. This is a problem for block based scripts that may
2444 2477 not have empty lines after blocks. This script adds those empty
2445 2478 lines to make scripts safe for running in the current line based
2446 2479 IPython.
2447 2480 """
2448 2481 res = []
2449 2482 lines = script.splitlines()
2450 2483 level = 0
2451 2484
2452 2485 for l in lines:
2453 2486 lstripped = l.lstrip()
2454 2487 stripped = l.strip()
2455 2488 if not stripped:
2456 2489 continue
2457 2490 newlevel = len(l) - len(lstripped)
2458 2491 if level > 0 and newlevel == 0 and \
2459 2492 not self._is_secondary_block_start(stripped):
2460 2493 # add empty line
2461 2494 res.append('')
2462 2495 res.append(l)
2463 2496 level = newlevel
2464 2497
2465 2498 return '\n'.join(res) + '\n'
2466 2499
2467 2500 def _autoindent_update(self,line):
2468 2501 """Keep track of the indent level."""
2469 2502
2470 2503 #debugx('line')
2471 2504 #debugx('self.indent_current_nsp')
2472 2505 if self.autoindent:
2473 2506 if line:
2474 2507 inisp = num_ini_spaces(line)
2475 2508 if inisp < self.indent_current_nsp:
2476 2509 self.indent_current_nsp = inisp
2477 2510
2478 2511 if line[-1] == ':':
2479 2512 self.indent_current_nsp += 4
2480 2513 elif dedent_re.match(line):
2481 2514 self.indent_current_nsp -= 4
2482 2515 else:
2483 2516 self.indent_current_nsp = 0
2484 2517
2485 2518 #-------------------------------------------------------------------------
2486 2519 # Things related to GUI support and pylab
2487 2520 #-------------------------------------------------------------------------
2488 2521
2489 2522 def enable_pylab(self, gui=None):
2490 2523 raise NotImplementedError('Implement enable_pylab in a subclass')
2491 2524
2492 2525 #-------------------------------------------------------------------------
2493 2526 # Utilities
2494 2527 #-------------------------------------------------------------------------
2495 2528
2496 2529 def var_expand(self,cmd,depth=0):
2497 2530 """Expand python variables in a string.
2498 2531
2499 2532 The depth argument indicates how many frames above the caller should
2500 2533 be walked to look for the local namespace where to expand variables.
2501 2534
2502 2535 The global namespace for expansion is always the user's interactive
2503 2536 namespace.
2504 2537 """
2505 2538
2506 2539 return str(ItplNS(cmd,
2507 2540 self.user_ns, # globals
2508 2541 # Skip our own frame in searching for locals:
2509 2542 sys._getframe(depth+1).f_locals # locals
2510 2543 ))
2511 2544
2512 2545 def mktempfile(self,data=None):
2513 2546 """Make a new tempfile and return its filename.
2514 2547
2515 2548 This makes a call to tempfile.mktemp, but it registers the created
2516 2549 filename internally so ipython cleans it up at exit time.
2517 2550
2518 2551 Optional inputs:
2519 2552
2520 2553 - data(None): if data is given, it gets written out to the temp file
2521 2554 immediately, and the file is closed again."""
2522 2555
2523 2556 filename = tempfile.mktemp('.py','ipython_edit_')
2524 2557 self.tempfiles.append(filename)
2525 2558
2526 2559 if data:
2527 2560 tmp_file = open(filename,'w')
2528 2561 tmp_file.write(data)
2529 2562 tmp_file.close()
2530 2563 return filename
2531 2564
2532 2565 # TODO: This should be removed when Term is refactored.
2533 2566 def write(self,data):
2534 2567 """Write a string to the default output"""
2535 2568 io.Term.cout.write(data)
2536 2569
2537 2570 # TODO: This should be removed when Term is refactored.
2538 2571 def write_err(self,data):
2539 2572 """Write a string to the default error output"""
2540 2573 io.Term.cerr.write(data)
2541 2574
2542 2575 def ask_yes_no(self,prompt,default=True):
2543 2576 if self.quiet:
2544 2577 return True
2545 2578 return ask_yes_no(prompt,default)
2546 2579
2547 2580 def show_usage(self):
2548 2581 """Show a usage message"""
2549 2582 page.page(IPython.core.usage.interactive_usage)
2550 2583
2551 2584 #-------------------------------------------------------------------------
2552 2585 # Things related to IPython exiting
2553 2586 #-------------------------------------------------------------------------
2554 2587 def atexit_operations(self):
2555 2588 """This will be executed at the time of exit.
2556 2589
2557 2590 Cleanup operations and saving of persistent data that is done
2558 2591 unconditionally by IPython should be performed here.
2559 2592
2560 2593 For things that may depend on startup flags or platform specifics (such
2561 2594 as having readline or not), register a separate atexit function in the
2562 2595 code that has the appropriate information, rather than trying to
2563 2596 clutter
2564 2597 """
2565 2598 # Cleanup all tempfiles left around
2566 2599 for tfile in self.tempfiles:
2567 2600 try:
2568 2601 os.unlink(tfile)
2569 2602 except OSError:
2570 2603 pass
2571 2604
2572 2605 # Clear all user namespaces to release all references cleanly.
2573 2606 self.reset()
2574 2607
2575 2608 # Run user hooks
2576 2609 self.hooks.shutdown_hook()
2577 2610
2578 2611 def cleanup(self):
2579 2612 self.restore_sys_module_state()
2580 2613
2581 2614
2582 2615 class InteractiveShellABC(object):
2583 2616 """An abstract base class for InteractiveShell."""
2584 2617 __metaclass__ = abc.ABCMeta
2585 2618
2586 2619 InteractiveShellABC.register(InteractiveShell)
@@ -1,263 +1,265 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Logger class for IPython's logging facilities.
4 4 """
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15 # Modules and globals
16 16
17 17 # Python standard modules
18 18 import glob
19 19 import os
20 20 import time
21 21
22 22 #****************************************************************************
23 23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
24 24 # ipython and does input cache management. Finish cleanup later...
25 25
26 26 class Logger(object):
27 27 """A Logfile class with different policies for file creation"""
28 28
29 29 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
30 30
31 31 self._i00,self._i,self._ii,self._iii = '','','',''
32 32
33 33 # this is the full ipython instance, we need some attributes from it
34 34 # which won't exist until later. What a mess, clean up later...
35 35 self.shell = shell
36 36
37 37 self.logfname = logfname
38 38 self.loghead = loghead
39 39 self.logmode = logmode
40 40 self.logfile = None
41 41
42 42 # Whether to log raw or processed input
43 43 self.log_raw_input = False
44 44
45 45 # whether to also log output
46 46 self.log_output = False
47 47
48 48 # whether to put timestamps before each log entry
49 49 self.timestamp = False
50 50
51 51 # activity control flags
52 52 self.log_active = False
53 53
54 54 # logmode is a validated property
55 55 def _set_mode(self,mode):
56 56 if mode not in ['append','backup','global','over','rotate']:
57 57 raise ValueError,'invalid log mode %s given' % mode
58 58 self._logmode = mode
59 59
60 60 def _get_mode(self):
61 61 return self._logmode
62 62
63 63 logmode = property(_get_mode,_set_mode)
64 64
65 65 def logstart(self,logfname=None,loghead=None,logmode=None,
66 66 log_output=False,timestamp=False,log_raw_input=False):
67 67 """Generate a new log-file with a default header.
68 68
69 69 Raises RuntimeError if the log has already been started"""
70 70
71 71 if self.logfile is not None:
72 72 raise RuntimeError('Log file is already active: %s' %
73 73 self.logfname)
74 74
75 75 self.log_active = True
76 76
77 77 # The parameters can override constructor defaults
78 78 if logfname is not None: self.logfname = logfname
79 79 if loghead is not None: self.loghead = loghead
80 80 if logmode is not None: self.logmode = logmode
81 81
82 82 # Parameters not part of the constructor
83 83 self.timestamp = timestamp
84 84 self.log_output = log_output
85 85 self.log_raw_input = log_raw_input
86 86
87 87 # init depending on the log mode requested
88 88 isfile = os.path.isfile
89 89 logmode = self.logmode
90 90
91 91 if logmode == 'append':
92 92 self.logfile = open(self.logfname,'a')
93 93
94 94 elif logmode == 'backup':
95 95 if isfile(self.logfname):
96 96 backup_logname = self.logfname+'~'
97 97 # Manually remove any old backup, since os.rename may fail
98 98 # under Windows.
99 99 if isfile(backup_logname):
100 100 os.remove(backup_logname)
101 101 os.rename(self.logfname,backup_logname)
102 102 self.logfile = open(self.logfname,'w')
103 103
104 104 elif logmode == 'global':
105 105 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
106 106 self.logfile = open(self.logfname, 'a')
107 107
108 108 elif logmode == 'over':
109 109 if isfile(self.logfname):
110 110 os.remove(self.logfname)
111 111 self.logfile = open(self.logfname,'w')
112 112
113 113 elif logmode == 'rotate':
114 114 if isfile(self.logfname):
115 115 if isfile(self.logfname+'.001~'):
116 116 old = glob.glob(self.logfname+'.*~')
117 117 old.sort()
118 118 old.reverse()
119 119 for f in old:
120 120 root, ext = os.path.splitext(f)
121 121 num = int(ext[1:-1])+1
122 122 os.rename(f, root+'.'+`num`.zfill(3)+'~')
123 123 os.rename(self.logfname, self.logfname+'.001~')
124 124 self.logfile = open(self.logfname,'w')
125 125
126 126 if logmode != 'append':
127 127 self.logfile.write(self.loghead)
128 128
129 129 self.logfile.flush()
130 130
131 131 def switch_log(self,val):
132 132 """Switch logging on/off. val should be ONLY a boolean."""
133 133
134 134 if val not in [False,True,0,1]:
135 135 raise ValueError, \
136 136 'Call switch_log ONLY with a boolean argument, not with:',val
137 137
138 138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139 139
140 140 if self.logfile is None:
141 141 print """
142 142 Logging hasn't been started yet (use logstart for that).
143 143
144 144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 145 which already exists. But you must first start the logging process with
146 146 %logstart (optionally giving a logfile name)."""
147 147
148 148 else:
149 149 if self.log_active == val:
150 150 print 'Logging is already',label[val]
151 151 else:
152 152 print 'Switching logging',label[val]
153 153 self.log_active = not self.log_active
154 154 self.log_active_out = self.log_active
155 155
156 156 def logstate(self):
157 157 """Print a status message about the logger."""
158 158 if self.logfile is None:
159 159 print 'Logging has not been activated.'
160 160 else:
161 161 state = self.log_active and 'active' or 'temporarily suspended'
162 162 print 'Filename :',self.logfname
163 163 print 'Mode :',self.logmode
164 164 print 'Output logging :',self.log_output
165 165 print 'Raw input log :',self.log_raw_input
166 166 print 'Timestamping :',self.timestamp
167 167 print 'State :',state
168 168
169 169 def log(self,line_ori,line_mod,continuation=None):
170 170 """Write the line to a log and create input cache variables _i*.
171 171
172 172 Inputs:
173 173
174 174 - line_ori: unmodified input line from the user. This is not
175 175 necessarily valid Python.
176 176
177 177 - line_mod: possibly modified input, such as the transformations made
178 178 by input prefilters or input handlers of various kinds. This should
179 179 always be valid Python.
180 180
181 181 - continuation: if True, indicates this is part of multi-line input."""
182 182
183 183 # update the auto _i tables
184 184 #print '***logging line',line_mod # dbg
185 185 #print '***cache_count', self.shell.displayhook.prompt_count # dbg
186 186 try:
187 187 input_hist = self.shell.user_ns['_ih']
188 188 except:
189 189 #print 'userns:',self.shell.user_ns.keys() # dbg
190 190 return
191 191
192 192 out_cache = self.shell.displayhook
193 193
194 194 # add blank lines if the input cache fell out of sync.
195 195 if out_cache.do_full_cache and \
196 196 out_cache.prompt_count +1 > len(input_hist):
197 197 input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist)))
198 198
199 199 if not continuation and line_mod:
200 200 self._iii = self._ii
201 201 self._ii = self._i
202 202 self._i = self._i00
203 203 # put back the final \n of every input line
204 204 self._i00 = line_mod+'\n'
205 205 #print 'Logging input:<%s>' % line_mod # dbg
206 206 input_hist.append(self._i00)
207 207 #print '---[%s]' % (len(input_hist)-1,) # dbg
208 208
209 209 # hackish access to top-level namespace to create _i1,_i2... dynamically
210 210 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
211 211 if self.shell.displayhook.do_full_cache:
212 212 in_num = self.shell.displayhook.prompt_count
213 213
214 214 # but if the opposite is true (a macro can produce multiple inputs
215 215 # with no output display called), then bring the output counter in
216 216 # sync:
217 last_num = len(input_hist)-1
218 if in_num != last_num:
219 in_num = self.shell.displayhook.prompt_count = last_num
217 ## last_num = len(input_hist)-1
218 ## if in_num != last_num:
219 ## pass # dbg
220 ## #in_num = self.shell.execution_count = last_num
221
220 222 new_i = '_i%s' % in_num
221 223 if continuation:
222 224 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
223 225 input_hist[in_num] = self._i00
224 226 to_main[new_i] = self._i00
225 227 self.shell.user_ns.update(to_main)
226 228
227 229 # Write the log line, but decide which one according to the
228 230 # log_raw_input flag, set when the log is started.
229 231 if self.log_raw_input:
230 232 self.log_write(line_ori)
231 233 else:
232 234 self.log_write(line_mod)
233 235
234 236 def log_write(self,data,kind='input'):
235 237 """Write data to the log file, if active"""
236 238
237 239 #print 'data: %r' % data # dbg
238 240 if self.log_active and data:
239 241 write = self.logfile.write
240 242 if kind=='input':
241 243 if self.timestamp:
242 244 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
243 245 time.localtime()))
244 246 write('%s\n' % data)
245 247 elif kind=='output' and self.log_output:
246 248 odata = '\n'.join(['#[Out]# %s' % s
247 249 for s in data.split('\n')])
248 250 write('%s\n' % odata)
249 251 self.logfile.flush()
250 252
251 253 def logstop(self):
252 254 """Fully stop logging and close log file.
253 255
254 256 In order to start logging again, a new logstart() call needs to be
255 257 made, possibly (though not necessarily) with a new filename, mode and
256 258 other options."""
257 259
258 260 self.logfile.close()
259 261 self.logfile = None
260 262 self.log_active = False
261 263
262 264 # For backwards compatibility, in case anyone was using this.
263 265 close_log = logstop
@@ -1,444 +1,436 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Classes for handling input/output prompts.
3 3
4 4 Authors:
5 5
6 6 * Fernando Perez
7 7 * Brian Granger
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2008-2010 The IPython Development Team
12 12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import os
23 23 import re
24 24 import socket
25 25 import sys
26 26
27 27 from IPython.core import release
28 28 from IPython.external.Itpl import ItplNS
29 29 from IPython.utils import coloransi
30 30
31 31 #-----------------------------------------------------------------------------
32 32 # Color schemes for prompts
33 33 #-----------------------------------------------------------------------------
34 34
35 35 PromptColors = coloransi.ColorSchemeTable()
36 36 InputColors = coloransi.InputTermColors # just a shorthand
37 37 Colors = coloransi.TermColors # just a shorthand
38 38
39 39 PromptColors.add_scheme(coloransi.ColorScheme(
40 40 'NoColor',
41 41 in_prompt = InputColors.NoColor, # Input prompt
42 42 in_number = InputColors.NoColor, # Input prompt number
43 43 in_prompt2 = InputColors.NoColor, # Continuation prompt
44 44 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
45 45
46 46 out_prompt = Colors.NoColor, # Output prompt
47 47 out_number = Colors.NoColor, # Output prompt number
48 48
49 49 normal = Colors.NoColor # color off (usu. Colors.Normal)
50 50 ))
51 51
52 52 # make some schemes as instances so we can copy them for modification easily:
53 53 __PColLinux = coloransi.ColorScheme(
54 54 'Linux',
55 55 in_prompt = InputColors.Green,
56 56 in_number = InputColors.LightGreen,
57 57 in_prompt2 = InputColors.Green,
58 58 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
59 59
60 60 out_prompt = Colors.Red,
61 61 out_number = Colors.LightRed,
62 62
63 63 normal = Colors.Normal
64 64 )
65 65 # Don't forget to enter it into the table!
66 66 PromptColors.add_scheme(__PColLinux)
67 67
68 68 # Slightly modified Linux for light backgrounds
69 69 __PColLightBG = __PColLinux.copy('LightBG')
70 70
71 71 __PColLightBG.colors.update(
72 72 in_prompt = InputColors.Blue,
73 73 in_number = InputColors.LightBlue,
74 74 in_prompt2 = InputColors.Blue
75 75 )
76 76 PromptColors.add_scheme(__PColLightBG)
77 77
78 78 del Colors,InputColors
79 79
80 80 #-----------------------------------------------------------------------------
81 81 # Utilities
82 82 #-----------------------------------------------------------------------------
83 83
84 84 def multiple_replace(dict, text):
85 85 """ Replace in 'text' all occurences of any key in the given
86 86 dictionary by its corresponding value. Returns the new string."""
87 87
88 88 # Function by Xavier Defrang, originally found at:
89 89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90 90
91 91 # Create a regular expression from the dictionary keys
92 92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 93 # For each match, look-up corresponding value in dictionary
94 94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Special characters that can be used in prompt templates, mainly bash-like
98 98 #-----------------------------------------------------------------------------
99 99
100 100 # If $HOME isn't defined (Windows), make it an absurd string so that it can
101 101 # never be expanded out into '~'. Basically anything which can never be a
102 102 # reasonable directory name will do, we just want the $HOME -> '~' operation
103 103 # to become a no-op. We pre-compute $HOME here so it's not done on every
104 104 # prompt call.
105 105
106 106 # FIXME:
107 107
108 108 # - This should be turned into a class which does proper namespace management,
109 109 # since the prompt specials need to be evaluated in a certain namespace.
110 110 # Currently it's just globals, which need to be managed manually by code
111 111 # below.
112 112
113 113 # - I also need to split up the color schemes from the prompt specials
114 114 # somehow. I don't have a clean design for that quite yet.
115 115
116 116 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
117 117
118 118 # We precompute a few more strings here for the prompt_specials, which are
119 119 # fixed once ipython starts. This reduces the runtime overhead of computing
120 120 # prompt strings.
121 121 USER = os.environ.get("USER")
122 122 HOSTNAME = socket.gethostname()
123 123 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
124 124 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
125 125
126 126 prompt_specials_color = {
127 127 # Prompt/history count
128 128 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 129 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
130 130 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
131 131 # can get numbers displayed in whatever color they want.
132 132 r'\N': '${self.cache.prompt_count}',
133 133
134 134 # Prompt/history count, with the actual digits replaced by dots. Used
135 135 # mainly in continuation prompts (prompt_in2)
136 136 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
137 137
138 138 # More robust form of the above expression, that uses the __builtin__
139 139 # module. Note that we can NOT use __builtins__ (note the 's'), because
140 140 # that can either be a dict or a module, and can even mutate at runtime,
141 141 # depending on the context (Python makes no guarantees on it). In
142 142 # contrast, __builtin__ is always a module object, though it must be
143 143 # explicitly imported.
144 144 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
145 145
146 146 # Current working directory
147 147 r'\w': '${os.getcwd()}',
148 148 # Current time
149 149 r'\t' : '${time.strftime("%H:%M:%S")}',
150 150 # Basename of current working directory.
151 151 # (use os.sep to make this portable across OSes)
152 152 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
153 153 # These X<N> are an extension to the normal bash prompts. They return
154 154 # N terms of the path, after replacing $HOME with '~'
155 155 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
156 156 r'\X1': '${self.cwd_filt(1)}',
157 157 r'\X2': '${self.cwd_filt(2)}',
158 158 r'\X3': '${self.cwd_filt(3)}',
159 159 r'\X4': '${self.cwd_filt(4)}',
160 160 r'\X5': '${self.cwd_filt(5)}',
161 161 # Y<N> are similar to X<N>, but they show '~' if it's the directory
162 162 # N+1 in the list. Somewhat like %cN in tcsh.
163 163 r'\Y0': '${self.cwd_filt2(0)}',
164 164 r'\Y1': '${self.cwd_filt2(1)}',
165 165 r'\Y2': '${self.cwd_filt2(2)}',
166 166 r'\Y3': '${self.cwd_filt2(3)}',
167 167 r'\Y4': '${self.cwd_filt2(4)}',
168 168 r'\Y5': '${self.cwd_filt2(5)}',
169 169 # Hostname up to first .
170 170 r'\h': HOSTNAME_SHORT,
171 171 # Full hostname
172 172 r'\H': HOSTNAME,
173 173 # Username of current user
174 174 r'\u': USER,
175 175 # Escaped '\'
176 176 '\\\\': '\\',
177 177 # Newline
178 178 r'\n': '\n',
179 179 # Carriage return
180 180 r'\r': '\r',
181 181 # Release version
182 182 r'\v': release.version,
183 183 # Root symbol ($ or #)
184 184 r'\$': ROOT_SYMBOL,
185 185 }
186 186
187 187 # A copy of the prompt_specials dictionary but with all color escapes removed,
188 188 # so we can correctly compute the prompt length for the auto_rewrite method.
189 189 prompt_specials_nocolor = prompt_specials_color.copy()
190 190 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
191 191 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
192 192
193 193 # Add in all the InputTermColors color escapes as valid prompt characters.
194 194 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
195 195 # with a color name which may begin with a letter used by any other of the
196 196 # allowed specials. This of course means that \\C will never be allowed for
197 197 # anything else.
198 198 input_colors = coloransi.InputTermColors
199 199 for _color in dir(input_colors):
200 200 if _color[0] != '_':
201 201 c_name = r'\C_'+_color
202 202 prompt_specials_color[c_name] = getattr(input_colors,_color)
203 203 prompt_specials_nocolor[c_name] = ''
204 204
205 205 # we default to no color for safety. Note that prompt_specials is a global
206 206 # variable used by all prompt objects.
207 207 prompt_specials = prompt_specials_nocolor
208 208
209 209 #-----------------------------------------------------------------------------
210 210 # More utilities
211 211 #-----------------------------------------------------------------------------
212 212
213 213 def str_safe(arg):
214 214 """Convert to a string, without ever raising an exception.
215 215
216 216 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
217 217 error message."""
218 218
219 219 try:
220 220 out = str(arg)
221 221 except UnicodeError:
222 222 try:
223 223 out = arg.encode('utf_8','replace')
224 224 except Exception,msg:
225 225 # let's keep this little duplication here, so that the most common
226 226 # case doesn't suffer from a double try wrapping.
227 227 out = '<ERROR: %s>' % msg
228 228 except Exception,msg:
229 229 out = '<ERROR: %s>' % msg
230 230 #raise # dbg
231 231 return out
232 232
233 233 #-----------------------------------------------------------------------------
234 234 # Prompt classes
235 235 #-----------------------------------------------------------------------------
236 236
237 237 class BasePrompt(object):
238 238 """Interactive prompt similar to Mathematica's."""
239 239
240 240 def _get_p_template(self):
241 241 return self._p_template
242 242
243 243 def _set_p_template(self,val):
244 244 self._p_template = val
245 245 self.set_p_str()
246 246
247 247 p_template = property(_get_p_template,_set_p_template,
248 248 doc='Template for prompt string creation')
249 249
250 250 def __init__(self, cache, sep, prompt, pad_left=False):
251 251
252 252 # Hack: we access information about the primary prompt through the
253 253 # cache argument. We need this, because we want the secondary prompt
254 254 # to be aligned with the primary one. Color table info is also shared
255 255 # by all prompt classes through the cache. Nice OO spaghetti code!
256 256 self.cache = cache
257 257 self.sep = sep
258 258
259 259 # regexp to count the number of spaces at the end of a prompt
260 260 # expression, useful for prompt auto-rewriting
261 261 self.rspace = re.compile(r'(\s*)$')
262 262 # Flag to left-pad prompt strings to match the length of the primary
263 263 # prompt
264 264 self.pad_left = pad_left
265 265
266 266 # Set template to create each actual prompt (where numbers change).
267 267 # Use a property
268 268 self.p_template = prompt
269 269 self.set_p_str()
270 270
271 271 def set_p_str(self):
272 272 """ Set the interpolating prompt strings.
273 273
274 274 This must be called every time the color settings change, because the
275 275 prompt_specials global may have changed."""
276 276
277 277 import os,time # needed in locals for prompt string handling
278 278 loc = locals()
279 279 try:
280 280 self.p_str = ItplNS('%s%s%s' %
281 281 ('${self.sep}${self.col_p}',
282 282 multiple_replace(prompt_specials, self.p_template),
283 283 '${self.col_norm}'),self.cache.shell.user_ns,loc)
284 284
285 285 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
286 286 self.p_template),
287 287 self.cache.shell.user_ns,loc)
288 288 except:
289 289 print "Illegal prompt template (check $ usage!):",self.p_template
290 290 self.p_str = self.p_template
291 291 self.p_str_nocolor = self.p_template
292 292
293 293 def write(self, msg):
294 294 sys.stdout.write(msg)
295 295 return ''
296 296
297 297 def __str__(self):
298 298 """Return a string form of the prompt.
299 299
300 300 This for is useful for continuation and output prompts, since it is
301 301 left-padded to match lengths with the primary one (if the
302 302 self.pad_left attribute is set)."""
303 303
304 304 out_str = str_safe(self.p_str)
305 305 if self.pad_left:
306 306 # We must find the amount of padding required to match lengths,
307 307 # taking the color escapes (which are invisible on-screen) into
308 308 # account.
309 309 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
310 310 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
311 311 return format % out_str
312 312 else:
313 313 return out_str
314 314
315 315 # these path filters are put in as methods so that we can control the
316 316 # namespace where the prompt strings get evaluated
317 317 def cwd_filt(self, depth):
318 318 """Return the last depth elements of the current working directory.
319 319
320 320 $HOME is always replaced with '~'.
321 321 If depth==0, the full path is returned."""
322 322
323 323 cwd = os.getcwd().replace(HOME,"~")
324 324 out = os.sep.join(cwd.split(os.sep)[-depth:])
325 325 if out:
326 326 return out
327 327 else:
328 328 return os.sep
329 329
330 330 def cwd_filt2(self, depth):
331 331 """Return the last depth elements of the current working directory.
332 332
333 333 $HOME is always replaced with '~'.
334 334 If depth==0, the full path is returned."""
335 335
336 336 full_cwd = os.getcwd()
337 337 cwd = full_cwd.replace(HOME,"~").split(os.sep)
338 338 if '~' in cwd and len(cwd) == depth+1:
339 339 depth += 1
340 340 drivepart = ''
341 341 if sys.platform == 'win32' and len(cwd) > depth:
342 342 drivepart = os.path.splitdrive(full_cwd)[0]
343 343 out = drivepart + '/'.join(cwd[-depth:])
344 344
345 345 if out:
346 346 return out
347 347 else:
348 348 return os.sep
349 349
350 350 def __nonzero__(self):
351 351 """Implement boolean behavior.
352 352
353 353 Checks whether the p_str attribute is non-empty"""
354 354
355 355 return bool(self.p_template)
356 356
357 357
358 358 class Prompt1(BasePrompt):
359 359 """Input interactive prompt similar to Mathematica's."""
360 360
361 361 def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True):
362 362 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
363 363
364 364 def set_colors(self):
365 365 self.set_p_str()
366 366 Colors = self.cache.color_table.active_colors # shorthand
367 367 self.col_p = Colors.in_prompt
368 368 self.col_num = Colors.in_number
369 369 self.col_norm = Colors.in_normal
370 370 # We need a non-input version of these escapes for the '--->'
371 371 # auto-call prompts used in the auto_rewrite() method.
372 372 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
373 373 self.col_norm_ni = Colors.normal
374 374
375 def peek_next_prompt(self):
376 """Get the next prompt, but don't increment the counter."""
377 self.cache.prompt_count += 1
378 next_prompt = str_safe(self.p_str)
379 self.cache.prompt_count -= 1
380 return next_prompt
381
382 375 def __str__(self):
383 self.cache.prompt_count += 1
384 376 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
385 377 return str_safe(self.p_str)
386 378
387 379 def auto_rewrite(self):
388 380 """Return a string of the form '--->' which lines up with the previous
389 381 input string. Useful for systems which re-write the user input when
390 382 handling automatically special syntaxes."""
391 383
392 384 curr = str(self.cache.last_prompt)
393 385 nrspaces = len(self.rspace.search(curr).group())
394 386 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
395 387 ' '*nrspaces,self.col_norm_ni)
396 388
397 389
398 390 class PromptOut(BasePrompt):
399 391 """Output interactive prompt similar to Mathematica's."""
400 392
401 393 def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True):
402 394 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
403 395 if not self.p_template:
404 396 self.__str__ = lambda: ''
405 397
406 398 def set_colors(self):
407 399 self.set_p_str()
408 400 Colors = self.cache.color_table.active_colors # shorthand
409 401 self.col_p = Colors.out_prompt
410 402 self.col_num = Colors.out_number
411 403 self.col_norm = Colors.normal
412 404
413 405
414 406 class Prompt2(BasePrompt):
415 407 """Interactive continuation prompt."""
416 408
417 409 def __init__(self, cache, prompt=' .\\D.: ', pad_left=True):
418 410 self.cache = cache
419 411 self.p_template = prompt
420 412 self.pad_left = pad_left
421 413 self.set_p_str()
422 414
423 415 def set_p_str(self):
424 416 import os,time # needed in locals for prompt string handling
425 417 loc = locals()
426 418 self.p_str = ItplNS('%s%s%s' %
427 419 ('${self.col_p2}',
428 420 multiple_replace(prompt_specials, self.p_template),
429 421 '$self.col_norm'),
430 422 self.cache.shell.user_ns,loc)
431 423 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
432 424 self.p_template),
433 425 self.cache.shell.user_ns,loc)
434 426
435 427 def set_colors(self):
436 428 self.set_p_str()
437 429 Colors = self.cache.color_table.active_colors
438 430 self.col_p2 = Colors.in_prompt2
439 431 self.col_norm = Colors.in_normal
440 432 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
441 433 # updated their prompt_in2 definitions. Remove eventually.
442 434 self.col_p = Colors.out_prompt
443 435 self.col_num = Colors.out_number
444 436
@@ -1,652 +1,657 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Subclass of InteractiveShell for terminal based frontends."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import __builtin__
18 18 import bdb
19 19 from contextlib import nested
20 20 import os
21 21 import re
22 22 import sys
23 23
24 24 from IPython.core.error import TryNext
25 25 from IPython.core.usage import interactive_usage, default_banner
26 26 from IPython.core.inputlist import InputList
27 27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 28 from IPython.lib.inputhook import enable_gui
29 29 from IPython.lib.pylabtools import pylab_activate
30 30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 31 from IPython.utils.process import abbrev_cwd
32 32 from IPython.utils.warn import warn
33 33 from IPython.utils.text import num_ini_spaces
34 34 from IPython.utils.traitlets import Int, Str, CBool
35 35
36 36
37 37 #-----------------------------------------------------------------------------
38 38 # Utilities
39 39 #-----------------------------------------------------------------------------
40 40
41 41
42 42 def get_default_editor():
43 43 try:
44 44 ed = os.environ['EDITOR']
45 45 except KeyError:
46 46 if os.name == 'posix':
47 47 ed = 'vi' # the only one guaranteed to be there!
48 48 else:
49 49 ed = 'notepad' # same in Windows!
50 50 return ed
51 51
52 52
53 53 # store the builtin raw_input globally, and use this always, in case user code
54 54 # overwrites it (like wx.py.PyShell does)
55 55 raw_input_original = raw_input
56 56
57 57
58 58 #-----------------------------------------------------------------------------
59 59 # Main class
60 60 #-----------------------------------------------------------------------------
61 61
62 62
63 63 class TerminalInteractiveShell(InteractiveShell):
64 64
65 65 autoedit_syntax = CBool(False, config=True)
66 66 banner = Str('')
67 67 banner1 = Str(default_banner, config=True)
68 68 banner2 = Str('', config=True)
69 69 confirm_exit = CBool(True, config=True)
70 70 # This display_banner only controls whether or not self.show_banner()
71 71 # is called when mainloop/interact are called. The default is False
72 72 # because for the terminal based application, the banner behavior
73 73 # is controlled by Global.display_banner, which IPythonApp looks at
74 74 # to determine if *it* should call show_banner() by hand or not.
75 75 display_banner = CBool(False) # This isn't configurable!
76 76 embedded = CBool(False)
77 77 embedded_active = CBool(False)
78 78 editor = Str(get_default_editor(), config=True)
79 79 pager = Str('less', config=True)
80 80
81 81 screen_length = Int(0, config=True)
82 82 term_title = CBool(False, config=True)
83 83
84 84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 85 user_global_ns=None, custom_exceptions=((),None),
86 86 usage=None, banner1=None, banner2=None,
87 87 display_banner=None):
88 88
89 89 super(TerminalInteractiveShell, self).__init__(
90 90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 92 )
93 93 self.init_term_title()
94 94 self.init_usage(usage)
95 95 self.init_banner(banner1, banner2, display_banner)
96 96
97 97 #-------------------------------------------------------------------------
98 98 # Things related to the terminal
99 99 #-------------------------------------------------------------------------
100 100
101 101 @property
102 102 def usable_screen_length(self):
103 103 if self.screen_length == 0:
104 104 return 0
105 105 else:
106 106 num_lines_bot = self.separate_in.count('\n')+1
107 107 return self.screen_length - num_lines_bot
108 108
109 109 def init_term_title(self):
110 110 # Enable or disable the terminal title.
111 111 if self.term_title:
112 112 toggle_set_term_title(True)
113 113 set_term_title('IPython: ' + abbrev_cwd())
114 114 else:
115 115 toggle_set_term_title(False)
116 116
117 117 #-------------------------------------------------------------------------
118 118 # Things related to aliases
119 119 #-------------------------------------------------------------------------
120 120
121 121 def init_alias(self):
122 122 # The parent class defines aliases that can be safely used with any
123 123 # frontend.
124 124 super(TerminalInteractiveShell, self).init_alias()
125 125
126 126 # Now define aliases that only make sense on the terminal, because they
127 127 # need direct access to the console in a way that we can't emulate in
128 128 # GUI or web frontend
129 129 if os.name == 'posix':
130 130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
131 131 ('man', 'man')]
132 132 elif os.name == 'nt':
133 133 aliases = [('cls', 'cls')]
134 134
135 135
136 136 for name, cmd in aliases:
137 137 self.alias_manager.define_alias(name, cmd)
138 138
139 139 #-------------------------------------------------------------------------
140 140 # Things related to the banner and usage
141 141 #-------------------------------------------------------------------------
142 142
143 143 def _banner1_changed(self):
144 144 self.compute_banner()
145 145
146 146 def _banner2_changed(self):
147 147 self.compute_banner()
148 148
149 149 def _term_title_changed(self, name, new_value):
150 150 self.init_term_title()
151 151
152 152 def init_banner(self, banner1, banner2, display_banner):
153 153 if banner1 is not None:
154 154 self.banner1 = banner1
155 155 if banner2 is not None:
156 156 self.banner2 = banner2
157 157 if display_banner is not None:
158 158 self.display_banner = display_banner
159 159 self.compute_banner()
160 160
161 161 def show_banner(self, banner=None):
162 162 if banner is None:
163 163 banner = self.banner
164 164 self.write(banner)
165 165
166 166 def compute_banner(self):
167 167 self.banner = self.banner1
168 168 if self.profile:
169 169 self.banner += '\nIPython profile: %s\n' % self.profile
170 170 if self.banner2:
171 171 self.banner += '\n' + self.banner2
172 172
173 173 def init_usage(self, usage=None):
174 174 if usage is None:
175 175 self.usage = interactive_usage
176 176 else:
177 177 self.usage = usage
178 178
179 179 #-------------------------------------------------------------------------
180 180 # Mainloop and code execution logic
181 181 #-------------------------------------------------------------------------
182 182
183 183 def mainloop(self, display_banner=None):
184 184 """Start the mainloop.
185 185
186 186 If an optional banner argument is given, it will override the
187 187 internally created default banner.
188 188 """
189 189
190 190 with nested(self.builtin_trap, self.display_trap):
191 191
192 192 # if you run stuff with -c <cmd>, raw hist is not updated
193 193 # ensure that it's in sync
194 194 if len(self.input_hist) != len (self.input_hist_raw):
195 195 self.input_hist_raw = InputList(self.input_hist)
196 196
197 197 while 1:
198 198 try:
199 199 self.interact(display_banner=display_banner)
200 200 #self.interact_with_readline()
201 201 # XXX for testing of a readline-decoupled repl loop, call
202 202 # interact_with_readline above
203 203 break
204 204 except KeyboardInterrupt:
205 205 # this should not be necessary, but KeyboardInterrupt
206 206 # handling seems rather unpredictable...
207 207 self.write("\nKeyboardInterrupt in interact()\n")
208 208
209 209 def interact(self, display_banner=None):
210 210 """Closely emulate the interactive Python console."""
211 211
212 212 # batch run -> do not interact
213 213 if self.exit_now:
214 214 return
215 215
216 216 if display_banner is None:
217 217 display_banner = self.display_banner
218 218 if display_banner:
219 219 self.show_banner()
220 220
221 221 more = 0
222 222
223 223 # Mark activity in the builtins
224 224 __builtin__.__dict__['__IPYTHON__active'] += 1
225 225
226 226 if self.has_readline:
227 227 self.readline_startup_hook(self.pre_readline)
228 228 # exit_now is set by a call to %Exit or %Quit, through the
229 229 # ask_exit callback.
230
231 # Before showing any prompts, if the counter is at zero, we execute an
232 # empty line to ensure the user only sees prompts starting at one.
233 if self.execution_count == 0:
234 self.push_line('\n')
230 235
231 236 while not self.exit_now:
232 237 self.hooks.pre_prompt_hook()
233 238 if more:
234 239 try:
235 240 prompt = self.hooks.generate_prompt(True)
236 241 except:
237 242 self.showtraceback()
238 243 if self.autoindent:
239 244 self.rl_do_indent = True
240 245
241 246 else:
242 247 try:
243 248 prompt = self.hooks.generate_prompt(False)
244 249 except:
245 250 self.showtraceback()
246 251 try:
247 252 line = self.raw_input(prompt, more)
248 253 if self.exit_now:
249 254 # quick exit on sys.std[in|out] close
250 255 break
251 256 if self.autoindent:
252 257 self.rl_do_indent = False
253 258
254 259 except KeyboardInterrupt:
255 260 #double-guard against keyboardinterrupts during kbdint handling
256 261 try:
257 262 self.write('\nKeyboardInterrupt\n')
258 263 self.resetbuffer()
259 264 # keep cache in sync with the prompt counter:
260 265 self.displayhook.prompt_count -= 1
261 266
262 267 if self.autoindent:
263 268 self.indent_current_nsp = 0
264 269 more = 0
265 270 except KeyboardInterrupt:
266 271 pass
267 272 except EOFError:
268 273 if self.autoindent:
269 274 self.rl_do_indent = False
270 275 if self.has_readline:
271 276 self.readline_startup_hook(None)
272 277 self.write('\n')
273 278 self.exit()
274 279 except bdb.BdbQuit:
275 280 warn('The Python debugger has exited with a BdbQuit exception.\n'
276 281 'Because of how pdb handles the stack, it is impossible\n'
277 282 'for IPython to properly format this particular exception.\n'
278 283 'IPython will resume normal operation.')
279 284 except:
280 285 # exceptions here are VERY RARE, but they can be triggered
281 286 # asynchronously by signal handlers, for example.
282 287 self.showtraceback()
283 288 else:
284 289 more = self.push_line(line)
285 290 if (self.SyntaxTB.last_syntax_error and
286 291 self.autoedit_syntax):
287 292 self.edit_syntax_error()
288 293
289 294 # We are off again...
290 295 __builtin__.__dict__['__IPYTHON__active'] -= 1
291 296
292 297 # Turn off the exit flag, so the mainloop can be restarted if desired
293 298 self.exit_now = False
294 299
295 300 def raw_input(self,prompt='',continue_prompt=False):
296 301 """Write a prompt and read a line.
297 302
298 303 The returned line does not include the trailing newline.
299 304 When the user enters the EOF key sequence, EOFError is raised.
300 305
301 306 Optional inputs:
302 307
303 308 - prompt(''): a string to be printed to prompt the user.
304 309
305 310 - continue_prompt(False): whether this line is the first one or a
306 311 continuation in a sequence of inputs.
307 312 """
308 313 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
309 314
310 315 # Code run by the user may have modified the readline completer state.
311 316 # We must ensure that our completer is back in place.
312 317
313 318 if self.has_readline:
314 319 self.set_readline_completer()
315 320
316 321 try:
317 322 line = raw_input_original(prompt).decode(self.stdin_encoding)
318 323 except ValueError:
319 324 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
320 325 " or sys.stdout.close()!\nExiting IPython!")
321 326 self.ask_exit()
322 327 return ""
323 328
324 329 # Try to be reasonably smart about not re-indenting pasted input more
325 330 # than necessary. We do this by trimming out the auto-indent initial
326 331 # spaces, if the user's actual input started itself with whitespace.
327 332 #debugx('self.buffer[-1]')
328 333
329 334 if self.autoindent:
330 335 if num_ini_spaces(line) > self.indent_current_nsp:
331 336 line = line[self.indent_current_nsp:]
332 337 self.indent_current_nsp = 0
333 338
334 339 # store the unfiltered input before the user has any chance to modify
335 340 # it.
336 341 if line.strip():
337 342 if continue_prompt:
338 343 self.input_hist_raw[-1] += '%s\n' % line
339 344 if self.has_readline and self.readline_use:
340 345 try:
341 346 histlen = self.readline.get_current_history_length()
342 347 if histlen > 1:
343 348 newhist = self.input_hist_raw[-1].rstrip()
344 349 self.readline.remove_history_item(histlen-1)
345 350 self.readline.replace_history_item(histlen-2,
346 351 newhist.encode(self.stdin_encoding))
347 352 except AttributeError:
348 353 pass # re{move,place}_history_item are new in 2.4.
349 354 else:
350 355 self.input_hist_raw.append('%s\n' % line)
351 356 # only entries starting at first column go to shadow history
352 357 if line.lstrip() == line:
353 358 self.shadowhist.add(line.strip())
354 359 elif not continue_prompt:
355 360 self.input_hist_raw.append('\n')
356 361 try:
357 362 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
358 363 except:
359 364 # blanket except, in case a user-defined prefilter crashes, so it
360 365 # can't take all of ipython with it.
361 366 self.showtraceback()
362 367 return ''
363 368 else:
364 369 return lineout
365 370
366 371 # TODO: The following three methods are an early attempt to refactor
367 372 # the main code execution logic. We don't use them, but they may be
368 373 # helpful when we refactor the code execution logic further.
369 374 # def interact_prompt(self):
370 375 # """ Print the prompt (in read-eval-print loop)
371 376 #
372 377 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
373 378 # used in standard IPython flow.
374 379 # """
375 380 # if self.more:
376 381 # try:
377 382 # prompt = self.hooks.generate_prompt(True)
378 383 # except:
379 384 # self.showtraceback()
380 385 # if self.autoindent:
381 386 # self.rl_do_indent = True
382 387 #
383 388 # else:
384 389 # try:
385 390 # prompt = self.hooks.generate_prompt(False)
386 391 # except:
387 392 # self.showtraceback()
388 393 # self.write(prompt)
389 394 #
390 395 # def interact_handle_input(self,line):
391 396 # """ Handle the input line (in read-eval-print loop)
392 397 #
393 398 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
394 399 # used in standard IPython flow.
395 400 # """
396 401 # if line.lstrip() == line:
397 402 # self.shadowhist.add(line.strip())
398 403 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
399 404 #
400 405 # if line.strip():
401 406 # if self.more:
402 407 # self.input_hist_raw[-1] += '%s\n' % line
403 408 # else:
404 409 # self.input_hist_raw.append('%s\n' % line)
405 410 #
406 411 #
407 412 # self.more = self.push_line(lineout)
408 413 # if (self.SyntaxTB.last_syntax_error and
409 414 # self.autoedit_syntax):
410 415 # self.edit_syntax_error()
411 416 #
412 417 # def interact_with_readline(self):
413 418 # """ Demo of using interact_handle_input, interact_prompt
414 419 #
415 420 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
416 421 # it should work like this.
417 422 # """
418 423 # self.readline_startup_hook(self.pre_readline)
419 424 # while not self.exit_now:
420 425 # self.interact_prompt()
421 426 # if self.more:
422 427 # self.rl_do_indent = True
423 428 # else:
424 429 # self.rl_do_indent = False
425 430 # line = raw_input_original().decode(self.stdin_encoding)
426 431 # self.interact_handle_input(line)
427 432
428 433 #-------------------------------------------------------------------------
429 434 # Methods to support auto-editing of SyntaxErrors.
430 435 #-------------------------------------------------------------------------
431 436
432 437 def edit_syntax_error(self):
433 438 """The bottom half of the syntax error handler called in the main loop.
434 439
435 440 Loop until syntax error is fixed or user cancels.
436 441 """
437 442
438 443 while self.SyntaxTB.last_syntax_error:
439 444 # copy and clear last_syntax_error
440 445 err = self.SyntaxTB.clear_err_state()
441 446 if not self._should_recompile(err):
442 447 return
443 448 try:
444 449 # may set last_syntax_error again if a SyntaxError is raised
445 450 self.safe_execfile(err.filename,self.user_ns)
446 451 except:
447 452 self.showtraceback()
448 453 else:
449 454 try:
450 455 f = file(err.filename)
451 456 try:
452 457 # This should be inside a display_trap block and I
453 458 # think it is.
454 459 sys.displayhook(f.read())
455 460 finally:
456 461 f.close()
457 462 except:
458 463 self.showtraceback()
459 464
460 465 def _should_recompile(self,e):
461 466 """Utility routine for edit_syntax_error"""
462 467
463 468 if e.filename in ('<ipython console>','<input>','<string>',
464 469 '<console>','<BackgroundJob compilation>',
465 470 None):
466 471
467 472 return False
468 473 try:
469 474 if (self.autoedit_syntax and
470 475 not self.ask_yes_no('Return to editor to correct syntax error? '
471 476 '[Y/n] ','y')):
472 477 return False
473 478 except EOFError:
474 479 return False
475 480
476 481 def int0(x):
477 482 try:
478 483 return int(x)
479 484 except TypeError:
480 485 return 0
481 486 # always pass integer line and offset values to editor hook
482 487 try:
483 488 self.hooks.fix_error_editor(e.filename,
484 489 int0(e.lineno),int0(e.offset),e.msg)
485 490 except TryNext:
486 491 warn('Could not open editor')
487 492 return False
488 493 return True
489 494
490 495 #-------------------------------------------------------------------------
491 496 # Things related to GUI support and pylab
492 497 #-------------------------------------------------------------------------
493 498
494 499 def enable_pylab(self, gui=None):
495 500 """Activate pylab support at runtime.
496 501
497 502 This turns on support for matplotlib, preloads into the interactive
498 503 namespace all of numpy and pylab, and configures IPython to correcdtly
499 504 interact with the GUI event loop. The GUI backend to be used can be
500 505 optionally selected with the optional :param:`gui` argument.
501 506
502 507 Parameters
503 508 ----------
504 509 gui : optional, string
505 510
506 511 If given, dictates the choice of matplotlib GUI backend to use
507 512 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
508 513 'gtk'), otherwise we use the default chosen by matplotlib (as
509 514 dictated by the matplotlib build-time options plus the user's
510 515 matplotlibrc configuration file).
511 516 """
512 517 # We want to prevent the loading of pylab to pollute the user's
513 518 # namespace as shown by the %who* magics, so we execute the activation
514 519 # code in an empty namespace, and we update *both* user_ns and
515 520 # user_ns_hidden with this information.
516 521 ns = {}
517 522 gui = pylab_activate(ns, gui)
518 523 self.user_ns.update(ns)
519 524 self.user_ns_hidden.update(ns)
520 525 # Now we must activate the gui pylab wants to use, and fix %run to take
521 526 # plot updates into account
522 527 enable_gui(gui)
523 528 self.magic_run = self._pylab_magic_run
524 529
525 530 #-------------------------------------------------------------------------
526 531 # Things related to exiting
527 532 #-------------------------------------------------------------------------
528 533
529 534 def ask_exit(self):
530 535 """ Ask the shell to exit. Can be overiden and used as a callback. """
531 536 self.exit_now = True
532 537
533 538 def exit(self):
534 539 """Handle interactive exit.
535 540
536 541 This method calls the ask_exit callback."""
537 542 if self.confirm_exit:
538 543 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
539 544 self.ask_exit()
540 545 else:
541 546 self.ask_exit()
542 547
543 548 #------------------------------------------------------------------------
544 549 # Magic overrides
545 550 #------------------------------------------------------------------------
546 551 # Once the base class stops inheriting from magic, this code needs to be
547 552 # moved into a separate machinery as well. For now, at least isolate here
548 553 # the magics which this class needs to implement differently from the base
549 554 # class, or that are unique to it.
550 555
551 556 def magic_autoindent(self, parameter_s = ''):
552 557 """Toggle autoindent on/off (if available)."""
553 558
554 559 self.shell.set_autoindent()
555 560 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
556 561
557 562 def magic_cpaste(self, parameter_s=''):
558 563 """Paste & execute a pre-formatted code block from clipboard.
559 564
560 565 You must terminate the block with '--' (two minus-signs) alone on the
561 566 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
562 567 is the new sentinel for this operation)
563 568
564 569 The block is dedented prior to execution to enable execution of method
565 570 definitions. '>' and '+' characters at the beginning of a line are
566 571 ignored, to allow pasting directly from e-mails, diff files and
567 572 doctests (the '...' continuation prompt is also stripped). The
568 573 executed block is also assigned to variable named 'pasted_block' for
569 574 later editing with '%edit pasted_block'.
570 575
571 576 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
572 577 This assigns the pasted block to variable 'foo' as string, without
573 578 dedenting or executing it (preceding >>> and + is still stripped)
574 579
575 580 '%cpaste -r' re-executes the block previously entered by cpaste.
576 581
577 582 Do not be alarmed by garbled output on Windows (it's a readline bug).
578 583 Just press enter and type -- (and press enter again) and the block
579 584 will be what was just pasted.
580 585
581 586 IPython statements (magics, shell escapes) are not supported (yet).
582 587
583 588 See also
584 589 --------
585 590 paste: automatically pull code from clipboard.
586 591 """
587 592
588 593 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
589 594 par = args.strip()
590 595 if opts.has_key('r'):
591 596 self._rerun_pasted()
592 597 return
593 598
594 599 sentinel = opts.get('s','--')
595 600
596 601 block = self._strip_pasted_lines_for_code(
597 602 self._get_pasted_lines(sentinel))
598 603
599 604 self._execute_block(block, par)
600 605
601 606 def magic_paste(self, parameter_s=''):
602 607 """Paste & execute a pre-formatted code block from clipboard.
603 608
604 609 The text is pulled directly from the clipboard without user
605 610 intervention and printed back on the screen before execution (unless
606 611 the -q flag is given to force quiet mode).
607 612
608 613 The block is dedented prior to execution to enable execution of method
609 614 definitions. '>' and '+' characters at the beginning of a line are
610 615 ignored, to allow pasting directly from e-mails, diff files and
611 616 doctests (the '...' continuation prompt is also stripped). The
612 617 executed block is also assigned to variable named 'pasted_block' for
613 618 later editing with '%edit pasted_block'.
614 619
615 620 You can also pass a variable name as an argument, e.g. '%paste foo'.
616 621 This assigns the pasted block to variable 'foo' as string, without
617 622 dedenting or executing it (preceding >>> and + is still stripped)
618 623
619 624 Options
620 625 -------
621 626
622 627 -r: re-executes the block previously entered by cpaste.
623 628
624 629 -q: quiet mode: do not echo the pasted text back to the terminal.
625 630
626 631 IPython statements (magics, shell escapes) are not supported (yet).
627 632
628 633 See also
629 634 --------
630 635 cpaste: manually paste code into terminal until you mark its end.
631 636 """
632 637 opts,args = self.parse_options(parameter_s,'rq',mode='string')
633 638 par = args.strip()
634 639 if opts.has_key('r'):
635 640 self._rerun_pasted()
636 641 return
637 642
638 643 text = self.shell.hooks.clipboard_get()
639 644 block = self._strip_pasted_lines_for_code(text.splitlines())
640 645
641 646 # By default, echo back to terminal unless quiet mode is requested
642 647 if not opts.has_key('q'):
643 648 write = self.shell.write
644 649 write(self.shell.pycolorize(block))
645 650 if not block.endswith('\n'):
646 651 write('\n')
647 652 write("## -- End pasted text --\n")
648 653
649 654 self._execute_block(block, par)
650 655
651 656
652 657 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,626 +1,627 b''
1 1 #!/usr/bin/env python
2 2 """A simple interactive kernel that talks to a frontend over 0MQ.
3 3
4 4 Things to do:
5 5
6 6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 7 call set_parent on all the PUB objects with the message about to be executed.
8 8 * Implement random port and security key logic.
9 9 * Implement control messages.
10 10 * Implement event loop and poll version.
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Standard library imports.
19 19 import __builtin__
20 20 import atexit
21 21 import sys
22 22 import time
23 23 import traceback
24 24
25 25 # System library imports.
26 26 import zmq
27 27
28 28 # Local imports.
29 29 from IPython.config.configurable import Configurable
30 30 from IPython.utils import io
31 31 from IPython.utils.jsonutil import json_clean
32 32 from IPython.lib import pylabtools
33 33 from IPython.utils.traitlets import Instance, Float
34 34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 35 start_kernel)
36 36 from iostream import OutStream
37 37 from session import Session, Message
38 38 from zmqshell import ZMQInteractiveShell
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Main kernel class
42 42 #-----------------------------------------------------------------------------
43 43
44 44 class Kernel(Configurable):
45 45
46 46 #---------------------------------------------------------------------------
47 47 # Kernel interface
48 48 #---------------------------------------------------------------------------
49 49
50 50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 51 session = Instance(Session)
52 52 reply_socket = Instance('zmq.Socket')
53 53 pub_socket = Instance('zmq.Socket')
54 54 req_socket = Instance('zmq.Socket')
55 55
56 56 # Private interface
57 57
58 58 # Time to sleep after flushing the stdout/err buffers in each execute
59 59 # cycle. While this introduces a hard limit on the minimal latency of the
60 60 # execute cycle, it helps prevent output synchronization problems for
61 61 # clients.
62 62 # Units are in seconds. The minimum zmq latency on local host is probably
63 63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 64 # a little if it's not enough after more interactive testing.
65 65 _execute_sleep = Float(0.0005, config=True)
66 66
67 67 # Frequency of the kernel's event loop.
68 68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 69 # adapt to milliseconds.
70 70 _poll_interval = Float(0.05, config=True)
71 71
72 72 # If the shutdown was requested over the network, we leave here the
73 73 # necessary reply message so it can be sent by our registered atexit
74 74 # handler. This ensures that the reply is only sent to clients truly at
75 75 # the end of our shutdown process (which happens after the underlying
76 76 # IPython shell's own shutdown).
77 77 _shutdown_message = None
78 78
79 79 # This is a dict of port number that the kernel is listening on. It is set
80 80 # by record_ports and used by connect_request.
81 81 _recorded_ports = None
82 82
83 83 def __init__(self, **kwargs):
84 84 super(Kernel, self).__init__(**kwargs)
85 85
86 86 # Before we even start up the shell, register *first* our exit handlers
87 87 # so they come before the shell's
88 88 atexit.register(self._at_shutdown)
89 89
90 90 # Initialize the InteractiveShell subclass
91 91 self.shell = ZMQInteractiveShell.instance()
92 92 self.shell.displayhook.session = self.session
93 93 self.shell.displayhook.pub_socket = self.pub_socket
94 94
95 95 # TMP - hack while developing
96 96 self.shell._reply_content = None
97 97
98 98 # Build dict of handlers for message types
99 99 msg_types = [ 'execute_request', 'complete_request',
100 100 'object_info_request', 'history_request',
101 101 'connect_request', 'shutdown_request']
102 102 self.handlers = {}
103 103 for msg_type in msg_types:
104 104 self.handlers[msg_type] = getattr(self, msg_type)
105 105
106 106 def do_one_iteration(self):
107 107 """Do one iteration of the kernel's evaluation loop.
108 108 """
109 109 try:
110 110 ident = self.reply_socket.recv(zmq.NOBLOCK)
111 111 except zmq.ZMQError, e:
112 112 if e.errno == zmq.EAGAIN:
113 113 return
114 114 else:
115 115 raise
116 116 # FIXME: Bug in pyzmq/zmq?
117 117 # assert self.reply_socket.rcvmore(), "Missing message part."
118 118 msg = self.reply_socket.recv_json()
119 119
120 120 # Print some info about this message and leave a '--->' marker, so it's
121 121 # easier to trace visually the message chain when debugging. Each
122 122 # handler prints its message at the end.
123 123 # Eventually we'll move these from stdout to a logger.
124 124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
125 125 io.raw_print(' Content: ', msg['content'],
126 126 '\n --->\n ', sep='', end='')
127 127
128 128 # Find and call actual handler for message
129 129 handler = self.handlers.get(msg['msg_type'], None)
130 130 if handler is None:
131 131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
132 132 else:
133 133 handler(ident, msg)
134 134
135 135 # Check whether we should exit, in case the incoming message set the
136 136 # exit flag on
137 137 if self.shell.exit_now:
138 138 io.raw_print('\nExiting IPython kernel...')
139 139 # We do a normal, clean exit, which allows any actions registered
140 140 # via atexit (such as history saving) to take place.
141 141 sys.exit(0)
142 142
143 143
144 144 def start(self):
145 145 """ Start the kernel main loop.
146 146 """
147 147 while True:
148 148 time.sleep(self._poll_interval)
149 149 self.do_one_iteration()
150 150
151 151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
152 152 """Record the ports that this kernel is using.
153 153
154 154 The creator of the Kernel instance must call this methods if they
155 155 want the :meth:`connect_request` method to return the port numbers.
156 156 """
157 157 self._recorded_ports = {
158 158 'xrep_port' : xrep_port,
159 159 'pub_port' : pub_port,
160 160 'req_port' : req_port,
161 161 'hb_port' : hb_port
162 162 }
163 163
164 164 #---------------------------------------------------------------------------
165 165 # Kernel request handlers
166 166 #---------------------------------------------------------------------------
167 167
168 168 def _publish_pyin(self, code, parent):
169 169 """Publish the code request on the pyin stream."""
170 170
171 171 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
172 172 self.pub_socket.send_json(pyin_msg)
173 173
174 174 def execute_request(self, ident, parent):
175 175
176 176 status_msg = self.session.msg(
177 177 u'status',
178 178 {u'execution_state':u'busy'},
179 179 parent=parent
180 180 )
181 181 self.pub_socket.send_json(status_msg)
182 182
183 183 try:
184 184 content = parent[u'content']
185 185 code = content[u'code']
186 186 silent = content[u'silent']
187 187 except:
188 188 io.raw_print_err("Got bad msg: ")
189 189 io.raw_print_err(Message(parent))
190 190 return
191 191
192 192 shell = self.shell # we'll need this a lot here
193 193
194 194 # Replace raw_input. Note that is not sufficient to replace
195 195 # raw_input in the user namespace.
196 196 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
197 197 __builtin__.raw_input = raw_input
198 198
199 199 # Set the parent message of the display hook and out streams.
200 200 shell.displayhook.set_parent(parent)
201 201 sys.stdout.set_parent(parent)
202 202 sys.stderr.set_parent(parent)
203 203
204 204 # Re-broadcast our input for the benefit of listening clients, and
205 205 # start computing output
206 206 if not silent:
207 207 self._publish_pyin(code, parent)
208 208
209 209 reply_content = {}
210 210 try:
211 211 if silent:
212 212 # runcode uses 'exec' mode, so no displayhook will fire, and it
213 213 # doesn't call logging or history manipulations. Print
214 214 # statements in that code will obviously still execute.
215 215 shell.runcode(code)
216 216 else:
217 217 # FIXME: runlines calls the exception handler itself.
218 218 shell._reply_content = None
219 219
220 220 # For now leave this here until we're sure we can stop using it
221 221 #shell.runlines(code)
222 222
223 223 # Experimental: cell mode! Test more before turning into
224 224 # default and removing the hacks around runlines.
225 225 shell.run_cell(code)
226 226 except:
227 227 status = u'error'
228 228 # FIXME: this code right now isn't being used yet by default,
229 229 # because the runlines() call above directly fires off exception
230 230 # reporting. This code, therefore, is only active in the scenario
231 231 # where runlines itself has an unhandled exception. We need to
232 232 # uniformize this, for all exception construction to come from a
233 233 # single location in the codbase.
234 234 etype, evalue, tb = sys.exc_info()
235 235 tb_list = traceback.format_exception(etype, evalue, tb)
236 236 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
237 237 else:
238 238 status = u'ok'
239 239
240 240 reply_content[u'status'] = status
241 # Compute the execution counter so clients can display prompts
242 reply_content['execution_count'] = shell.displayhook.prompt_count
241
242 # Return the execution counter so clients can display prompts
243 reply_content['execution_count'] = shell.execution_count
243 244
244 245 # FIXME - fish exception info out of shell, possibly left there by
245 246 # runlines. We'll need to clean up this logic later.
246 247 if shell._reply_content is not None:
247 248 reply_content.update(shell._reply_content)
248 249
249 250 # At this point, we can tell whether the main code execution succeeded
250 251 # or not. If it did, we proceed to evaluate user_variables/expressions
251 252 if reply_content['status'] == 'ok':
252 253 reply_content[u'user_variables'] = \
253 254 shell.user_variables(content[u'user_variables'])
254 255 reply_content[u'user_expressions'] = \
255 256 shell.user_expressions(content[u'user_expressions'])
256 257 else:
257 258 # If there was an error, don't even try to compute variables or
258 259 # expressions
259 260 reply_content[u'user_variables'] = {}
260 261 reply_content[u'user_expressions'] = {}
261 262
262 263 # Payloads should be retrieved regardless of outcome, so we can both
263 264 # recover partial output (that could have been generated early in a
264 265 # block, before an error) and clear the payload system always.
265 266 reply_content[u'payload'] = shell.payload_manager.read_payload()
266 267 # Be agressive about clearing the payload because we don't want
267 268 # it to sit in memory until the next execute_request comes in.
268 269 shell.payload_manager.clear_payload()
269 270
270 271 # Send the reply.
271 272 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
272 273 io.raw_print(reply_msg)
273 274
274 275 # Flush output before sending the reply.
275 276 sys.stdout.flush()
276 277 sys.stderr.flush()
277 278 # FIXME: on rare occasions, the flush doesn't seem to make it to the
278 279 # clients... This seems to mitigate the problem, but we definitely need
279 280 # to better understand what's going on.
280 281 if self._execute_sleep:
281 282 time.sleep(self._execute_sleep)
282 283
283 284 self.reply_socket.send(ident, zmq.SNDMORE)
284 285 self.reply_socket.send_json(reply_msg)
285 286 if reply_msg['content']['status'] == u'error':
286 287 self._abort_queue()
287 288
288 289 status_msg = self.session.msg(
289 290 u'status',
290 291 {u'execution_state':u'idle'},
291 292 parent=parent
292 293 )
293 294 self.pub_socket.send_json(status_msg)
294 295
295 296 def complete_request(self, ident, parent):
296 297 txt, matches = self._complete(parent)
297 298 matches = {'matches' : matches,
298 299 'matched_text' : txt,
299 300 'status' : 'ok'}
300 301 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
301 302 matches, parent, ident)
302 303 io.raw_print(completion_msg)
303 304
304 305 def object_info_request(self, ident, parent):
305 306 object_info = self.shell.object_inspect(parent['content']['oname'])
306 307 # Before we send this object over, we scrub it for JSON usage
307 308 oinfo = json_clean(object_info)
308 309 msg = self.session.send(self.reply_socket, 'object_info_reply',
309 310 oinfo, parent, ident)
310 311 io.raw_print(msg)
311 312
312 313 def history_request(self, ident, parent):
313 314 output = parent['content']['output']
314 315 index = parent['content']['index']
315 316 raw = parent['content']['raw']
316 317 hist = self.shell.get_history(index=index, raw=raw, output=output)
317 318 content = {'history' : hist}
318 319 msg = self.session.send(self.reply_socket, 'history_reply',
319 320 content, parent, ident)
320 321 io.raw_print(msg)
321 322
322 323 def connect_request(self, ident, parent):
323 324 if self._recorded_ports is not None:
324 325 content = self._recorded_ports.copy()
325 326 else:
326 327 content = {}
327 328 msg = self.session.send(self.reply_socket, 'connect_reply',
328 329 content, parent, ident)
329 330 io.raw_print(msg)
330 331
331 332 def shutdown_request(self, ident, parent):
332 333 self.shell.exit_now = True
333 334 self._shutdown_message = self.session.msg(u'shutdown_reply', {}, parent)
334 335 sys.exit(0)
335 336
336 337 #---------------------------------------------------------------------------
337 338 # Protected interface
338 339 #---------------------------------------------------------------------------
339 340
340 341 def _abort_queue(self):
341 342 while True:
342 343 try:
343 344 ident = self.reply_socket.recv(zmq.NOBLOCK)
344 345 except zmq.ZMQError, e:
345 346 if e.errno == zmq.EAGAIN:
346 347 break
347 348 else:
348 349 assert self.reply_socket.rcvmore(), \
349 350 "Unexpected missing message part."
350 351 msg = self.reply_socket.recv_json()
351 352 io.raw_print("Aborting:\n", Message(msg))
352 353 msg_type = msg['msg_type']
353 354 reply_type = msg_type.split('_')[0] + '_reply'
354 355 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
355 356 io.raw_print(reply_msg)
356 357 self.reply_socket.send(ident,zmq.SNDMORE)
357 358 self.reply_socket.send_json(reply_msg)
358 359 # We need to wait a bit for requests to come in. This can probably
359 360 # be set shorter for true asynchronous clients.
360 361 time.sleep(0.1)
361 362
362 363 def _raw_input(self, prompt, ident, parent):
363 364 # Flush output before making the request.
364 365 sys.stderr.flush()
365 366 sys.stdout.flush()
366 367
367 368 # Send the input request.
368 369 content = dict(prompt=prompt)
369 370 msg = self.session.msg(u'input_request', content, parent)
370 371 self.req_socket.send_json(msg)
371 372
372 373 # Await a response.
373 374 reply = self.req_socket.recv_json()
374 375 try:
375 376 value = reply['content']['value']
376 377 except:
377 378 io.raw_print_err("Got bad raw_input reply: ")
378 379 io.raw_print_err(Message(parent))
379 380 value = ''
380 381 return value
381 382
382 383 def _complete(self, msg):
383 384 c = msg['content']
384 385 try:
385 386 cpos = int(c['cursor_pos'])
386 387 except:
387 388 # If we don't get something that we can convert to an integer, at
388 389 # least attempt the completion guessing the cursor is at the end of
389 390 # the text, if there's any, and otherwise of the line
390 391 cpos = len(c['text'])
391 392 if cpos==0:
392 393 cpos = len(c['line'])
393 394 return self.shell.complete(c['text'], c['line'], cpos)
394 395
395 396 def _object_info(self, context):
396 397 symbol, leftover = self._symbol_from_context(context)
397 398 if symbol is not None and not leftover:
398 399 doc = getattr(symbol, '__doc__', '')
399 400 else:
400 401 doc = ''
401 402 object_info = dict(docstring = doc)
402 403 return object_info
403 404
404 405 def _symbol_from_context(self, context):
405 406 if not context:
406 407 return None, context
407 408
408 409 base_symbol_string = context[0]
409 410 symbol = self.shell.user_ns.get(base_symbol_string, None)
410 411 if symbol is None:
411 412 symbol = __builtin__.__dict__.get(base_symbol_string, None)
412 413 if symbol is None:
413 414 return None, context
414 415
415 416 context = context[1:]
416 417 for i, name in enumerate(context):
417 418 new_symbol = getattr(symbol, name, None)
418 419 if new_symbol is None:
419 420 return symbol, context[i:]
420 421 else:
421 422 symbol = new_symbol
422 423
423 424 return symbol, []
424 425
425 426 def _at_shutdown(self):
426 427 """Actions taken at shutdown by the kernel, called by python's atexit.
427 428 """
428 429 # io.rprint("Kernel at_shutdown") # dbg
429 430 if self._shutdown_message is not None:
430 431 self.reply_socket.send_json(self._shutdown_message)
431 432 io.raw_print(self._shutdown_message)
432 433 # A very short sleep to give zmq time to flush its message buffers
433 434 # before Python truly shuts down.
434 435 time.sleep(0.01)
435 436
436 437
437 438 class QtKernel(Kernel):
438 439 """A Kernel subclass with Qt support."""
439 440
440 441 def start(self):
441 442 """Start a kernel with QtPy4 event loop integration."""
442 443
443 444 from PyQt4 import QtCore
444 445 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
445 446
446 447 self.app = get_app_qt4([" "])
447 448 self.app.setQuitOnLastWindowClosed(False)
448 449 self.timer = QtCore.QTimer()
449 450 self.timer.timeout.connect(self.do_one_iteration)
450 451 # Units for the timer are in milliseconds
451 452 self.timer.start(1000*self._poll_interval)
452 453 start_event_loop_qt4(self.app)
453 454
454 455
455 456 class WxKernel(Kernel):
456 457 """A Kernel subclass with Wx support."""
457 458
458 459 def start(self):
459 460 """Start a kernel with wx event loop support."""
460 461
461 462 import wx
462 463 from IPython.lib.guisupport import start_event_loop_wx
463 464
464 465 doi = self.do_one_iteration
465 466 # Wx uses milliseconds
466 467 poll_interval = int(1000*self._poll_interval)
467 468
468 469 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
469 470 # We make the Frame hidden when we create it in the main app below.
470 471 class TimerFrame(wx.Frame):
471 472 def __init__(self, func):
472 473 wx.Frame.__init__(self, None, -1)
473 474 self.timer = wx.Timer(self)
474 475 # Units for the timer are in milliseconds
475 476 self.timer.Start(poll_interval)
476 477 self.Bind(wx.EVT_TIMER, self.on_timer)
477 478 self.func = func
478 479
479 480 def on_timer(self, event):
480 481 self.func()
481 482
482 483 # We need a custom wx.App to create our Frame subclass that has the
483 484 # wx.Timer to drive the ZMQ event loop.
484 485 class IPWxApp(wx.App):
485 486 def OnInit(self):
486 487 self.frame = TimerFrame(doi)
487 488 self.frame.Show(False)
488 489 return True
489 490
490 491 # The redirect=False here makes sure that wx doesn't replace
491 492 # sys.stdout/stderr with its own classes.
492 493 self.app = IPWxApp(redirect=False)
493 494 start_event_loop_wx(self.app)
494 495
495 496
496 497 class TkKernel(Kernel):
497 498 """A Kernel subclass with Tk support."""
498 499
499 500 def start(self):
500 501 """Start a Tk enabled event loop."""
501 502
502 503 import Tkinter
503 504 doi = self.do_one_iteration
504 505 # Tk uses milliseconds
505 506 poll_interval = int(1000*self._poll_interval)
506 507 # For Tkinter, we create a Tk object and call its withdraw method.
507 508 class Timer(object):
508 509 def __init__(self, func):
509 510 self.app = Tkinter.Tk()
510 511 self.app.withdraw()
511 512 self.func = func
512 513
513 514 def on_timer(self):
514 515 self.func()
515 516 self.app.after(poll_interval, self.on_timer)
516 517
517 518 def start(self):
518 519 self.on_timer() # Call it once to get things going.
519 520 self.app.mainloop()
520 521
521 522 self.timer = Timer(doi)
522 523 self.timer.start()
523 524
524 525
525 526 class GTKKernel(Kernel):
526 527 """A Kernel subclass with GTK support."""
527 528
528 529 def start(self):
529 530 """Start the kernel, coordinating with the GTK event loop"""
530 531 from .gui.gtkembed import GTKEmbed
531 532
532 533 gtk_kernel = GTKEmbed(self)
533 534 gtk_kernel.start()
534 535
535 536
536 537 #-----------------------------------------------------------------------------
537 538 # Kernel main and launch functions
538 539 #-----------------------------------------------------------------------------
539 540
540 541 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
541 542 independent=False, pylab=False):
542 543 """Launches a localhost kernel, binding to the specified ports.
543 544
544 545 Parameters
545 546 ----------
546 547 xrep_port : int, optional
547 548 The port to use for XREP channel.
548 549
549 550 pub_port : int, optional
550 551 The port to use for the SUB channel.
551 552
552 553 req_port : int, optional
553 554 The port to use for the REQ (raw input) channel.
554 555
555 556 hb_port : int, optional
556 557 The port to use for the hearbeat REP channel.
557 558
558 559 independent : bool, optional (default False)
559 560 If set, the kernel process is guaranteed to survive if this process
560 561 dies. If not set, an effort is made to ensure that the kernel is killed
561 562 when this process dies. Note that in this case it is still good practice
562 563 to kill kernels manually before exiting.
563 564
564 565 pylab : bool or string, optional (default False)
565 566 If not False, the kernel will be launched with pylab enabled. If a
566 567 string is passed, matplotlib will use the specified backend. Otherwise,
567 568 matplotlib's default backend will be used.
568 569
569 570 Returns
570 571 -------
571 572 A tuple of form:
572 573 (kernel_process, xrep_port, pub_port, req_port)
573 574 where kernel_process is a Popen object and the ports are integers.
574 575 """
575 576 extra_arguments = []
576 577 if pylab:
577 578 extra_arguments.append('--pylab')
578 579 if isinstance(pylab, basestring):
579 580 extra_arguments.append(pylab)
580 581 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
581 582 xrep_port, pub_port, req_port, hb_port,
582 583 independent, extra_arguments)
583 584
584 585
585 586 def main():
586 587 """ The IPython kernel main entry point.
587 588 """
588 589 parser = make_argument_parser()
589 590 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
590 591 const='auto', help = \
591 592 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
592 593 given, the GUI backend is matplotlib's, otherwise use one of: \
593 594 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
594 595 namespace = parser.parse_args()
595 596
596 597 kernel_class = Kernel
597 598
598 599 kernel_classes = {
599 600 'qt' : QtKernel,
600 601 'qt4': QtKernel,
601 602 'inline': Kernel,
602 603 'wx' : WxKernel,
603 604 'tk' : TkKernel,
604 605 'gtk': GTKKernel,
605 606 }
606 607 if namespace.pylab:
607 608 if namespace.pylab == 'auto':
608 609 gui, backend = pylabtools.find_gui_and_backend()
609 610 else:
610 611 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
611 612 kernel_class = kernel_classes.get(gui)
612 613 if kernel_class is None:
613 614 raise ValueError('GUI is not supported: %r' % gui)
614 615 pylabtools.activate_matplotlib(backend)
615 616
616 617 kernel = make_kernel(namespace, kernel_class, OutStream)
617 618
618 619 if namespace.pylab:
619 620 pylabtools.import_pylab(kernel.shell.user_ns, backend,
620 621 shell=kernel.shell)
621 622
622 623 start_kernel(namespace, kernel)
623 624
624 625
625 626 if __name__ == '__main__':
626 627 main()
General Comments 0
You need to be logged in to leave comments. Login now