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