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