##// END OF EJS Templates
Merging Fernando's trunk (fp-trunk-dev) and Brian's edits (fp-review)....
Brian Granger -
r2515:08ca9176 merge
parent child Browse files
Show More

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

1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,64 +1,67 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 IPython.
4 IPython.
5
5
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 IPython is a set of tools for interactive and exploratory computing in Python.
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2009 The IPython Development Team
10 # Copyright (C) 2008-2009 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 from __future__ import absolute_import
19
20
20 import os
21 import os
21 import sys
22 import sys
22 from IPython.core import release
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Setup everything
25 # Setup everything
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28 if sys.version[0:3] < '2.5':
29 if sys.version[0:3] < '2.4':
29 raise ImportError('Python Version 2.5 or above is required for IPython.')
30 raise ImportError('Python Version 2.4 or above is required for IPython.')
31
30
32
31
33 # Make it easy to import extensions - they are always directly on pythonpath.
32 # Make it easy to import extensions - they are always directly on pythonpath.
34 # Therefore, non-IPython modules can be added to extensions directory
33 # Therefore, non-IPython modules can be added to extensions directory.
34 # This should probably be in ipapp.py.
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Setup the top level names
38 # Setup the top level names
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 # In some cases, these are causing circular imports.
41 from .config.loader import Config
42 from IPython.core.iplib import InteractiveShell
42 from .core import release
43 from IPython.core.embed import embed
43 from .core.application import Application
44 from IPython.core.error import TryNext
44 from .core.ipapp import IPythonApp
45 from .core.embed import embed
46 from .core.error import TryNext
47 from .core.iplib import InteractiveShell
48 from .testing import test
45
49
46 from IPython.lib import (
50 from .lib import (
47 enable_wx, disable_wx,
51 enable_wx, disable_wx,
48 enable_gtk, disable_gtk,
52 enable_gtk, disable_gtk,
49 enable_qt4, disable_qt4,
53 enable_qt4, disable_qt4,
50 enable_tk, disable_tk,
54 enable_tk, disable_tk,
51 set_inputhook, clear_inputhook,
55 set_inputhook, clear_inputhook,
52 current_gui, spin,
56 current_gui, spin,
53 appstart_qt4, appstart_wx,
57 appstart_qt4, appstart_wx,
54 appstart_gtk, appstart_tk
58 appstart_gtk, appstart_tk
55 )
59 )
56
60
57 # Release data
61 # Release data
58 __author__ = ''
62 __author__ = ''
59 for author, email in release.authors.values():
63 for author, email in release.authors.values():
60 __author__ += author + ' <' + email + '>\n'
64 __author__ += author + ' <' + email + '>\n'
61 __license__ = release.license
65 __license__ = release.license
62 __version__ = release.version
66 __version__ = release.version
63 __revision__ = release.revision
67 __revision__ = release.revision
64
@@ -1,336 +1,370 b''
1 #!/usr/bin/env python
1 # coding: utf-8
2 # encoding: utf-8
3 """A simple configuration system.
2 """A simple configuration system.
4
3
5 Authors:
4 Authors
6
5 -------
7 * Brian Granger
6 * Brian Granger
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.genutils 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 #-----------------------------------------------------------------------------
41 # Argparse fix
42 #-----------------------------------------------------------------------------
43
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
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
48 # stdout and use our class instead.
40
49
50 class ArgumentParser(argparse.ArgumentParser):
51 """Simple argparse subclass that prints help to stdout by default."""
52
53 def print_help(self, file=None):
54 if file is None:
55 file = sys.stdout
56 return super(ArgumentParser, self).print_help(file)
57
58 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
59
41 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
42 # Config class for holding config information
61 # Config class for holding config information
43 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
44
63
45
64
46 class Config(dict):
65 class Config(dict):
47 """An attribute based dict that can do smart merges."""
66 """An attribute based dict that can do smart merges."""
48
67
49 def __init__(self, *args, **kwds):
68 def __init__(self, *args, **kwds):
50 dict.__init__(self, *args, **kwds)
69 dict.__init__(self, *args, **kwds)
51 # 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
52 # because we are also overriding __setattr__.
71 # because we are also overriding __setattr__.
53 dict.__setattr__(self, '__dict__', self)
72 dict.__setattr__(self, '__dict__', self)
54
73
55 def _merge(self, other):
74 def _merge(self, other):
56 to_update = {}
75 to_update = {}
57 for k, v in other.items():
76 for k, v in other.items():
58 if not self.has_key(k):
77 if not self.has_key(k):
59 to_update[k] = v
78 to_update[k] = v
60 else: # I have this key
79 else: # I have this key
61 if isinstance(v, Config):
80 if isinstance(v, Config):
62 # Recursively merge common sub Configs
81 # Recursively merge common sub Configs
63 self[k]._merge(v)
82 self[k]._merge(v)
64 else:
83 else:
65 # Plain updates for non-Configs
84 # Plain updates for non-Configs
66 to_update[k] = v
85 to_update[k] = v
67
86
68 self.update(to_update)
87 self.update(to_update)
69
88
70 def _is_section_key(self, key):
89 def _is_section_key(self, key):
71 if key[0].upper()==key[0] and not key.startswith('_'):
90 if key[0].upper()==key[0] and not key.startswith('_'):
72 return True
91 return True
73 else:
92 else:
74 return False
93 return False
75
94
76 def has_key(self, key):
95 def has_key(self, key):
77 if self._is_section_key(key):
96 if self._is_section_key(key):
78 return True
97 return True
79 else:
98 else:
80 return dict.has_key(self, key)
99 return dict.has_key(self, key)
81
100
82 def _has_section(self, key):
101 def _has_section(self, key):
83 if self._is_section_key(key):
102 if self._is_section_key(key):
84 if dict.has_key(self, key):
103 if dict.has_key(self, key):
85 return True
104 return True
86 return False
105 return False
87
106
88 def copy(self):
107 def copy(self):
89 return type(self)(dict.copy(self))
108 return type(self)(dict.copy(self))
90
109
91 def __copy__(self):
110 def __copy__(self):
92 return self.copy()
111 return self.copy()
93
112
94 def __deepcopy__(self, memo):
113 def __deepcopy__(self, memo):
95 import copy
114 import copy
96 return type(self)(copy.deepcopy(self.items()))
115 return type(self)(copy.deepcopy(self.items()))
97
116
98 def __getitem__(self, key):
117 def __getitem__(self, key):
99 # Because we use this for an exec namespace, we need to delegate
118 # Because we use this for an exec namespace, we need to delegate
100 # the lookup of names in __builtin__ to itself. This means
119 # the lookup of names in __builtin__ to itself. This means
101 # that you can't have section or attribute names that are
120 # that you can't have section or attribute names that are
102 # builtins.
121 # builtins.
103 try:
122 try:
104 return getattr(__builtin__, key)
123 return getattr(__builtin__, key)
105 except AttributeError:
124 except AttributeError:
106 pass
125 pass
107 if self._is_section_key(key):
126 if self._is_section_key(key):
108 try:
127 try:
109 return dict.__getitem__(self, key)
128 return dict.__getitem__(self, key)
110 except KeyError:
129 except KeyError:
111 c = Config()
130 c = Config()
112 dict.__setitem__(self, key, c)
131 dict.__setitem__(self, key, c)
113 return c
132 return c
114 else:
133 else:
115 return dict.__getitem__(self, key)
134 return dict.__getitem__(self, key)
116
135
117 def __setitem__(self, key, value):
136 def __setitem__(self, key, value):
118 # Don't allow names in __builtin__ to be modified.
137 # Don't allow names in __builtin__ to be modified.
119 if hasattr(__builtin__, key):
138 if hasattr(__builtin__, key):
120 raise ConfigError('Config variable names cannot have the same name '
139 raise ConfigError('Config variable names cannot have the same name '
121 'as a Python builtin: %s' % key)
140 'as a Python builtin: %s' % key)
122 if self._is_section_key(key):
141 if self._is_section_key(key):
123 if not isinstance(value, Config):
142 if not isinstance(value, Config):
124 raise ValueError('values whose keys begin with an uppercase '
143 raise ValueError('values whose keys begin with an uppercase '
125 'char must be Config instances: %r, %r' % (key, value))
144 'char must be Config instances: %r, %r' % (key, value))
126 else:
145 else:
127 dict.__setitem__(self, key, value)
146 dict.__setitem__(self, key, value)
128
147
129 def __getattr__(self, key):
148 def __getattr__(self, key):
130 try:
149 try:
131 return self.__getitem__(key)
150 return self.__getitem__(key)
132 except KeyError, e:
151 except KeyError, e:
133 raise AttributeError(e)
152 raise AttributeError(e)
134
153
135 def __setattr__(self, key, value):
154 def __setattr__(self, key, value):
136 try:
155 try:
137 self.__setitem__(key, value)
156 self.__setitem__(key, value)
138 except KeyError, e:
157 except KeyError, e:
139 raise AttributeError(e)
158 raise AttributeError(e)
140
159
141 def __delattr__(self, key):
160 def __delattr__(self, key):
142 try:
161 try:
143 dict.__delitem__(self, key)
162 dict.__delitem__(self, key)
144 except KeyError, e:
163 except KeyError, e:
145 raise AttributeError(e)
164 raise AttributeError(e)
146
165
147
166
148 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
149 # Config loading classes
168 # Config loading classes
150 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
151
170
152
171
153 class ConfigLoader(object):
172 class ConfigLoader(object):
154 """A object for loading configurations from just about anywhere.
173 """A object for loading configurations from just about anywhere.
155
174
156 The resulting configuration is packaged as a :class:`Struct`.
175 The resulting configuration is packaged as a :class:`Struct`.
157
176
158 Notes
177 Notes
159 -----
178 -----
160 A :class:`ConfigLoader` does one thing: load a config from a source
179 A :class:`ConfigLoader` does one thing: load a config from a source
161 (file, command line arguments) and returns the data as a :class:`Struct`.
180 (file, command line arguments) and returns the data as a :class:`Struct`.
162 There are lots of things that :class:`ConfigLoader` does not do. It does
181 There are lots of things that :class:`ConfigLoader` does not do. It does
163 not implement complex logic for finding config files. It does not handle
182 not implement complex logic for finding config files. It does not handle
164 default values or merge multiple configs. These things need to be
183 default values or merge multiple configs. These things need to be
165 handled elsewhere.
184 handled elsewhere.
166 """
185 """
167
186
168 def __init__(self):
187 def __init__(self):
169 """A base class for config loaders.
188 """A base class for config loaders.
170
189
171 Examples
190 Examples
172 --------
191 --------
173
192
174 >>> cl = ConfigLoader()
193 >>> cl = ConfigLoader()
175 >>> config = cl.load_config()
194 >>> config = cl.load_config()
176 >>> config
195 >>> config
177 {}
196 {}
178 """
197 """
179 self.clear()
198 self.clear()
180
199
181 def clear(self):
200 def clear(self):
182 self.config = Config()
201 self.config = Config()
183
202
184 def load_config(self):
203 def load_config(self):
185 """Load a config from somewhere, return a Struct.
204 """Load a config from somewhere, return a :class:`Config` instance.
186
205
187 Usually, this will cause self.config to be set and then returned.
206 Usually, this will cause self.config to be set and then returned.
207 However, in most cases, :meth:`ConfigLoader.clear` should be called
208 to erase any previous state.
188 """
209 """
210 self.clear()
189 return self.config
211 return self.config
190
212
191
213
192 class FileConfigLoader(ConfigLoader):
214 class FileConfigLoader(ConfigLoader):
193 """A base class for file based configurations.
215 """A base class for file based configurations.
194
216
195 As we add more file based config loaders, the common logic should go
217 As we add more file based config loaders, the common logic should go
196 here.
218 here.
197 """
219 """
198 pass
220 pass
199
221
200
222
201 class PyFileConfigLoader(FileConfigLoader):
223 class PyFileConfigLoader(FileConfigLoader):
202 """A config loader for pure python files.
224 """A config loader for pure python files.
203
225
204 This calls execfile on a plain python file and looks for attributes
226 This calls execfile on a plain python file and looks for attributes
205 that are all caps. These attribute are added to the config Struct.
227 that are all caps. These attribute are added to the config Struct.
206 """
228 """
207
229
208 def __init__(self, filename, path=None):
230 def __init__(self, filename, path=None):
209 """Build a config loader for a filename and path.
231 """Build a config loader for a filename and path.
210
232
211 Parameters
233 Parameters
212 ----------
234 ----------
213 filename : str
235 filename : str
214 The file name of the config file.
236 The file name of the config file.
215 path : str, list, tuple
237 path : str, list, tuple
216 The path to search for the config file on, or a sequence of
238 The path to search for the config file on, or a sequence of
217 paths to try in order.
239 paths to try in order.
218 """
240 """
219 super(PyFileConfigLoader, self).__init__()
241 super(PyFileConfigLoader, self).__init__()
220 self.filename = filename
242 self.filename = filename
221 self.path = path
243 self.path = path
222 self.full_filename = ''
244 self.full_filename = ''
223 self.data = None
245 self.data = None
224
246
225 def load_config(self):
247 def load_config(self):
226 """Load the config from a file and return it as a Struct."""
248 """Load the config from a file and return it as a Struct."""
249 self.clear()
227 self._find_file()
250 self._find_file()
228 self._read_file_as_dict()
251 self._read_file_as_dict()
229 self._convert_to_config()
252 self._convert_to_config()
230 return self.config
253 return self.config
231
254
232 def _find_file(self):
255 def _find_file(self):
233 """Try to find the file by searching the paths."""
256 """Try to find the file by searching the paths."""
234 self.full_filename = filefind(self.filename, self.path)
257 self.full_filename = filefind(self.filename, self.path)
235
258
236 def _read_file_as_dict(self):
259 def _read_file_as_dict(self):
237 """Load the config file into self.config, with recursive loading."""
260 """Load the config file into self.config, with recursive loading."""
238 # This closure is made available in the namespace that is used
261 # This closure is made available in the namespace that is used
239 # to exec the config file. This allows users to call
262 # to exec the config file. This allows users to call
240 # load_subconfig('myconfig.py') to load config files recursively.
263 # load_subconfig('myconfig.py') to load config files recursively.
241 # It needs to be a closure because it has references to self.path
264 # It needs to be a closure because it has references to self.path
242 # and self.config. The sub-config is loaded with the same path
265 # and self.config. The sub-config is loaded with the same path
243 # as the parent, but it uses an empty config which is then merged
266 # as the parent, but it uses an empty config which is then merged
244 # with the parents.
267 # with the parents.
245 def load_subconfig(fname):
268 def load_subconfig(fname):
246 loader = PyFileConfigLoader(fname, self.path)
269 loader = PyFileConfigLoader(fname, self.path)
247 try:
270 try:
248 sub_config = loader.load_config()
271 sub_config = loader.load_config()
249 except IOError:
272 except IOError:
250 # Pass silently if the sub config is not there. This happens
273 # Pass silently if the sub config is not there. This happens
251 # when a user us using a profile, but not the default config.
274 # when a user us using a profile, but not the default config.
252 pass
275 pass
253 else:
276 else:
254 self.config._merge(sub_config)
277 self.config._merge(sub_config)
255
278
256 # Again, this needs to be a closure and should be used in config
279 # Again, this needs to be a closure and should be used in config
257 # files to get the config being loaded.
280 # files to get the config being loaded.
258 def get_config():
281 def get_config():
259 return self.config
282 return self.config
260
283
261 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
284 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
262 execfile(self.full_filename, namespace)
285 execfile(self.full_filename, namespace)
263
286
264 def _convert_to_config(self):
287 def _convert_to_config(self):
265 if self.data is None:
288 if self.data is None:
266 ConfigLoaderError('self.data does not exist')
289 ConfigLoaderError('self.data does not exist')
267
290
268
291
269 class CommandLineConfigLoader(ConfigLoader):
292 class CommandLineConfigLoader(ConfigLoader):
270 """A config loader for command line arguments.
293 """A config loader for command line arguments.
271
294
272 As we add more command line based loaders, the common logic should go
295 As we add more command line based loaders, the common logic should go
273 here.
296 here.
274 """
297 """
275
298
276
299
277 class __NoConfigDefault(object): pass
278 NoConfigDefault = __NoConfigDefault()
279
280
281 class ArgParseConfigLoader(CommandLineConfigLoader):
300 class ArgParseConfigLoader(CommandLineConfigLoader):
282
283 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
284 arguments = ()
285
301
286 def __init__(self, *args, **kw):
302 def __init__(self, argv=None, *parser_args, **parser_kw):
287 """Create a config loader for use with argparse.
303 """Create a config loader for use with argparse.
288
304
289 The args and kwargs arguments here are passed onto the constructor
305 Parameters
290 of :class:`argparse.ArgumentParser`.
306 ----------
307
308 argv : optional, list
309 If given, used to read command-line arguments from, otherwise
310 sys.argv[1:] is used.
311
312 parser_args : tuple
313 A tuple of positional arguments that will be passed to the
314 constructor of :class:`argparse.ArgumentParser`.
315
316 parser_kw : dict
317 A tuple of keyword arguments that will be passed to the
318 constructor of :class:`argparse.ArgumentParser`.
291 """
319 """
292 super(CommandLineConfigLoader, self).__init__()
320 super(CommandLineConfigLoader, self).__init__()
293 self.args = args
321 if argv == None:
294 self.kw = kw
322 argv = sys.argv[1:]
323 self.argv = argv
324 self.parser_args = parser_args
325 kwargs = dict(argument_default=argparse.SUPPRESS)
326 kwargs.update(parser_kw)
327 self.parser_kw = kwargs
295
328
296 def load_config(self, args=None):
329 def load_config(self, args=None):
297 """Parse command line arguments and return as a Struct."""
330 """Parse command line arguments and return as a Struct.
331
332 Parameters
333 ----------
334
335 args : optional, list
336 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 (given at construction time) is used."""
339 self.clear()
340 if args is None:
341 args = self.argv
298 self._create_parser()
342 self._create_parser()
299 self._parse_args(args)
343 self._parse_args(args)
300 self._convert_to_config()
344 self._convert_to_config()
301 return self.config
345 return self.config
302
346
303 def get_extra_args(self):
347 def get_extra_args(self):
304 if hasattr(self, 'extra_args'):
348 if hasattr(self, 'extra_args'):
305 return self.extra_args
349 return self.extra_args
306 else:
350 else:
307 return []
351 return []
308
352
309 def _create_parser(self):
353 def _create_parser(self):
310 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
354 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
311 self._add_arguments()
355 self._add_arguments()
312 self._add_other_arguments()
313
314 def _add_other_arguments(self):
315 pass
316
356
317 def _add_arguments(self):
357 def _add_arguments(self):
318 for argument in self.arguments:
358 raise NotImplementedError("subclasses must implement _add_arguments")
319 if not argument[1].has_key('default'):
320 argument[1]['default'] = NoConfigDefault
321 self.parser.add_argument(*argument[0],**argument[1])
322
359
323 def _parse_args(self, args=None):
360 def _parse_args(self, args):
324 """self.parser->self.parsed_data"""
361 """self.parser->self.parsed_data"""
325 if args is None:
362 self.parsed_data, self.extra_args = self.parser.parse_known_args(args)
326 self.parsed_data, self.extra_args = self.parser.parse_known_args()
327 else:
328 self.parsed_data, self.extra_args = self.parser.parse_known_args(args)
329
363
330 def _convert_to_config(self):
364 def _convert_to_config(self):
331 """self.parsed_data->self.config"""
365 """self.parsed_data->self.config"""
332 for k, v in vars(self.parsed_data).items():
366 for k, v in vars(self.parsed_data).items():
333 if v is not NoConfigDefault:
367 exec_str = 'self.config.' + k + '= v'
334 exec_str = 'self.config.' + k + '= v'
368 exec exec_str in locals(), globals()
335 exec exec_str in locals(), globals()
369
336
370
@@ -1,163 +1,174 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Tests for IPython.config.loader
4 Tests for IPython.config.loader
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez (design help)
9 * Fernando Perez (design help)
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import os
23 import os
24 from tempfile import mkstemp
24 from tempfile import mkstemp
25 from unittest import TestCase
25 from unittest import TestCase
26
26
27 from IPython.config.loader import (
27 from IPython.config.loader import (
28 Config,
28 Config,
29 PyFileConfigLoader,
29 PyFileConfigLoader,
30 ArgParseConfigLoader,
30 ArgParseConfigLoader,
31 ConfigError
31 ConfigError
32 )
32 )
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Actual tests
35 # Actual tests
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 pyfile = """
39 pyfile = """
40 a = 10
40 c = get_config()
41 b = 20
41 c.a = 10
42 Foo.Bar.value = 10
42 c.b = 20
43 Foo.Bam.value = range(10)
43 c.Foo.Bar.value = 10
44 D.C.value = 'hi there'
44 c.Foo.Bam.value = range(10)
45 c.D.C.value = 'hi there'
45 """
46 """
46
47
47 class TestPyFileCL(TestCase):
48 class TestPyFileCL(TestCase):
48
49
49 def test_basic(self):
50 def test_basic(self):
50 fd, fname = mkstemp()
51 fd, fname = mkstemp('.py')
51 f = os.fdopen(fd, 'w')
52 f = os.fdopen(fd, 'w')
52 f.write(pyfile)
53 f.write(pyfile)
53 f.close()
54 f.close()
54 # Unlink the file
55 # Unlink the file
55 cl = PyFileConfigLoader(fname)
56 cl = PyFileConfigLoader(fname)
56 config = cl.load_config()
57 config = cl.load_config()
57 self.assertEquals(config.a, 10)
58 self.assertEquals(config.a, 10)
58 self.assertEquals(config.b, 20)
59 self.assertEquals(config.b, 20)
59 self.assertEquals(config.Foo.Bar.value, 10)
60 self.assertEquals(config.Foo.Bar.value, 10)
60 self.assertEquals(config.Foo.Bam.value, range(10))
61 self.assertEquals(config.Foo.Bam.value, range(10))
61 self.assertEquals(config.D.C.value, 'hi there')
62 self.assertEquals(config.D.C.value, 'hi there')
62
63
64 class MyLoader1(ArgParseConfigLoader):
65 def _add_arguments(self):
66 p = self.parser
67 p.add_argument('-f', '--foo', dest='Global.foo', type=str)
68 p.add_argument('-b', dest='MyClass.bar', type=int)
69 p.add_argument('-n', dest='n', action='store_true')
70 p.add_argument('Global.bam', type=str)
71
72 class MyLoader2(ArgParseConfigLoader):
73 def _add_arguments(self):
74 subparsers = self.parser.add_subparsers(dest='subparser_name')
75 subparser1 = subparsers.add_parser('1')
76 subparser1.add_argument('-x',dest='Global.x')
77 subparser2 = subparsers.add_parser('2')
78 subparser2.add_argument('y')
63
79
64 class TestArgParseCL(TestCase):
80 class TestArgParseCL(TestCase):
65
81
66 def test_basic(self):
82 def test_basic(self):
67
83 cl = MyLoader1()
68 class MyLoader(ArgParseConfigLoader):
69 arguments = (
70 (('-f','--foo'), dict(dest='Global.foo', type=str)),
71 (('-b',), dict(dest='MyClass.bar', type=int)),
72 (('-n',), dict(dest='n', action='store_true')),
73 (('Global.bam',), dict(type=str))
74 )
75
76 cl = MyLoader()
77 config = cl.load_config('-f hi -b 10 -n wow'.split())
84 config = cl.load_config('-f hi -b 10 -n wow'.split())
78 self.assertEquals(config.Global.foo, 'hi')
85 self.assertEquals(config.Global.foo, 'hi')
79 self.assertEquals(config.MyClass.bar, 10)
86 self.assertEquals(config.MyClass.bar, 10)
80 self.assertEquals(config.n, True)
87 self.assertEquals(config.n, True)
81 self.assertEquals(config.Global.bam, 'wow')
88 self.assertEquals(config.Global.bam, 'wow')
89 config = cl.load_config(['wow'])
90 self.assertEquals(config.keys(), ['Global'])
91 self.assertEquals(config.Global.keys(), ['bam'])
92 self.assertEquals(config.Global.bam, 'wow')
82
93
83 def test_add_arguments(self):
94 def test_add_arguments(self):
84
95 cl = MyLoader2()
85 class MyLoader(ArgParseConfigLoader):
86 def _add_arguments(self):
87 subparsers = self.parser.add_subparsers(dest='subparser_name')
88 subparser1 = subparsers.add_parser('1')
89 subparser1.add_argument('-x',dest='Global.x')
90 subparser2 = subparsers.add_parser('2')
91 subparser2.add_argument('y')
92
93 cl = MyLoader()
94 config = cl.load_config('2 frobble'.split())
96 config = cl.load_config('2 frobble'.split())
95 self.assertEquals(config.subparser_name, '2')
97 self.assertEquals(config.subparser_name, '2')
96 self.assertEquals(config.y, 'frobble')
98 self.assertEquals(config.y, 'frobble')
97 config = cl.load_config('1 -x frobble'.split())
99 config = cl.load_config('1 -x frobble'.split())
98 self.assertEquals(config.subparser_name, '1')
100 self.assertEquals(config.subparser_name, '1')
99 self.assertEquals(config.Global.x, 'frobble')
101 self.assertEquals(config.Global.x, 'frobble')
100
102
103 def test_argv(self):
104 cl = MyLoader1(argv='-f hi -b 10 -n wow'.split())
105 config = cl.load_config()
106 self.assertEquals(config.Global.foo, 'hi')
107 self.assertEquals(config.MyClass.bar, 10)
108 self.assertEquals(config.n, True)
109 self.assertEquals(config.Global.bam, 'wow')
110
111
101 class TestConfig(TestCase):
112 class TestConfig(TestCase):
102
113
103 def test_setget(self):
114 def test_setget(self):
104 c = Config()
115 c = Config()
105 c.a = 10
116 c.a = 10
106 self.assertEquals(c.a, 10)
117 self.assertEquals(c.a, 10)
107 self.assertEquals(c.has_key('b'), False)
118 self.assertEquals(c.has_key('b'), False)
108
119
109 def test_auto_section(self):
120 def test_auto_section(self):
110 c = Config()
121 c = Config()
111 self.assertEquals(c.has_key('A'), True)
122 self.assertEquals(c.has_key('A'), True)
112 self.assertEquals(c._has_section('A'), False)
123 self.assertEquals(c._has_section('A'), False)
113 A = c.A
124 A = c.A
114 A.foo = 'hi there'
125 A.foo = 'hi there'
115 self.assertEquals(c._has_section('A'), True)
126 self.assertEquals(c._has_section('A'), True)
116 self.assertEquals(c.A.foo, 'hi there')
127 self.assertEquals(c.A.foo, 'hi there')
117 del c.A
128 del c.A
118 self.assertEquals(len(c.A.keys()),0)
129 self.assertEquals(len(c.A.keys()),0)
119
130
120 def test_merge_doesnt_exist(self):
131 def test_merge_doesnt_exist(self):
121 c1 = Config()
132 c1 = Config()
122 c2 = Config()
133 c2 = Config()
123 c2.bar = 10
134 c2.bar = 10
124 c2.Foo.bar = 10
135 c2.Foo.bar = 10
125 c1._merge(c2)
136 c1._merge(c2)
126 self.assertEquals(c1.Foo.bar, 10)
137 self.assertEquals(c1.Foo.bar, 10)
127 self.assertEquals(c1.bar, 10)
138 self.assertEquals(c1.bar, 10)
128 c2.Bar.bar = 10
139 c2.Bar.bar = 10
129 c1._merge(c2)
140 c1._merge(c2)
130 self.assertEquals(c1.Bar.bar, 10)
141 self.assertEquals(c1.Bar.bar, 10)
131
142
132 def test_merge_exists(self):
143 def test_merge_exists(self):
133 c1 = Config()
144 c1 = Config()
134 c2 = Config()
145 c2 = Config()
135 c1.Foo.bar = 10
146 c1.Foo.bar = 10
136 c1.Foo.bam = 30
147 c1.Foo.bam = 30
137 c2.Foo.bar = 20
148 c2.Foo.bar = 20
138 c2.Foo.wow = 40
149 c2.Foo.wow = 40
139 c1._merge(c2)
150 c1._merge(c2)
140 self.assertEquals(c1.Foo.bam, 30)
151 self.assertEquals(c1.Foo.bam, 30)
141 self.assertEquals(c1.Foo.bar, 20)
152 self.assertEquals(c1.Foo.bar, 20)
142 self.assertEquals(c1.Foo.wow, 40)
153 self.assertEquals(c1.Foo.wow, 40)
143 c2.Foo.Bam.bam = 10
154 c2.Foo.Bam.bam = 10
144 c1._merge(c2)
155 c1._merge(c2)
145 self.assertEquals(c1.Foo.Bam.bam, 10)
156 self.assertEquals(c1.Foo.Bam.bam, 10)
146
157
147 def test_deepcopy(self):
158 def test_deepcopy(self):
148 c1 = Config()
159 c1 = Config()
149 c1.Foo.bar = 10
160 c1.Foo.bar = 10
150 c1.Foo.bam = 30
161 c1.Foo.bam = 30
151 c1.a = 'asdf'
162 c1.a = 'asdf'
152 c1.b = range(10)
163 c1.b = range(10)
153 import copy
164 import copy
154 c2 = copy.deepcopy(c1)
165 c2 = copy.deepcopy(c1)
155 self.assertEquals(c1, c2)
166 self.assertEquals(c1, c2)
156 self.assert_(c1 is not c2)
167 self.assert_(c1 is not c2)
157 self.assert_(c1.Foo is not c2.Foo)
168 self.assert_(c1.Foo is not c2.Foo)
158
169
159 def test_builtin(self):
170 def test_builtin(self):
160 c1 = Config()
171 c1 = Config()
161 exec 'foo = True' in c1
172 exec 'foo = True' in c1
162 self.assertEquals(c1.foo, True)
173 self.assertEquals(c1.foo, True)
163 self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10)
174 self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10)
@@ -1,262 +1,262 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 IPython's alias component
4 IPython's alias component
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23 import keyword
23 import keyword
24 import os
24 import os
25 import re
25 import re
26 import sys
26 import sys
27
27
28 from IPython.core.component import Component
28 from IPython.core.component import Component
29 from IPython.core.splitinput import split_user_input
29 from IPython.core.splitinput import split_user_input
30
30
31 from IPython.utils.traitlets import CBool, List, Instance
31 from IPython.utils.traitlets import List
32 from IPython.utils.genutils import error
33 from IPython.utils.autoattr import auto_attr
32 from IPython.utils.autoattr import auto_attr
33 from IPython.utils.warn import warn, error
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Utilities
36 # Utilities
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39 # This is used as the pattern for calls to split_user_input.
39 # This is used as the pattern for calls to split_user_input.
40 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
40 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
41
41
42 def default_aliases():
42 def default_aliases():
43 # Make some aliases automatically
43 # Make some aliases automatically
44 # Prepare list of shell aliases to auto-define
44 # Prepare list of shell aliases to auto-define
45 if os.name == 'posix':
45 if os.name == 'posix':
46 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
46 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
47 'mv mv -i','rm rm -i','cp cp -i',
47 'mv mv -i','rm rm -i','cp cp -i',
48 'cat cat','less less','clear clear',
48 'cat cat','less less','clear clear',
49 # a better ls
49 # a better ls
50 'ls ls -F',
50 'ls ls -F',
51 # long ls
51 # long ls
52 'll ls -lF')
52 'll ls -lF')
53 # Extra ls aliases with color, which need special treatment on BSD
53 # Extra ls aliases with color, which need special treatment on BSD
54 # variants
54 # variants
55 ls_extra = ( # color ls
55 ls_extra = ( # color ls
56 'lc ls -F -o --color',
56 'lc ls -F -o --color',
57 # ls normal files only
57 # ls normal files only
58 'lf ls -F -o --color %l | grep ^-',
58 'lf ls -F -o --color %l | grep ^-',
59 # ls symbolic links
59 # ls symbolic links
60 'lk ls -F -o --color %l | grep ^l',
60 'lk ls -F -o --color %l | grep ^l',
61 # directories or links to directories,
61 # directories or links to directories,
62 'ldir ls -F -o --color %l | grep /$',
62 'ldir ls -F -o --color %l | grep /$',
63 # things which are executable
63 # things which are executable
64 'lx ls -F -o --color %l | grep ^-..x',
64 'lx ls -F -o --color %l | grep ^-..x',
65 )
65 )
66 # The BSDs don't ship GNU ls, so they don't understand the
66 # The BSDs don't ship GNU ls, so they don't understand the
67 # --color switch out of the box
67 # --color switch out of the box
68 if 'bsd' in sys.platform:
68 if 'bsd' in sys.platform:
69 ls_extra = ( # ls normal files only
69 ls_extra = ( # ls normal files only
70 'lf ls -lF | grep ^-',
70 'lf ls -lF | grep ^-',
71 # ls symbolic links
71 # ls symbolic links
72 'lk ls -lF | grep ^l',
72 'lk ls -lF | grep ^l',
73 # directories or links to directories,
73 # directories or links to directories,
74 'ldir ls -lF | grep /$',
74 'ldir ls -lF | grep /$',
75 # things which are executable
75 # things which are executable
76 'lx ls -lF | grep ^-..x',
76 'lx ls -lF | grep ^-..x',
77 )
77 )
78 default_aliases = default_aliases + ls_extra
78 default_aliases = default_aliases + ls_extra
79 elif os.name in ['nt','dos']:
79 elif os.name in ['nt','dos']:
80 default_aliases = ('ls dir /on',
80 default_aliases = ('ls dir /on',
81 'ddir dir /ad /on', 'ldir dir /ad /on',
81 'ddir dir /ad /on', 'ldir dir /ad /on',
82 'mkdir mkdir','rmdir rmdir','echo echo',
82 'mkdir mkdir','rmdir rmdir','echo echo',
83 'ren ren','cls cls','copy copy')
83 'ren ren','cls cls','copy copy')
84 else:
84 else:
85 default_aliases = ()
85 default_aliases = ()
86 return [s.split(None,1) for s in default_aliases]
86 return [s.split(None,1) for s in default_aliases]
87
87
88
88
89 class AliasError(Exception):
89 class AliasError(Exception):
90 pass
90 pass
91
91
92
92
93 class InvalidAliasError(AliasError):
93 class InvalidAliasError(AliasError):
94 pass
94 pass
95
95
96
96
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98 # Main AliasManager class
98 # Main AliasManager class
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100
100
101
101
102 class AliasManager(Component):
102 class AliasManager(Component):
103
103
104 default_aliases = List(default_aliases(), config=True)
104 default_aliases = List(default_aliases(), config=True)
105 user_aliases = List(default_value=[], config=True)
105 user_aliases = List(default_value=[], config=True)
106
106
107 def __init__(self, parent, config=None):
107 def __init__(self, parent, config=None):
108 super(AliasManager, self).__init__(parent, config=config)
108 super(AliasManager, self).__init__(parent, config=config)
109 self.alias_table = {}
109 self.alias_table = {}
110 self.exclude_aliases()
110 self.exclude_aliases()
111 self.init_aliases()
111 self.init_aliases()
112
112
113 @auto_attr
113 @auto_attr
114 def shell(self):
114 def shell(self):
115 return Component.get_instances(
115 return Component.get_instances(
116 root=self.root,
116 root=self.root,
117 klass='IPython.core.iplib.InteractiveShell')[0]
117 klass='IPython.core.iplib.InteractiveShell')[0]
118
118
119 def __contains__(self, name):
119 def __contains__(self, name):
120 if name in self.alias_table:
120 if name in self.alias_table:
121 return True
121 return True
122 else:
122 else:
123 return False
123 return False
124
124
125 @property
125 @property
126 def aliases(self):
126 def aliases(self):
127 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
127 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
128
128
129 def exclude_aliases(self):
129 def exclude_aliases(self):
130 # set of things NOT to alias (keywords, builtins and some magics)
130 # set of things NOT to alias (keywords, builtins and some magics)
131 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
131 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
132 no_alias.update(set(keyword.kwlist))
132 no_alias.update(set(keyword.kwlist))
133 no_alias.update(set(__builtin__.__dict__.keys()))
133 no_alias.update(set(__builtin__.__dict__.keys()))
134 self.no_alias = no_alias
134 self.no_alias = no_alias
135
135
136 def init_aliases(self):
136 def init_aliases(self):
137 # Load default aliases
137 # Load default aliases
138 for name, cmd in self.default_aliases:
138 for name, cmd in self.default_aliases:
139 self.soft_define_alias(name, cmd)
139 self.soft_define_alias(name, cmd)
140
140
141 # Load user aliases
141 # Load user aliases
142 for name, cmd in self.user_aliases:
142 for name, cmd in self.user_aliases:
143 self.soft_define_alias(name, cmd)
143 self.soft_define_alias(name, cmd)
144
144
145 def clear_aliases(self):
145 def clear_aliases(self):
146 self.alias_table.clear()
146 self.alias_table.clear()
147
147
148 def soft_define_alias(self, name, cmd):
148 def soft_define_alias(self, name, cmd):
149 """Define an alias, but don't raise on an AliasError."""
149 """Define an alias, but don't raise on an AliasError."""
150 try:
150 try:
151 self.define_alias(name, cmd)
151 self.define_alias(name, cmd)
152 except AliasError, e:
152 except AliasError, e:
153 error("Invalid alias: %s" % e)
153 error("Invalid alias: %s" % e)
154
154
155 def define_alias(self, name, cmd):
155 def define_alias(self, name, cmd):
156 """Define a new alias after validating it.
156 """Define a new alias after validating it.
157
157
158 This will raise an :exc:`AliasError` if there are validation
158 This will raise an :exc:`AliasError` if there are validation
159 problems.
159 problems.
160 """
160 """
161 nargs = self.validate_alias(name, cmd)
161 nargs = self.validate_alias(name, cmd)
162 self.alias_table[name] = (nargs, cmd)
162 self.alias_table[name] = (nargs, cmd)
163
163
164 def undefine_alias(self, name):
164 def undefine_alias(self, name):
165 if self.alias_table.has_key(name):
165 if self.alias_table.has_key(name):
166 del self.alias_table[name]
166 del self.alias_table[name]
167
167
168 def validate_alias(self, name, cmd):
168 def validate_alias(self, name, cmd):
169 """Validate an alias and return the its number of arguments."""
169 """Validate an alias and return the its number of arguments."""
170 if name in self.no_alias:
170 if name in self.no_alias:
171 raise InvalidAliasError("The name %s can't be aliased "
171 raise InvalidAliasError("The name %s can't be aliased "
172 "because it is a keyword or builtin." % name)
172 "because it is a keyword or builtin." % name)
173 if not (isinstance(cmd, basestring)):
173 if not (isinstance(cmd, basestring)):
174 raise InvalidAliasError("An alias command must be a string, "
174 raise InvalidAliasError("An alias command must be a string, "
175 "got: %r" % name)
175 "got: %r" % name)
176 nargs = cmd.count('%s')
176 nargs = cmd.count('%s')
177 if nargs>0 and cmd.find('%l')>=0:
177 if nargs>0 and cmd.find('%l')>=0:
178 raise InvalidAliasError('The %s and %l specifiers are mutually '
178 raise InvalidAliasError('The %s and %l specifiers are mutually '
179 'exclusive in alias definitions.')
179 'exclusive in alias definitions.')
180 return nargs
180 return nargs
181
181
182 def call_alias(self, alias, rest=''):
182 def call_alias(self, alias, rest=''):
183 """Call an alias given its name and the rest of the line."""
183 """Call an alias given its name and the rest of the line."""
184 cmd = self.transform_alias(alias, rest)
184 cmd = self.transform_alias(alias, rest)
185 try:
185 try:
186 self.shell.system(cmd)
186 self.shell.system(cmd)
187 except:
187 except:
188 self.shell.showtraceback()
188 self.shell.showtraceback()
189
189
190 def transform_alias(self, alias,rest=''):
190 def transform_alias(self, alias,rest=''):
191 """Transform alias to system command string."""
191 """Transform alias to system command string."""
192 nargs, cmd = self.alias_table[alias]
192 nargs, cmd = self.alias_table[alias]
193
193
194 if ' ' in cmd and os.path.isfile(cmd):
194 if ' ' in cmd and os.path.isfile(cmd):
195 cmd = '"%s"' % cmd
195 cmd = '"%s"' % cmd
196
196
197 # Expand the %l special to be the user's input line
197 # Expand the %l special to be the user's input line
198 if cmd.find('%l') >= 0:
198 if cmd.find('%l') >= 0:
199 cmd = cmd.replace('%l', rest)
199 cmd = cmd.replace('%l', rest)
200 rest = ''
200 rest = ''
201 if nargs==0:
201 if nargs==0:
202 # Simple, argument-less aliases
202 # Simple, argument-less aliases
203 cmd = '%s %s' % (cmd, rest)
203 cmd = '%s %s' % (cmd, rest)
204 else:
204 else:
205 # Handle aliases with positional arguments
205 # Handle aliases with positional arguments
206 args = rest.split(None, nargs)
206 args = rest.split(None, nargs)
207 if len(args) < nargs:
207 if len(args) < nargs:
208 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
208 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
209 (alias, nargs, len(args)))
209 (alias, nargs, len(args)))
210 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
210 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
211 return cmd
211 return cmd
212
212
213 def expand_alias(self, line):
213 def expand_alias(self, line):
214 """ Expand an alias in the command line
214 """ Expand an alias in the command line
215
215
216 Returns the provided command line, possibly with the first word
216 Returns the provided command line, possibly with the first word
217 (command) translated according to alias expansion rules.
217 (command) translated according to alias expansion rules.
218
218
219 [ipython]|16> _ip.expand_aliases("np myfile.txt")
219 [ipython]|16> _ip.expand_aliases("np myfile.txt")
220 <16> 'q:/opt/np/notepad++.exe myfile.txt'
220 <16> 'q:/opt/np/notepad++.exe myfile.txt'
221 """
221 """
222
222
223 pre,fn,rest = split_user_input(line)
223 pre,fn,rest = split_user_input(line)
224 res = pre + self.expand_aliases(fn, rest)
224 res = pre + self.expand_aliases(fn, rest)
225 return res
225 return res
226
226
227 def expand_aliases(self, fn, rest):
227 def expand_aliases(self, fn, rest):
228 """Expand multiple levels of aliases:
228 """Expand multiple levels of aliases:
229
229
230 if:
230 if:
231
231
232 alias foo bar /tmp
232 alias foo bar /tmp
233 alias baz foo
233 alias baz foo
234
234
235 then:
235 then:
236
236
237 baz huhhahhei -> bar /tmp huhhahhei
237 baz huhhahhei -> bar /tmp huhhahhei
238
238
239 """
239 """
240 line = fn + " " + rest
240 line = fn + " " + rest
241
241
242 done = set()
242 done = set()
243 while 1:
243 while 1:
244 pre,fn,rest = split_user_input(line, shell_line_split)
244 pre,fn,rest = split_user_input(line, shell_line_split)
245 if fn in self.alias_table:
245 if fn in self.alias_table:
246 if fn in done:
246 if fn in done:
247 warn("Cyclic alias definition, repeated '%s'" % fn)
247 warn("Cyclic alias definition, repeated '%s'" % fn)
248 return ""
248 return ""
249 done.add(fn)
249 done.add(fn)
250
250
251 l2 = self.transform_alias(fn, rest)
251 l2 = self.transform_alias(fn, rest)
252 if l2 == line:
252 if l2 == line:
253 break
253 break
254 # ls -> ls -F should not recurse forever
254 # ls -> ls -F should not recurse forever
255 if l2.split(None,1)[0] == line.split(None,1)[0]:
255 if l2.split(None,1)[0] == line.split(None,1)[0]:
256 line = l2
256 line = l2
257 break
257 break
258 line=l2
258 line=l2
259 else:
259 else:
260 break
260 break
261
261
262 return line
262 return line
@@ -1,364 +1,453 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
1 # encoding: utf-8
3 """
2 """
4 An application for IPython.
3 An application for IPython.
5
4
6 All top-level applications should use the classes in this module for
5 All top-level applications should use the classes in this module for
7 handling configuration and creating componenets.
6 handling configuration and creating componenets.
8
7
9 The job of an :class:`Application` is to create the master configuration
8 The job of an :class:`Application` is to create the master configuration
10 object and then create the components, passing the config to them.
9 object and then create the components, passing the config to them.
11
10
12 Authors:
11 Authors:
13
12
14 * Brian Granger
13 * Brian Granger
15 * Fernando Perez
14 * Fernando Perez
16
15
17 Notes
16 Notes
18 -----
17 -----
19 """
18 """
20
19
21 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
22 # Copyright (C) 2008-2009 The IPython Development Team
21 # Copyright (C) 2008-2009 The IPython Development Team
23 #
22 #
24 # Distributed under the terms of the BSD License. The full license is in
23 # Distributed under the terms of the BSD License. The full license is in
25 # the file COPYING, distributed as part of this software.
24 # the file COPYING, distributed as part of this software.
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27
26
28 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
29 # Imports
28 # Imports
30 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
31
30
32 import logging
31 import logging
33 import os
32 import os
34 import sys
33 import sys
35
34
36 from IPython.core import release
35 from IPython.core import release, crashhandler
37 from IPython.utils.genutils import get_ipython_dir
36 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
38 from IPython.config.loader import (
37 from IPython.config.loader import (
39 PyFileConfigLoader,
38 PyFileConfigLoader,
40 ArgParseConfigLoader,
39 ArgParseConfigLoader,
41 Config,
40 Config,
42 NoConfigDefault
43 )
41 )
44
42
45 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
46 # Classes and functions
44 # Classes and functions
47 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
48
46
47 class ApplicationError(Exception):
48 pass
49
49
50
50 class BaseAppArgParseConfigLoader(ArgParseConfigLoader):
51 class BaseAppConfigLoader(ArgParseConfigLoader):
51 """Default command line options for IPython based applications."""
52 """Default command line options for IPython based applications."""
52
53
53 def _add_other_arguments(self):
54 def _add_ipython_dir(self, parser):
54 self.parser.add_argument('--ipython-dir',
55 """Add the --ipython-dir option to the parser."""
56 paa = parser.add_argument
57 paa('--ipython-dir',
55 dest='Global.ipython_dir',type=unicode,
58 dest='Global.ipython_dir',type=unicode,
56 help='Set to override default location of Global.ipython_dir.',
59 help=
57 default=NoConfigDefault,
60 """Set to override default location of the IPython directory
61 IPYTHON_DIR, stored as Global.ipython_dir. This can also be
62 specified through the environment variable IPYTHON_DIR.""",
58 metavar='Global.ipython_dir')
63 metavar='Global.ipython_dir')
59 self.parser.add_argument('-p', '--profile',
64
60 dest='Global.profile',type=unicode,
65 def _add_log_level(self, parser):
61 help='The string name of the ipython profile to be used.',
66 """Add the --log-level option to the parser."""
62 default=NoConfigDefault,
67 paa = parser.add_argument
63 metavar='Global.profile')
68 paa('--log-level',
64 self.parser.add_argument('--log-level',
65 dest="Global.log_level",type=int,
69 dest="Global.log_level",type=int,
66 help='Set the log level (0,10,20,30,40,50). Default is 30.',
70 help='Set the log level (0,10,20,30,40,50). Default is 30.',
67 default=NoConfigDefault,
68 metavar='Global.log_level')
71 metavar='Global.log_level')
69 self.parser.add_argument('--config-file',
70 dest='Global.config_file',type=unicode,
71 help='Set the config file name to override default.',
72 default=NoConfigDefault,
73 metavar='Global.config_file')
74
75
72
76 class ApplicationError(Exception):
73 def _add_arguments(self):
77 pass
74 self._add_ipython_dir(self.parser)
75 self._add_log_level(self.parser)
78
76
79
77
80 class Application(object):
78 class Application(object):
81 """Load a config, construct components and set them running."""
79 """Load a config, construct components and set them running.
80
81 The configuration of an application can be done via three different Config
82 objects, which are loaded and ultimately merged into a single one used
83 from that point on by the app. These are:
84
85 1. default_config: internal defaults, implemented in code.
86 2. file_config: read from the filesystem.
87 3. command_line_config: read from the system's command line flags.
88
89 During initialization, 3 is actually read before 2, since at the
90 command-line one may override the location of the file to be read. But the
91 above is the order in which the merge is made.
92 """
82
93
83 name = u'ipython'
94 name = u'ipython'
84 description = 'IPython: an enhanced interactive Python shell.'
95 description = 'IPython: an enhanced interactive Python shell.'
85 config_file_name = u'ipython_config.py'
96 #: Usage message printed by argparse. If None, auto-generate
97 usage = None
98 #: The command line config loader. Subclass of ArgParseConfigLoader.
99 command_line_loader = BaseAppConfigLoader
100 #: The name of the config file to load, determined at runtime
101 config_file_name = None
102 #: The name of the default config file. Track separately from the actual
103 #: name because some logic happens only if we aren't using the default.
104 default_config_file_name = u'ipython_config.py'
86 default_log_level = logging.WARN
105 default_log_level = logging.WARN
87
106 #: Set by --profile option
88 def __init__(self):
107 profile_name = None
89 self._exiting = False
108 #: User's ipython directory, typically ~/.ipython/
109 ipython_dir = None
110 #: Internal defaults, implemented in code.
111 default_config = None
112 #: Read from the filesystem.
113 file_config = None
114 #: Read from the system's command line flags.
115 command_line_config = None
116 #: The final config that will be passed to the component.
117 master_config = None
118 #: A reference to the argv to be used (typically ends up being sys.argv[1:])
119 argv = None
120 #: extra arguments computed by the command-line loader
121 extra_args = None
122 #: The class to use as the crash handler.
123 crash_handler_class = crashhandler.CrashHandler
124
125 # Private attributes
126 _exiting = False
127 _initialized = False
128
129 def __init__(self, argv=None):
130 self.argv = sys.argv[1:] if argv is None else argv
90 self.init_logger()
131 self.init_logger()
91 # Track the default and actual separately because some messages are
92 # only printed if we aren't using the default.
93 self.default_config_file_name = self.config_file_name
94
132
95 def init_logger(self):
133 def init_logger(self):
96 self.log = logging.getLogger(self.__class__.__name__)
134 self.log = logging.getLogger(self.__class__.__name__)
97 # This is used as the default until the command line arguments are read.
135 # This is used as the default until the command line arguments are read.
98 self.log.setLevel(self.default_log_level)
136 self.log.setLevel(self.default_log_level)
99 self._log_handler = logging.StreamHandler()
137 self._log_handler = logging.StreamHandler()
100 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
138 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
101 self._log_handler.setFormatter(self._log_formatter)
139 self._log_handler.setFormatter(self._log_formatter)
102 self.log.addHandler(self._log_handler)
140 self.log.addHandler(self._log_handler)
103
141
104 def _set_log_level(self, level):
142 def _set_log_level(self, level):
105 self.log.setLevel(level)
143 self.log.setLevel(level)
106
144
107 def _get_log_level(self):
145 def _get_log_level(self):
108 return self.log.level
146 return self.log.level
109
147
110 log_level = property(_get_log_level, _set_log_level)
148 log_level = property(_get_log_level, _set_log_level)
111
149
112 def start(self):
150 def initialize(self):
113 """Start the application."""
151 """Initialize the application.
114 self.attempt(self.create_default_config)
152
153 Loads all configuration information and sets all application state, but
154 does not start any relevant processing (typically some kind of event
155 loop).
156
157 Once this method has been called, the application is flagged as
158 initialized and the method becomes a no-op."""
159
160 if self._initialized:
161 return
162
163 # The first part is protected with an 'attempt' wrapper, that will log
164 # failures with the basic system traceback machinery. Once our crash
165 # handler is in place, we can let any subsequent exception propagate,
166 # as our handler will log it with much better detail than the default.
167 self.attempt(self.create_crash_handler)
168
169 # Configuration phase
170 # Default config (internally hardwired in application code)
171 self.create_default_config()
115 self.log_default_config()
172 self.log_default_config()
116 self.set_default_config_log_level()
173 self.set_default_config_log_level()
117 self.attempt(self.pre_load_command_line_config)
174
118 self.attempt(self.load_command_line_config, action='abort')
175 # Command-line config
176 self.pre_load_command_line_config()
177 self.load_command_line_config()
119 self.set_command_line_config_log_level()
178 self.set_command_line_config_log_level()
120 self.attempt(self.post_load_command_line_config)
179 self.post_load_command_line_config()
121 self.log_command_line_config()
180 self.log_command_line_config()
122 self.attempt(self.find_ipython_dir)
181
123 self.attempt(self.find_resources)
182 # Find resources needed for filesystem access, using information from
124 self.attempt(self.find_config_file_name)
183 # the above two
125 self.attempt(self.find_config_file_paths)
184 self.find_ipython_dir()
126 self.attempt(self.pre_load_file_config)
185 self.find_resources()
127 self.attempt(self.load_file_config)
186 self.find_config_file_name()
187 self.find_config_file_paths()
188
189 # File-based config
190 self.pre_load_file_config()
191 self.load_file_config()
128 self.set_file_config_log_level()
192 self.set_file_config_log_level()
129 self.attempt(self.post_load_file_config)
193 self.post_load_file_config()
130 self.log_file_config()
194 self.log_file_config()
131 self.attempt(self.merge_configs)
195
196 # Merge all config objects into a single one the app can then use
197 self.merge_configs()
132 self.log_master_config()
198 self.log_master_config()
133 self.attempt(self.pre_construct)
199
134 self.attempt(self.construct)
200 # Construction phase
135 self.attempt(self.post_construct)
201 self.pre_construct()
136 self.attempt(self.start_app)
202 self.construct()
203 self.post_construct()
204
205 # Done, flag as such and
206 self._initialized = True
207
208 def start(self):
209 """Start the application."""
210 self.initialize()
211 self.start_app()
137
212
138 #-------------------------------------------------------------------------
213 #-------------------------------------------------------------------------
139 # Various stages of Application creation
214 # Various stages of Application creation
140 #-------------------------------------------------------------------------
215 #-------------------------------------------------------------------------
141
216
217 def create_crash_handler(self):
218 """Create a crash handler, typically setting sys.excepthook to it."""
219 self.crash_handler = self.crash_handler_class(self)
220 sys.excepthook = self.crash_handler
221
142 def create_default_config(self):
222 def create_default_config(self):
143 """Create defaults that can't be set elsewhere.
223 """Create defaults that can't be set elsewhere.
144
224
145 For the most part, we try to set default in the class attributes
225 For the most part, we try to set default in the class attributes
146 of Components. But, defaults the top-level Application (which is
226 of Components. But, defaults the top-level Application (which is
147 not a HasTraitlets or Component) are not set in this way. Instead
227 not a HasTraitlets or Component) are not set in this way. Instead
148 we set them here. The Global section is for variables like this that
228 we set them here. The Global section is for variables like this that
149 don't belong to a particular component.
229 don't belong to a particular component.
150 """
230 """
151 self.default_config = Config()
231 c = Config()
152 self.default_config.Global.ipython_dir = get_ipython_dir()
232 c.Global.ipython_dir = get_ipython_dir()
153 self.default_config.Global.log_level = self.log_level
233 c.Global.log_level = self.log_level
234 self.default_config = c
154
235
155 def log_default_config(self):
236 def log_default_config(self):
156 self.log.debug('Default config loaded:')
237 self.log.debug('Default config loaded:')
157 self.log.debug(repr(self.default_config))
238 self.log.debug(repr(self.default_config))
158
239
159 def set_default_config_log_level(self):
240 def set_default_config_log_level(self):
160 try:
241 try:
161 self.log_level = self.default_config.Global.log_level
242 self.log_level = self.default_config.Global.log_level
162 except AttributeError:
243 except AttributeError:
163 # Fallback to the default_log_level class attribute
244 # Fallback to the default_log_level class attribute
164 pass
245 pass
165
246
166 def create_command_line_config(self):
247 def create_command_line_config(self):
167 """Create and return a command line config loader."""
248 """Create and return a command line config loader."""
168 return BaseAppArgParseConfigLoader(
249 return self.command_line_loader(
250 self.argv,
169 description=self.description,
251 description=self.description,
170 version=release.version
252 version=release.version,
253 usage=self.usage
171 )
254 )
172
255
173 def pre_load_command_line_config(self):
256 def pre_load_command_line_config(self):
174 """Do actions just before loading the command line config."""
257 """Do actions just before loading the command line config."""
175 pass
258 pass
176
259
177 def load_command_line_config(self):
260 def load_command_line_config(self):
178 """Load the command line config."""
261 """Load the command line config."""
179 loader = self.create_command_line_config()
262 loader = self.create_command_line_config()
180 self.command_line_config = loader.load_config()
263 self.command_line_config = loader.load_config()
181 self.extra_args = loader.get_extra_args()
264 self.extra_args = loader.get_extra_args()
182
265
183 def set_command_line_config_log_level(self):
266 def set_command_line_config_log_level(self):
184 try:
267 try:
185 self.log_level = self.command_line_config.Global.log_level
268 self.log_level = self.command_line_config.Global.log_level
186 except AttributeError:
269 except AttributeError:
187 pass
270 pass
188
271
189 def post_load_command_line_config(self):
272 def post_load_command_line_config(self):
190 """Do actions just after loading the command line config."""
273 """Do actions just after loading the command line config."""
191 pass
274 pass
192
275
193 def log_command_line_config(self):
276 def log_command_line_config(self):
194 self.log.debug("Command line config loaded:")
277 self.log.debug("Command line config loaded:")
195 self.log.debug(repr(self.command_line_config))
278 self.log.debug(repr(self.command_line_config))
196
279
197 def find_ipython_dir(self):
280 def find_ipython_dir(self):
198 """Set the IPython directory.
281 """Set the IPython directory.
199
282
200 This sets ``self.ipython_dir``, but the actual value that is passed
283 This sets ``self.ipython_dir``, but the actual value that is passed to
201 to the application is kept in either ``self.default_config`` or
284 the application is kept in either ``self.default_config`` or
202 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
285 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
203 ``sys.path`` so config files there can be references by other config
286 ``sys.path`` so config files there can be referenced by other config
204 files.
287 files.
205 """
288 """
206
289
207 try:
290 try:
208 self.ipython_dir = self.command_line_config.Global.ipython_dir
291 self.ipython_dir = self.command_line_config.Global.ipython_dir
209 except AttributeError:
292 except AttributeError:
210 self.ipython_dir = self.default_config.Global.ipython_dir
293 self.ipython_dir = self.default_config.Global.ipython_dir
211 sys.path.append(os.path.abspath(self.ipython_dir))
294 sys.path.append(os.path.abspath(self.ipython_dir))
212 if not os.path.isdir(self.ipython_dir):
295 if not os.path.isdir(self.ipython_dir):
213 os.makedirs(self.ipython_dir, mode=0777)
296 os.makedirs(self.ipython_dir, mode=0777)
214 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
297 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
215
298
216 def find_resources(self):
299 def find_resources(self):
217 """Find other resources that need to be in place.
300 """Find other resources that need to be in place.
218
301
219 Things like cluster directories need to be in place to find the
302 Things like cluster directories need to be in place to find the
220 config file. These happen right after the IPython directory has
303 config file. These happen right after the IPython directory has
221 been set.
304 been set.
222 """
305 """
223 pass
306 pass
224
307
225 def find_config_file_name(self):
308 def find_config_file_name(self):
226 """Find the config file name for this application.
309 """Find the config file name for this application.
227
310
228 This must set ``self.config_file_name`` to the filename of the
311 This must set ``self.config_file_name`` to the filename of the
229 config file to use (just the filename). The search paths for the
312 config file to use (just the filename). The search paths for the
230 config file are set in :meth:`find_config_file_paths` and then passed
313 config file are set in :meth:`find_config_file_paths` and then passed
231 to the config file loader where they are resolved to an absolute path.
314 to the config file loader where they are resolved to an absolute path.
232
315
233 If a profile has been set at the command line, this will resolve
316 If a profile has been set at the command line, this will resolve it.
234 it.
235 """
317 """
236
237 try:
318 try:
238 self.config_file_name = self.command_line_config.Global.config_file
319 self.config_file_name = self.command_line_config.Global.config_file
239 except AttributeError:
320 except AttributeError:
240 pass
321 pass
322 else:
323 return
241
324
242 try:
325 try:
243 self.profile_name = self.command_line_config.Global.profile
326 self.profile_name = self.command_line_config.Global.profile
244 name_parts = self.config_file_name.split('.')
327 except AttributeError:
328 # Just use the default as there is no profile
329 self.config_file_name = self.default_config_file_name
330 else:
331 # Use the default config file name and profile name if set
332 # to determine the used config file name.
333 name_parts = self.default_config_file_name.split('.')
245 name_parts.insert(1, u'_' + self.profile_name + u'.')
334 name_parts.insert(1, u'_' + self.profile_name + u'.')
246 self.config_file_name = ''.join(name_parts)
335 self.config_file_name = ''.join(name_parts)
247 except AttributeError:
248 pass
249
336
250 def find_config_file_paths(self):
337 def find_config_file_paths(self):
251 """Set the search paths for resolving the config file.
338 """Set the search paths for resolving the config file.
252
339
253 This must set ``self.config_file_paths`` to a sequence of search
340 This must set ``self.config_file_paths`` to a sequence of search
254 paths to pass to the config file loader.
341 paths to pass to the config file loader.
255 """
342 """
256 self.config_file_paths = (os.getcwd(), self.ipython_dir)
343 # Include our own profiles directory last, so that users can still find
344 # our shipped copies of builtin profiles even if they don't have them
345 # in their local ipython directory.
346 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
347 self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir)
257
348
258 def pre_load_file_config(self):
349 def pre_load_file_config(self):
259 """Do actions before the config file is loaded."""
350 """Do actions before the config file is loaded."""
260 pass
351 pass
261
352
262 def load_file_config(self):
353 def load_file_config(self):
263 """Load the config file.
354 """Load the config file.
264
355
265 This tries to load the config file from disk. If successful, the
356 This tries to load the config file from disk. If successful, the
266 ``CONFIG_FILE`` config variable is set to the resolved config file
357 ``CONFIG_FILE`` config variable is set to the resolved config file
267 location. If not successful, an empty config is used.
358 location. If not successful, an empty config is used.
268 """
359 """
269 self.log.debug("Attempting to load config file: %s" % self.config_file_name)
360 self.log.debug("Attempting to load config file: %s" %
361 self.config_file_name)
270 loader = PyFileConfigLoader(self.config_file_name,
362 loader = PyFileConfigLoader(self.config_file_name,
271 path=self.config_file_paths)
363 path=self.config_file_paths)
272 try:
364 try:
273 self.file_config = loader.load_config()
365 self.file_config = loader.load_config()
274 self.file_config.Global.config_file = loader.full_filename
366 self.file_config.Global.config_file = loader.full_filename
275 except IOError:
367 except IOError:
276 # Only warn if the default config file was NOT being used.
368 # Only warn if the default config file was NOT being used.
277 if not self.config_file_name==self.default_config_file_name:
369 if not self.config_file_name==self.default_config_file_name:
278 self.log.warn("Config file not found, skipping: %s" % \
370 self.log.warn("Config file not found, skipping: %s" %
279 self.config_file_name, exc_info=True)
371 self.config_file_name, exc_info=True)
280 self.file_config = Config()
372 self.file_config = Config()
281 except:
373 except:
282 self.log.warn("Error loading config file: %s" % \
374 self.log.warn("Error loading config file: %s" %
283 self.config_file_name, exc_info=True)
375 self.config_file_name, exc_info=True)
284 self.file_config = Config()
376 self.file_config = Config()
285
377
286 def set_file_config_log_level(self):
378 def set_file_config_log_level(self):
287 # We need to keeep self.log_level updated. But we only use the value
379 # We need to keeep self.log_level updated. But we only use the value
288 # of the file_config if a value was not specified at the command
380 # of the file_config if a value was not specified at the command
289 # line, because the command line overrides everything.
381 # line, because the command line overrides everything.
290 if not hasattr(self.command_line_config.Global, 'log_level'):
382 if not hasattr(self.command_line_config.Global, 'log_level'):
291 try:
383 try:
292 self.log_level = self.file_config.Global.log_level
384 self.log_level = self.file_config.Global.log_level
293 except AttributeError:
385 except AttributeError:
294 pass # Use existing value
386 pass # Use existing value
295
387
296 def post_load_file_config(self):
388 def post_load_file_config(self):
297 """Do actions after the config file is loaded."""
389 """Do actions after the config file is loaded."""
298 pass
390 pass
299
391
300 def log_file_config(self):
392 def log_file_config(self):
301 if hasattr(self.file_config.Global, 'config_file'):
393 if hasattr(self.file_config.Global, 'config_file'):
302 self.log.debug("Config file loaded: %s" % self.file_config.Global.config_file)
394 self.log.debug("Config file loaded: %s" %
395 self.file_config.Global.config_file)
303 self.log.debug(repr(self.file_config))
396 self.log.debug(repr(self.file_config))
304
397
305 def merge_configs(self):
398 def merge_configs(self):
306 """Merge the default, command line and file config objects."""
399 """Merge the default, command line and file config objects."""
307 config = Config()
400 config = Config()
308 config._merge(self.default_config)
401 config._merge(self.default_config)
309 config._merge(self.file_config)
402 config._merge(self.file_config)
310 config._merge(self.command_line_config)
403 config._merge(self.command_line_config)
404
405 # XXX fperez - propose to Brian we rename master_config to simply
406 # config, I think this is going to be heavily used in examples and
407 # application code and the name is shorter/easier to find/remember.
408 # For now, just alias it...
311 self.master_config = config
409 self.master_config = config
410 self.config = config
312
411
313 def log_master_config(self):
412 def log_master_config(self):
314 self.log.debug("Master config created:")
413 self.log.debug("Master config created:")
315 self.log.debug(repr(self.master_config))
414 self.log.debug(repr(self.master_config))
316
415
317 def pre_construct(self):
416 def pre_construct(self):
318 """Do actions after the config has been built, but before construct."""
417 """Do actions after the config has been built, but before construct."""
319 pass
418 pass
320
419
321 def construct(self):
420 def construct(self):
322 """Construct the main components that make up this app."""
421 """Construct the main components that make up this app."""
323 self.log.debug("Constructing components for application")
422 self.log.debug("Constructing components for application")
324
423
325 def post_construct(self):
424 def post_construct(self):
326 """Do actions after construct, but before starting the app."""
425 """Do actions after construct, but before starting the app."""
327 pass
426 pass
328
427
329 def start_app(self):
428 def start_app(self):
330 """Actually start the app."""
429 """Actually start the app."""
331 self.log.debug("Starting application")
430 self.log.debug("Starting application")
332
431
333 #-------------------------------------------------------------------------
432 #-------------------------------------------------------------------------
334 # Utility methods
433 # Utility methods
335 #-------------------------------------------------------------------------
434 #-------------------------------------------------------------------------
336
435
337 def abort(self):
338 """Abort the starting of the application."""
339 if self._exiting:
340 pass
341 else:
342 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
343 self._exiting = True
344 sys.exit(1)
345
346 def exit(self, exit_status=0):
436 def exit(self, exit_status=0):
347 if self._exiting:
437 if self._exiting:
348 pass
438 pass
349 else:
439 else:
350 self.log.debug("Exiting application: %s" % self.name)
440 self.log.debug("Exiting application: %s" % self.name)
351 self._exiting = True
441 self._exiting = True
352 sys.exit(exit_status)
442 sys.exit(exit_status)
353
443
354 def attempt(self, func, action='abort'):
444 def attempt(self, func):
355 try:
445 try:
356 func()
446 func()
357 except SystemExit:
447 except SystemExit:
358 raise
448 raise
359 except:
449 except:
360 if action == 'abort':
450 self.log.critical("Aborting application: %s" % self.name,
361 self.abort()
451 exc_info=True)
362 elif action == 'exit':
452 self.exit(0)
363 self.exit(0)
364
453
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
@@ -1,642 +1,658 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 __getattr__ hook is found. Since it is the responsibility of the
34 __getattr__ hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47
48 """
47 """
49
48
50 #*****************************************************************************
49 #*****************************************************************************
51 #
50 #
52 # Since this file is essentially a minimally modified copy of the rlcompleter
51 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # module which is part of the standard Python distribution, I assume that the
52 # module which is part of the standard Python distribution, I assume that the
54 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
55 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
56 #
55 #
56 # Copyright (C) 2008-2010 IPython Development Team
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64
64
65 #-----------------------------------------------------------------------------
66 # Imports
67 #-----------------------------------------------------------------------------
68
65 import __builtin__
69 import __builtin__
66 import __main__
70 import __main__
67 import glob
71 import glob
72 import inspect
68 import itertools
73 import itertools
69 import keyword
74 import keyword
70 import os
75 import os
71 import re
76 import re
72 import shlex
77 import shlex
73 import sys
78 import sys
74 import types
75
79
76 from IPython.core.error import TryNext
80 from IPython.core.error import TryNext
77 from IPython.core.prefilter import ESC_MAGIC
81 from IPython.core.prefilter import ESC_MAGIC
78
79 import IPython.utils.rlineimpl as readline
80 from IPython.utils.ipstruct import Struct
81 from IPython.utils import generics
82 from IPython.utils import generics
83 from IPython.utils.frame import debugx
84 from IPython.utils.dir2 import dir2
85 import IPython.utils.rlineimpl as readline
82
86
83 # Python 2.4 offers sets as a builtin
87 #-----------------------------------------------------------------------------
84 try:
88 # Globals
85 set()
89 #-----------------------------------------------------------------------------
86 except NameError:
87 from sets import Set as set
88
89 from IPython.utils.genutils import debugx, dir2
90
90
91 # Public API
91 __all__ = ['Completer','IPCompleter']
92 __all__ = ['Completer','IPCompleter']
92
93
94 if sys.platform == 'win32':
95 PROTECTABLES = ' '
96 else:
97 PROTECTABLES = ' ()'
98
99 #-----------------------------------------------------------------------------
100 # Main functions and classes
101 #-----------------------------------------------------------------------------
102
103 def protect_filename(s):
104 """Escape a string to protect certain characters."""
105
106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
107 for ch in s])
108
109
110 def single_dir_expand(matches):
111 "Recursively expand match lists containing a single dir."
112
113 if len(matches) == 1 and os.path.isdir(matches[0]):
114 # Takes care of links to directories also. Use '/'
115 # explicitly, even under Windows, so that name completions
116 # don't end up escaped.
117 d = matches[0]
118 if d[-1] in ['/','\\']:
119 d = d[:-1]
120
121 subdirs = os.listdir(d)
122 if subdirs:
123 matches = [ (d + '/' + p) for p in subdirs]
124 return single_dir_expand(matches)
125 else:
126 return matches
127 else:
128 return matches
129
130 class Bunch: pass
131
93 class Completer:
132 class Completer:
94 def __init__(self,namespace=None,global_namespace=None):
133 def __init__(self,namespace=None,global_namespace=None):
95 """Create a new completer for the command line.
134 """Create a new completer for the command line.
96
135
97 Completer([namespace,global_namespace]) -> completer instance.
136 Completer([namespace,global_namespace]) -> completer instance.
98
137
99 If unspecified, the default namespace where completions are performed
138 If unspecified, the default namespace where completions are performed
100 is __main__ (technically, __main__.__dict__). Namespaces should be
139 is __main__ (technically, __main__.__dict__). Namespaces should be
101 given as dictionaries.
140 given as dictionaries.
102
141
103 An optional second namespace can be given. This allows the completer
142 An optional second namespace can be given. This allows the completer
104 to handle cases where both the local and global scopes need to be
143 to handle cases where both the local and global scopes need to be
105 distinguished.
144 distinguished.
106
145
107 Completer instances should be used as the completion mechanism of
146 Completer instances should be used as the completion mechanism of
108 readline via the set_completer() call:
147 readline via the set_completer() call:
109
148
110 readline.set_completer(Completer(my_namespace).complete)
149 readline.set_completer(Completer(my_namespace).complete)
111 """
150 """
112
151
113 # Don't bind to namespace quite yet, but flag whether the user wants a
152 # Don't bind to namespace quite yet, but flag whether the user wants a
114 # specific namespace or to use __main__.__dict__. This will allow us
153 # specific namespace or to use __main__.__dict__. This will allow us
115 # to bind to __main__.__dict__ at completion time, not now.
154 # to bind to __main__.__dict__ at completion time, not now.
116 if namespace is None:
155 if namespace is None:
117 self.use_main_ns = 1
156 self.use_main_ns = 1
118 else:
157 else:
119 self.use_main_ns = 0
158 self.use_main_ns = 0
120 self.namespace = namespace
159 self.namespace = namespace
121
160
122 # The global namespace, if given, can be bound directly
161 # The global namespace, if given, can be bound directly
123 if global_namespace is None:
162 if global_namespace is None:
124 self.global_namespace = {}
163 self.global_namespace = {}
125 else:
164 else:
126 self.global_namespace = global_namespace
165 self.global_namespace = global_namespace
127
166
128 def complete(self, text, state):
167 def complete(self, text, state):
129 """Return the next possible completion for 'text'.
168 """Return the next possible completion for 'text'.
130
169
131 This is called successively with state == 0, 1, 2, ... until it
170 This is called successively with state == 0, 1, 2, ... until it
132 returns None. The completion should begin with 'text'.
171 returns None. The completion should begin with 'text'.
133
172
134 """
173 """
135 if self.use_main_ns:
174 if self.use_main_ns:
136 self.namespace = __main__.__dict__
175 self.namespace = __main__.__dict__
137
176
138 if state == 0:
177 if state == 0:
139 if "." in text:
178 if "." in text:
140 self.matches = self.attr_matches(text)
179 self.matches = self.attr_matches(text)
141 else:
180 else:
142 self.matches = self.global_matches(text)
181 self.matches = self.global_matches(text)
143 try:
182 try:
144 return self.matches[state]
183 return self.matches[state]
145 except IndexError:
184 except IndexError:
146 return None
185 return None
147
186
148 def global_matches(self, text):
187 def global_matches(self, text):
149 """Compute matches when text is a simple name.
188 """Compute matches when text is a simple name.
150
189
151 Return a list of all keywords, built-in functions and names currently
190 Return a list of all keywords, built-in functions and names currently
152 defined in self.namespace or self.global_namespace that match.
191 defined in self.namespace or self.global_namespace that match.
153
192
154 """
193 """
194 #print 'Completer->global_matches, txt=%r' % text # dbg
155 matches = []
195 matches = []
156 match_append = matches.append
196 match_append = matches.append
157 n = len(text)
197 n = len(text)
158 for lst in [keyword.kwlist,
198 for lst in [keyword.kwlist,
159 __builtin__.__dict__.keys(),
199 __builtin__.__dict__.keys(),
160 self.namespace.keys(),
200 self.namespace.keys(),
161 self.global_namespace.keys()]:
201 self.global_namespace.keys()]:
162 for word in lst:
202 for word in lst:
163 if word[:n] == text and word != "__builtins__":
203 if word[:n] == text and word != "__builtins__":
164 match_append(word)
204 match_append(word)
165 return matches
205 return matches
166
206
167 def attr_matches(self, text):
207 def attr_matches(self, text):
168 """Compute matches when text contains a dot.
208 """Compute matches when text contains a dot.
169
209
170 Assuming the text is of the form NAME.NAME....[NAME], and is
210 Assuming the text is of the form NAME.NAME....[NAME], and is
171 evaluatable in self.namespace or self.global_namespace, it will be
211 evaluatable in self.namespace or self.global_namespace, it will be
172 evaluated and its attributes (as revealed by dir()) are used as
212 evaluated and its attributes (as revealed by dir()) are used as
173 possible completions. (For class instances, class members are are
213 possible completions. (For class instances, class members are are
174 also considered.)
214 also considered.)
175
215
176 WARNING: this can still invoke arbitrary C code, if an object
216 WARNING: this can still invoke arbitrary C code, if an object
177 with a __getattr__ hook is evaluated.
217 with a __getattr__ hook is evaluated.
178
218
179 """
219 """
180 import re
181
220
221 #print 'Completer->attr_matches, txt=%r' % text # dbg
182 # Another option, seems to work great. Catches things like ''.<tab>
222 # Another option, seems to work great. Catches things like ''.<tab>
183 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
223 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
184
224
185 if not m:
225 if not m:
186 return []
226 return []
187
227
188 expr, attr = m.group(1, 3)
228 expr, attr = m.group(1, 3)
189 try:
229 try:
190 obj = eval(expr, self.namespace)
230 obj = eval(expr, self.namespace)
191 except:
231 except:
192 try:
232 try:
193 obj = eval(expr, self.global_namespace)
233 obj = eval(expr, self.global_namespace)
194 except:
234 except:
195 return []
235 return []
196
236
197 words = dir2(obj)
237 words = dir2(obj)
198
238
199 try:
239 try:
200 words = generics.complete_object(obj, words)
240 words = generics.complete_object(obj, words)
201 except TryNext:
241 except TryNext:
202 pass
242 pass
203 # Build match list to return
243 # Build match list to return
204 n = len(attr)
244 n = len(attr)
205 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
245 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
206 return res
246 return res
207
247
248
208 class IPCompleter(Completer):
249 class IPCompleter(Completer):
209 """Extension of the completer class with IPython-specific features"""
250 """Extension of the completer class with IPython-specific features"""
210
251
211 def __init__(self,shell,namespace=None,global_namespace=None,
252 def __init__(self,shell,namespace=None,global_namespace=None,
212 omit__names=0,alias_table=None):
253 omit__names=0,alias_table=None):
213 """IPCompleter() -> completer
254 """IPCompleter() -> completer
214
255
215 Return a completer object suitable for use by the readline library
256 Return a completer object suitable for use by the readline library
216 via readline.set_completer().
257 via readline.set_completer().
217
258
218 Inputs:
259 Inputs:
219
260
220 - shell: a pointer to the ipython shell itself. This is needed
261 - shell: a pointer to the ipython shell itself. This is needed
221 because this completer knows about magic functions, and those can
262 because this completer knows about magic functions, and those can
222 only be accessed via the ipython instance.
263 only be accessed via the ipython instance.
223
264
224 - namespace: an optional dict where completions are performed.
265 - namespace: an optional dict where completions are performed.
225
266
226 - global_namespace: secondary optional dict for completions, to
267 - global_namespace: secondary optional dict for completions, to
227 handle cases (such as IPython embedded inside functions) where
268 handle cases (such as IPython embedded inside functions) where
228 both Python scopes are visible.
269 both Python scopes are visible.
229
270
230 - The optional omit__names parameter sets the completer to omit the
271 - The optional omit__names parameter sets the completer to omit the
231 'magic' names (__magicname__) for python objects unless the text
272 'magic' names (__magicname__) for python objects unless the text
232 to be completed explicitly starts with one or more underscores.
273 to be completed explicitly starts with one or more underscores.
233
274
234 - If alias_table is supplied, it should be a dictionary of aliases
275 - If alias_table is supplied, it should be a dictionary of aliases
235 to complete. """
276 to complete. """
236
277
237 Completer.__init__(self,namespace,global_namespace)
278 Completer.__init__(self,namespace,global_namespace)
238 self.magic_prefix = shell.name+'.magic_'
279
239 self.magic_escape = ESC_MAGIC
280 self.magic_escape = ESC_MAGIC
240 self.readline = readline
281 self.readline = readline
241 delims = self.readline.get_completer_delims()
282 delims = self.readline.get_completer_delims()
242 delims = delims.replace(self.magic_escape,'')
283 delims = delims.replace(self.magic_escape,'')
243 self.readline.set_completer_delims(delims)
284 self.readline.set_completer_delims(delims)
244 self.get_line_buffer = self.readline.get_line_buffer
285 self.get_line_buffer = self.readline.get_line_buffer
245 self.get_endidx = self.readline.get_endidx
286 self.get_endidx = self.readline.get_endidx
246 self.omit__names = omit__names
287 self.omit__names = omit__names
247 self.merge_completions = shell.readline_merge_completions
288 self.merge_completions = shell.readline_merge_completions
289 self.shell = shell.shell
248 if alias_table is None:
290 if alias_table is None:
249 alias_table = {}
291 alias_table = {}
250 self.alias_table = alias_table
292 self.alias_table = alias_table
251 # Regexp to split filenames with spaces in them
293 # Regexp to split filenames with spaces in them
252 self.space_name_re = re.compile(r'([^\\] )')
294 self.space_name_re = re.compile(r'([^\\] )')
253 # Hold a local ref. to glob.glob for speed
295 # Hold a local ref. to glob.glob for speed
254 self.glob = glob.glob
296 self.glob = glob.glob
255
297
256 # Determine if we are running on 'dumb' terminals, like (X)Emacs
298 # Determine if we are running on 'dumb' terminals, like (X)Emacs
257 # buffers, to avoid completion problems.
299 # buffers, to avoid completion problems.
258 term = os.environ.get('TERM','xterm')
300 term = os.environ.get('TERM','xterm')
259 self.dumb_terminal = term in ['dumb','emacs']
301 self.dumb_terminal = term in ['dumb','emacs']
260
302
261 # Special handling of backslashes needed in win32 platforms
303 # Special handling of backslashes needed in win32 platforms
262 if sys.platform == "win32":
304 if sys.platform == "win32":
263 self.clean_glob = self._clean_glob_win32
305 self.clean_glob = self._clean_glob_win32
264 else:
306 else:
265 self.clean_glob = self._clean_glob
307 self.clean_glob = self._clean_glob
308
309 # All active matcher routines for completion
266 self.matchers = [self.python_matches,
310 self.matchers = [self.python_matches,
267 self.file_matches,
311 self.file_matches,
312 self.magic_matches,
268 self.alias_matches,
313 self.alias_matches,
269 self.python_func_kw_matches]
314 self.python_func_kw_matches]
270
271
315
272 # Code contributed by Alex Schmolck, for ipython/emacs integration
316 # Code contributed by Alex Schmolck, for ipython/emacs integration
273 def all_completions(self, text):
317 def all_completions(self, text):
274 """Return all possible completions for the benefit of emacs."""
318 """Return all possible completions for the benefit of emacs."""
275
319
276 completions = []
320 completions = []
277 comp_append = completions.append
321 comp_append = completions.append
278 try:
322 try:
279 for i in xrange(sys.maxint):
323 for i in xrange(sys.maxint):
280 res = self.complete(text, i)
324 res = self.complete(text, i)
281
325 if not res:
282 if not res: break
326 break
283
284 comp_append(res)
327 comp_append(res)
285 #XXX workaround for ``notDefined.<tab>``
328 #XXX workaround for ``notDefined.<tab>``
286 except NameError:
329 except NameError:
287 pass
330 pass
288 return completions
331 return completions
289 # /end Alex Schmolck code.
332 # /end Alex Schmolck code.
290
333
291 def _clean_glob(self,text):
334 def _clean_glob(self,text):
292 return self.glob("%s*" % text)
335 return self.glob("%s*" % text)
293
336
294 def _clean_glob_win32(self,text):
337 def _clean_glob_win32(self,text):
295 return [f.replace("\\","/")
338 return [f.replace("\\","/")
296 for f in self.glob("%s*" % text)]
339 for f in self.glob("%s*" % text)]
297
340
298 def file_matches(self, text):
341 def file_matches(self, text):
299 """Match filenames, expanding ~USER type strings.
342 """Match filenames, expanding ~USER type strings.
300
343
301 Most of the seemingly convoluted logic in this completer is an
344 Most of the seemingly convoluted logic in this completer is an
302 attempt to handle filenames with spaces in them. And yet it's not
345 attempt to handle filenames with spaces in them. And yet it's not
303 quite perfect, because Python's readline doesn't expose all of the
346 quite perfect, because Python's readline doesn't expose all of the
304 GNU readline details needed for this to be done correctly.
347 GNU readline details needed for this to be done correctly.
305
348
306 For a filename with a space in it, the printed completions will be
349 For a filename with a space in it, the printed completions will be
307 only the parts after what's already been typed (instead of the
350 only the parts after what's already been typed (instead of the
308 full completions, as is normally done). I don't think with the
351 full completions, as is normally done). I don't think with the
309 current (as of Python 2.3) Python readline it's possible to do
352 current (as of Python 2.3) Python readline it's possible to do
310 better."""
353 better."""
311
354
312 #print 'Completer->file_matches: <%s>' % text # dbg
355 #print 'Completer->file_matches: <%s>' % text # dbg
313
356
314 # chars that require escaping with backslash - i.e. chars
357 # chars that require escaping with backslash - i.e. chars
315 # that readline treats incorrectly as delimiters, but we
358 # that readline treats incorrectly as delimiters, but we
316 # don't want to treat as delimiters in filename matching
359 # don't want to treat as delimiters in filename matching
317 # when escaped with backslash
360 # when escaped with backslash
318
361
319 if sys.platform == 'win32':
320 protectables = ' '
321 else:
322 protectables = ' ()'
323
324 if text.startswith('!'):
362 if text.startswith('!'):
325 text = text[1:]
363 text = text[1:]
326 text_prefix = '!'
364 text_prefix = '!'
327 else:
365 else:
328 text_prefix = ''
366 text_prefix = ''
329
367
330 def protect_filename(s):
331 return "".join([(ch in protectables and '\\' + ch or ch)
332 for ch in s])
333
334 def single_dir_expand(matches):
335 "Recursively expand match lists containing a single dir."
336
337 if len(matches) == 1 and os.path.isdir(matches[0]):
338 # Takes care of links to directories also. Use '/'
339 # explicitly, even under Windows, so that name completions
340 # don't end up escaped.
341 d = matches[0]
342 if d[-1] in ['/','\\']:
343 d = d[:-1]
344
345 subdirs = os.listdir(d)
346 if subdirs:
347 matches = [ (d + '/' + p) for p in subdirs]
348 return single_dir_expand(matches)
349 else:
350 return matches
351 else:
352 return matches
353
354 lbuf = self.lbuf
368 lbuf = self.lbuf
355 open_quotes = 0 # track strings with open quotes
369 open_quotes = 0 # track strings with open quotes
356 try:
370 try:
357 lsplit = shlex.split(lbuf)[-1]
371 lsplit = shlex.split(lbuf)[-1]
358 except ValueError:
372 except ValueError:
359 # typically an unmatched ", or backslash without escaped char.
373 # typically an unmatched ", or backslash without escaped char.
360 if lbuf.count('"')==1:
374 if lbuf.count('"')==1:
361 open_quotes = 1
375 open_quotes = 1
362 lsplit = lbuf.split('"')[-1]
376 lsplit = lbuf.split('"')[-1]
363 elif lbuf.count("'")==1:
377 elif lbuf.count("'")==1:
364 open_quotes = 1
378 open_quotes = 1
365 lsplit = lbuf.split("'")[-1]
379 lsplit = lbuf.split("'")[-1]
366 else:
380 else:
367 return []
381 return []
368 except IndexError:
382 except IndexError:
369 # tab pressed on empty line
383 # tab pressed on empty line
370 lsplit = ""
384 lsplit = ""
371
385
372 if lsplit != protect_filename(lsplit):
386 if lsplit != protect_filename(lsplit):
373 # if protectables are found, do matching on the whole escaped
387 # if protectables are found, do matching on the whole escaped
374 # name
388 # name
375 has_protectables = 1
389 has_protectables = 1
376 text0,text = text,lsplit
390 text0,text = text,lsplit
377 else:
391 else:
378 has_protectables = 0
392 has_protectables = 0
379 text = os.path.expanduser(text)
393 text = os.path.expanduser(text)
380
394
381 if text == "":
395 if text == "":
382 return [text_prefix + protect_filename(f) for f in self.glob("*")]
396 return [text_prefix + protect_filename(f) for f in self.glob("*")]
383
397
384 m0 = self.clean_glob(text.replace('\\',''))
398 m0 = self.clean_glob(text.replace('\\',''))
385 if has_protectables:
399 if has_protectables:
386 # If we had protectables, we need to revert our changes to the
400 # If we had protectables, we need to revert our changes to the
387 # beginning of filename so that we don't double-write the part
401 # beginning of filename so that we don't double-write the part
388 # of the filename we have so far
402 # of the filename we have so far
389 len_lsplit = len(lsplit)
403 len_lsplit = len(lsplit)
390 matches = [text_prefix + text0 +
404 matches = [text_prefix + text0 +
391 protect_filename(f[len_lsplit:]) for f in m0]
405 protect_filename(f[len_lsplit:]) for f in m0]
392 else:
406 else:
393 if open_quotes:
407 if open_quotes:
394 # if we have a string with an open quote, we don't need to
408 # if we have a string with an open quote, we don't need to
395 # protect the names at all (and we _shouldn't_, as it
409 # protect the names at all (and we _shouldn't_, as it
396 # would cause bugs when the filesystem call is made).
410 # would cause bugs when the filesystem call is made).
397 matches = m0
411 matches = m0
398 else:
412 else:
399 matches = [text_prefix +
413 matches = [text_prefix +
400 protect_filename(f) for f in m0]
414 protect_filename(f) for f in m0]
401
415
402 #print 'mm',matches # dbg
416 #print 'mm',matches # dbg
403 return single_dir_expand(matches)
417 return single_dir_expand(matches)
404
418
419 def magic_matches(self, text):
420 """Match magics"""
421 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
422 # Get all shell magics now rather than statically, so magics loaded at
423 # runtime show up too
424 magics = self.shell.lsmagic()
425 pre = self.magic_escape
426 baretext = text.lstrip(pre)
427 return [ pre+m for m in magics if m.startswith(baretext)]
428
405 def alias_matches(self, text):
429 def alias_matches(self, text):
406 """Match internal system aliases"""
430 """Match internal system aliases"""
407 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
431 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
408
432
409 # if we are not in the first 'item', alias matching
433 # if we are not in the first 'item', alias matching
410 # doesn't make sense - unless we are starting with 'sudo' command.
434 # doesn't make sense - unless we are starting with 'sudo' command.
411 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
435 if ' ' in self.lbuf.lstrip() and \
436 not self.lbuf.lstrip().startswith('sudo'):
412 return []
437 return []
413 text = os.path.expanduser(text)
438 text = os.path.expanduser(text)
414 aliases = self.alias_table.keys()
439 aliases = self.alias_table.keys()
415 if text == "":
440 if text == "":
416 return aliases
441 return aliases
417 else:
442 else:
418 return [alias for alias in aliases if alias.startswith(text)]
443 return [alias for alias in aliases if alias.startswith(text)]
419
444
420 def python_matches(self,text):
445 def python_matches(self,text):
421 """Match attributes or global python names"""
446 """Match attributes or global python names"""
422
447
423 #print 'Completer->python_matches, txt=<%s>' % text # dbg
448 #print 'Completer->python_matches, txt=%r' % text # dbg
424 if "." in text:
449 if "." in text:
425 try:
450 try:
426 matches = self.attr_matches(text)
451 matches = self.attr_matches(text)
427 if text.endswith('.') and self.omit__names:
452 if text.endswith('.') and self.omit__names:
428 if self.omit__names == 1:
453 if self.omit__names == 1:
429 # true if txt is _not_ a __ name, false otherwise:
454 # true if txt is _not_ a __ name, false otherwise:
430 no__name = (lambda txt:
455 no__name = (lambda txt:
431 re.match(r'.*\.__.*?__',txt) is None)
456 re.match(r'.*\.__.*?__',txt) is None)
432 else:
457 else:
433 # true if txt is _not_ a _ name, false otherwise:
458 # true if txt is _not_ a _ name, false otherwise:
434 no__name = (lambda txt:
459 no__name = (lambda txt:
435 re.match(r'.*\._.*?',txt) is None)
460 re.match(r'.*\._.*?',txt) is None)
436 matches = filter(no__name, matches)
461 matches = filter(no__name, matches)
437 except NameError:
462 except NameError:
438 # catches <undefined attributes>.<tab>
463 # catches <undefined attributes>.<tab>
439 matches = []
464 matches = []
440 else:
465 else:
441 matches = self.global_matches(text)
466 matches = self.global_matches(text)
442 # this is so completion finds magics when automagic is on:
467
443 if (matches == [] and
444 not text.startswith(os.sep) and
445 not ' ' in self.lbuf):
446 matches = self.attr_matches(self.magic_prefix+text)
447 return matches
468 return matches
448
469
449 def _default_arguments(self, obj):
470 def _default_arguments(self, obj):
450 """Return the list of default arguments of obj if it is callable,
471 """Return the list of default arguments of obj if it is callable,
451 or empty list otherwise."""
472 or empty list otherwise."""
452
473
453 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
474 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
454 # for classes, check for __init__,__new__
475 # for classes, check for __init__,__new__
455 if inspect.isclass(obj):
476 if inspect.isclass(obj):
456 obj = (getattr(obj,'__init__',None) or
477 obj = (getattr(obj,'__init__',None) or
457 getattr(obj,'__new__',None))
478 getattr(obj,'__new__',None))
458 # for all others, check if they are __call__able
479 # for all others, check if they are __call__able
459 elif hasattr(obj, '__call__'):
480 elif hasattr(obj, '__call__'):
460 obj = obj.__call__
481 obj = obj.__call__
461 # XXX: is there a way to handle the builtins ?
482 # XXX: is there a way to handle the builtins ?
462 try:
483 try:
463 args,_,_1,defaults = inspect.getargspec(obj)
484 args,_,_1,defaults = inspect.getargspec(obj)
464 if defaults:
485 if defaults:
465 return args[-len(defaults):]
486 return args[-len(defaults):]
466 except TypeError: pass
487 except TypeError: pass
467 return []
488 return []
468
489
469 def python_func_kw_matches(self,text):
490 def python_func_kw_matches(self,text):
470 """Match named parameters (kwargs) of the last open function"""
491 """Match named parameters (kwargs) of the last open function"""
471
492
472 if "." in text: # a parameter cannot be dotted
493 if "." in text: # a parameter cannot be dotted
473 return []
494 return []
474 try: regexp = self.__funcParamsRegex
495 try: regexp = self.__funcParamsRegex
475 except AttributeError:
496 except AttributeError:
476 regexp = self.__funcParamsRegex = re.compile(r'''
497 regexp = self.__funcParamsRegex = re.compile(r'''
477 '.*?' | # single quoted strings or
498 '.*?' | # single quoted strings or
478 ".*?" | # double quoted strings or
499 ".*?" | # double quoted strings or
479 \w+ | # identifier
500 \w+ | # identifier
480 \S # other characters
501 \S # other characters
481 ''', re.VERBOSE | re.DOTALL)
502 ''', re.VERBOSE | re.DOTALL)
482 # 1. find the nearest identifier that comes before an unclosed
503 # 1. find the nearest identifier that comes before an unclosed
483 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
504 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
484 tokens = regexp.findall(self.get_line_buffer())
505 tokens = regexp.findall(self.get_line_buffer())
485 tokens.reverse()
506 tokens.reverse()
486 iterTokens = iter(tokens); openPar = 0
507 iterTokens = iter(tokens); openPar = 0
487 for token in iterTokens:
508 for token in iterTokens:
488 if token == ')':
509 if token == ')':
489 openPar -= 1
510 openPar -= 1
490 elif token == '(':
511 elif token == '(':
491 openPar += 1
512 openPar += 1
492 if openPar > 0:
513 if openPar > 0:
493 # found the last unclosed parenthesis
514 # found the last unclosed parenthesis
494 break
515 break
495 else:
516 else:
496 return []
517 return []
497 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
518 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
498 ids = []
519 ids = []
499 isId = re.compile(r'\w+$').match
520 isId = re.compile(r'\w+$').match
500 while True:
521 while True:
501 try:
522 try:
502 ids.append(iterTokens.next())
523 ids.append(iterTokens.next())
503 if not isId(ids[-1]):
524 if not isId(ids[-1]):
504 ids.pop(); break
525 ids.pop(); break
505 if not iterTokens.next() == '.':
526 if not iterTokens.next() == '.':
506 break
527 break
507 except StopIteration:
528 except StopIteration:
508 break
529 break
509 # lookup the candidate callable matches either using global_matches
530 # lookup the candidate callable matches either using global_matches
510 # or attr_matches for dotted names
531 # or attr_matches for dotted names
511 if len(ids) == 1:
532 if len(ids) == 1:
512 callableMatches = self.global_matches(ids[0])
533 callableMatches = self.global_matches(ids[0])
513 else:
534 else:
514 callableMatches = self.attr_matches('.'.join(ids[::-1]))
535 callableMatches = self.attr_matches('.'.join(ids[::-1]))
515 argMatches = []
536 argMatches = []
516 for callableMatch in callableMatches:
537 for callableMatch in callableMatches:
517 try: namedArgs = self._default_arguments(eval(callableMatch,
538 try:
539 namedArgs = self._default_arguments(eval(callableMatch,
518 self.namespace))
540 self.namespace))
519 except: continue
541 except:
542 continue
520 for namedArg in namedArgs:
543 for namedArg in namedArgs:
521 if namedArg.startswith(text):
544 if namedArg.startswith(text):
522 argMatches.append("%s=" %namedArg)
545 argMatches.append("%s=" %namedArg)
523 return argMatches
546 return argMatches
524
547
525 def dispatch_custom_completer(self,text):
548 def dispatch_custom_completer(self,text):
526 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
549 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
527 line = self.full_lbuf
550 line = self.full_lbuf
528 if not line.strip():
551 if not line.strip():
529 return None
552 return None
530
553
531 event = Struct()
554 event = Bunch()
532 event.line = line
555 event.line = line
533 event.symbol = text
556 event.symbol = text
534 cmd = line.split(None,1)[0]
557 cmd = line.split(None,1)[0]
535 event.command = cmd
558 event.command = cmd
536 #print "\ncustom:{%s]\n" % event # dbg
559 #print "\ncustom:{%s]\n" % event # dbg
537
560
538 # for foo etc, try also to find completer for %foo
561 # for foo etc, try also to find completer for %foo
539 if not cmd.startswith(self.magic_escape):
562 if not cmd.startswith(self.magic_escape):
540 try_magic = self.custom_completers.s_matches(
563 try_magic = self.custom_completers.s_matches(
541 self.magic_escape + cmd)
564 self.magic_escape + cmd)
542 else:
565 else:
543 try_magic = []
566 try_magic = []
544
545
567
546 for c in itertools.chain(
568 for c in itertools.chain(self.custom_completers.s_matches(cmd),
547 self.custom_completers.s_matches(cmd),
548 try_magic,
569 try_magic,
549 self.custom_completers.flat_matches(self.lbuf)):
570 self.custom_completers.flat_matches(self.lbuf)):
550 #print "try",c # dbg
571 #print "try",c # dbg
551 try:
572 try:
552 res = c(event)
573 res = c(event)
553 # first, try case sensitive match
574 # first, try case sensitive match
554 withcase = [r for r in res if r.startswith(text)]
575 withcase = [r for r in res if r.startswith(text)]
555 if withcase:
576 if withcase:
556 return withcase
577 return withcase
557 # if none, then case insensitive ones are ok too
578 # if none, then case insensitive ones are ok too
558 return [r for r in res if r.lower().startswith(text.lower())]
579 text_low = text.lower()
580 return [r for r in res if r.lower().startswith(text_low)]
559 except TryNext:
581 except TryNext:
560 pass
582 pass
561
583
562 return None
584 return None
563
585
564 def complete(self, text, state,line_buffer=None):
586 def complete(self, text, state,line_buffer=None):
565 """Return the next possible completion for 'text'.
587 """Return the next possible completion for 'text'.
566
588
567 This is called successively with state == 0, 1, 2, ... until it
589 This is called successively with state == 0, 1, 2, ... until it
568 returns None. The completion should begin with 'text'.
590 returns None. The completion should begin with 'text'.
569
591
570 :Keywords:
592 :Keywords:
571 - line_buffer: string
593 - line_buffer: string
572 If not given, the completer attempts to obtain the current line buffer
594 If not given, the completer attempts to obtain the current line buffer
573 via readline. This keyword allows clients which are requesting for
595 via readline. This keyword allows clients which are requesting for
574 text completions in non-readline contexts to inform the completer of
596 text completions in non-readline contexts to inform the completer of
575 the entire text.
597 the entire text.
576 """
598 """
577
599
578 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
600 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
579
601
580 # if there is only a tab on a line with only whitespace, instead
602 # if there is only a tab on a line with only whitespace, instead
581 # of the mostly useless 'do you want to see all million
603 # of the mostly useless 'do you want to see all million
582 # completions' message, just do the right thing and give the user
604 # completions' message, just do the right thing and give the user
583 # his tab! Incidentally, this enables pasting of tabbed text from
605 # his tab! Incidentally, this enables pasting of tabbed text from
584 # an editor (as long as autoindent is off).
606 # an editor (as long as autoindent is off).
585
607
586 # It should be noted that at least pyreadline still shows
608 # It should be noted that at least pyreadline still shows
587 # file completions - is there a way around it?
609 # file completions - is there a way around it?
588
610
589 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
611 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
590 # don't interfere with their own tab-completion mechanism.
612 # don't interfere with their own tab-completion mechanism.
591 if line_buffer is None:
613 if line_buffer is None:
592 self.full_lbuf = self.get_line_buffer()
614 self.full_lbuf = self.get_line_buffer()
593 else:
615 else:
594 self.full_lbuf = line_buffer
616 self.full_lbuf = line_buffer
595
617
596 if not (self.dumb_terminal or self.full_lbuf.strip()):
618 if not (self.dumb_terminal or self.full_lbuf.strip()):
597 self.readline.insert_text('\t')
619 self.readline.insert_text('\t')
598 return None
620 return None
599
621
600 magic_escape = self.magic_escape
622 magic_escape = self.magic_escape
601 magic_prefix = self.magic_prefix
602
623
603 self.lbuf = self.full_lbuf[:self.get_endidx()]
624 self.lbuf = self.full_lbuf[:self.get_endidx()]
604
625
605 try:
626 try:
606 if text.startswith(magic_escape):
627 if text.startswith('~'):
607 text = text.replace(magic_escape,magic_prefix)
608 elif text.startswith('~'):
609 text = os.path.expanduser(text)
628 text = os.path.expanduser(text)
610 if state == 0:
629 if state == 0:
611 custom_res = self.dispatch_custom_completer(text)
630 custom_res = self.dispatch_custom_completer(text)
612 if custom_res is not None:
631 if custom_res is not None:
613 # did custom completers produce something?
632 # did custom completers produce something?
614 self.matches = custom_res
633 self.matches = custom_res
615 else:
634 else:
616 # Extend the list of completions with the results of each
635 # Extend the list of completions with the results of each
617 # matcher, so we return results to the user from all
636 # matcher, so we return results to the user from all
618 # namespaces.
637 # namespaces.
619 if self.merge_completions:
638 if self.merge_completions:
620 self.matches = []
639 self.matches = []
621 for matcher in self.matchers:
640 for matcher in self.matchers:
622 self.matches.extend(matcher(text))
641 self.matches.extend(matcher(text))
623 else:
642 else:
624 for matcher in self.matchers:
643 for matcher in self.matchers:
625 self.matches = matcher(text)
644 self.matches = matcher(text)
626 if self.matches:
645 if self.matches:
627 break
646 break
628 def uniq(alist):
647 self.matches = list(set(self.matches))
629 set = {}
630 return [set.setdefault(e,e) for e in alist if e not in set]
631 self.matches = uniq(self.matches)
632 try:
648 try:
633 ret = self.matches[state].replace(magic_prefix,magic_escape)
649 #print "MATCH: %r" % self.matches[state] # dbg
634 return ret
650 return self.matches[state]
635 except IndexError:
651 except IndexError:
636 return None
652 return None
637 except:
653 except:
638 #from IPython.core.ultratb import AutoFormattedTB; # dbg
654 #from IPython.core.ultratb import AutoFormattedTB; # dbg
639 #tb=AutoFormattedTB('Verbose');tb() #dbg
655 #tb=AutoFormattedTB('Verbose');tb() #dbg
640
656
641 # If completion fails, don't annoy the user.
657 # If completion fails, don't annoy the user.
642 return None
658 return None
@@ -1,346 +1,346 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight component system for IPython.
4 A lightweight component system for IPython.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from copy import deepcopy
23 from copy import deepcopy
24 import datetime
24 import datetime
25 from weakref import WeakValueDictionary
25 from weakref import WeakValueDictionary
26
26
27 from IPython.utils.importstring import import_item
27 from IPython.utils.importstring import import_item
28 from IPython.config.loader import Config
28 from IPython.config.loader import Config
29 from IPython.utils.traitlets import (
29 from IPython.utils.traitlets import (
30 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
30 HasTraitlets, MetaHasTraitlets, Instance, This
31 )
31 )
32
32
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Helper classes for Components
35 # Helper classes for Components
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 class ComponentError(Exception):
39 class ComponentError(Exception):
40 pass
40 pass
41
41
42 class MetaComponentTracker(type):
42 class MetaComponentTracker(type):
43 """A metaclass that tracks instances of Components and its subclasses."""
43 """A metaclass that tracks instances of Components and its subclasses."""
44
44
45 def __init__(cls, name, bases, d):
45 def __init__(cls, name, bases, d):
46 super(MetaComponentTracker, cls).__init__(name, bases, d)
46 super(MetaComponentTracker, cls).__init__(name, bases, d)
47 cls.__instance_refs = WeakValueDictionary()
47 cls.__instance_refs = WeakValueDictionary()
48 cls.__numcreated = 0
48 cls.__numcreated = 0
49
49
50 def __call__(cls, *args, **kw):
50 def __call__(cls, *args, **kw):
51 """Called when a class is called (instantiated)!!!
51 """Called when a class is called (instantiated)!!!
52
52
53 When a Component or subclass is instantiated, this is called and
53 When a Component or subclass is instantiated, this is called and
54 the instance is saved in a WeakValueDictionary for tracking.
54 the instance is saved in a WeakValueDictionary for tracking.
55 """
55 """
56 instance = cls.__new__(cls, *args, **kw)
56 instance = cls.__new__(cls, *args, **kw)
57
57
58 # Register the instance before __init__ is called so get_instances
58 # Register the instance before __init__ is called so get_instances
59 # works inside __init__ methods!
59 # works inside __init__ methods!
60 indices = cls.register_instance(instance)
60 indices = cls.register_instance(instance)
61
61
62 # This is in a try/except because of the __init__ method fails, the
62 # This is in a try/except because of the __init__ method fails, the
63 # instance is discarded and shouldn't be tracked.
63 # instance is discarded and shouldn't be tracked.
64 try:
64 try:
65 if isinstance(instance, cls):
65 if isinstance(instance, cls):
66 cls.__init__(instance, *args, **kw)
66 cls.__init__(instance, *args, **kw)
67 except:
67 except:
68 # Unregister the instance because __init__ failed!
68 # Unregister the instance because __init__ failed!
69 cls.unregister_instances(indices)
69 cls.unregister_instances(indices)
70 raise
70 raise
71 else:
71 else:
72 return instance
72 return instance
73
73
74 def register_instance(cls, instance):
74 def register_instance(cls, instance):
75 """Register instance with cls and its subclasses."""
75 """Register instance with cls and its subclasses."""
76 # indices is a list of the keys used to register the instance
76 # indices is a list of the keys used to register the instance
77 # with. This list is needed if the instance needs to be unregistered.
77 # with. This list is needed if the instance needs to be unregistered.
78 indices = []
78 indices = []
79 for c in cls.__mro__:
79 for c in cls.__mro__:
80 if issubclass(cls, c) and issubclass(c, Component):
80 if issubclass(cls, c) and issubclass(c, Component):
81 c.__numcreated += 1
81 c.__numcreated += 1
82 indices.append(c.__numcreated)
82 indices.append(c.__numcreated)
83 c.__instance_refs[c.__numcreated] = instance
83 c.__instance_refs[c.__numcreated] = instance
84 else:
84 else:
85 break
85 break
86 return indices
86 return indices
87
87
88 def unregister_instances(cls, indices):
88 def unregister_instances(cls, indices):
89 """Unregister instance with cls and its subclasses."""
89 """Unregister instance with cls and its subclasses."""
90 for c, index in zip(cls.__mro__, indices):
90 for c, index in zip(cls.__mro__, indices):
91 try:
91 try:
92 del c.__instance_refs[index]
92 del c.__instance_refs[index]
93 except KeyError:
93 except KeyError:
94 pass
94 pass
95
95
96 def clear_instances(cls):
96 def clear_instances(cls):
97 """Clear all instances tracked by cls."""
97 """Clear all instances tracked by cls."""
98 cls.__instance_refs.clear()
98 cls.__instance_refs.clear()
99 cls.__numcreated = 0
99 cls.__numcreated = 0
100
100
101 def get_instances(cls, name=None, root=None, klass=None):
101 def get_instances(cls, name=None, root=None, klass=None):
102 """Get all instances of cls and its subclasses.
102 """Get all instances of cls and its subclasses.
103
103
104 Parameters
104 Parameters
105 ----------
105 ----------
106 name : str
106 name : str
107 Limit to components with this name.
107 Limit to components with this name.
108 root : Component or subclass
108 root : Component or subclass
109 Limit to components having this root.
109 Limit to components having this root.
110 klass : class or str
110 klass : class or str
111 Limits to instances of the class or its subclasses. If a str
111 Limits to instances of the class or its subclasses. If a str
112 is given ut must be in the form 'foo.bar.MyClass'. The str
112 is given ut must be in the form 'foo.bar.MyClass'. The str
113 form of this argument is useful for forward declarations.
113 form of this argument is useful for forward declarations.
114 """
114 """
115 if klass is not None:
115 if klass is not None:
116 if isinstance(klass, basestring):
116 if isinstance(klass, basestring):
117 klass = import_item(klass)
117 klass = import_item(klass)
118 # Limit search to instances of klass for performance
118 # Limit search to instances of klass for performance
119 if issubclass(klass, Component):
119 if issubclass(klass, Component):
120 return klass.get_instances(name=name, root=root)
120 return klass.get_instances(name=name, root=root)
121 instances = cls.__instance_refs.values()
121 instances = cls.__instance_refs.values()
122 if name is not None:
122 if name is not None:
123 instances = [i for i in instances if i.name == name]
123 instances = [i for i in instances if i.name == name]
124 if klass is not None:
124 if klass is not None:
125 instances = [i for i in instances if isinstance(i, klass)]
125 instances = [i for i in instances if isinstance(i, klass)]
126 if root is not None:
126 if root is not None:
127 instances = [i for i in instances if i.root == root]
127 instances = [i for i in instances if i.root == root]
128 return instances
128 return instances
129
129
130 def get_instances_by_condition(cls, call, name=None, root=None,
130 def get_instances_by_condition(cls, call, name=None, root=None,
131 klass=None):
131 klass=None):
132 """Get all instances of cls, i such that call(i)==True.
132 """Get all instances of cls, i such that call(i)==True.
133
133
134 This also takes the ``name`` and ``root`` and ``classname``
134 This also takes the ``name`` and ``root`` and ``classname``
135 arguments of :meth:`get_instance`
135 arguments of :meth:`get_instance`
136 """
136 """
137 return [i for i in cls.get_instances(name, root, klass) if call(i)]
137 return [i for i in cls.get_instances(name, root, klass) if call(i)]
138
138
139
139
140 def masquerade_as(instance, cls):
140 def masquerade_as(instance, cls):
141 """Let instance masquerade as an instance of cls.
141 """Let instance masquerade as an instance of cls.
142
142
143 Sometimes, such as in testing code, it is useful to let a class
143 Sometimes, such as in testing code, it is useful to let a class
144 masquerade as another. Python, being duck typed, allows this by
144 masquerade as another. Python, being duck typed, allows this by
145 default. But, instances of components are tracked by their class type.
145 default. But, instances of components are tracked by their class type.
146
146
147 After calling this, ``cls.get_instances()`` will return ``instance``. This
147 After calling this, ``cls.get_instances()`` will return ``instance``. This
148 does not, however, cause ``isinstance(instance, cls)`` to return ``True``.
148 does not, however, cause ``isinstance(instance, cls)`` to return ``True``.
149
149
150 Parameters
150 Parameters
151 ----------
151 ----------
152 instance : an instance of a Component or Component subclass
152 instance : an instance of a Component or Component subclass
153 The instance that will pretend to be a cls.
153 The instance that will pretend to be a cls.
154 cls : subclass of Component
154 cls : subclass of Component
155 The Component subclass that instance will pretend to be.
155 The Component subclass that instance will pretend to be.
156 """
156 """
157 cls.register_instance(instance)
157 cls.register_instance(instance)
158
158
159
159
160 class __ComponentNameGenerator(object):
160 class __ComponentNameGenerator(object):
161 """A Singleton to generate unique component names."""
161 """A Singleton to generate unique component names."""
162
162
163 def __init__(self, prefix):
163 def __init__(self, prefix):
164 self.prefix = prefix
164 self.prefix = prefix
165 self.i = 0
165 self.i = 0
166
166
167 def __call__(self):
167 def __call__(self):
168 count = self.i
168 count = self.i
169 self.i += 1
169 self.i += 1
170 return "%s%s" % (self.prefix, count)
170 return "%s%s" % (self.prefix, count)
171
171
172
172
173 ComponentNameGenerator = __ComponentNameGenerator('ipython.component')
173 ComponentNameGenerator = __ComponentNameGenerator('ipython.component')
174
174
175
175
176 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
176 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
177 pass
177 pass
178
178
179
179
180 #-----------------------------------------------------------------------------
180 #-----------------------------------------------------------------------------
181 # Component implementation
181 # Component implementation
182 #-----------------------------------------------------------------------------
182 #-----------------------------------------------------------------------------
183
183
184
184
185 class Component(HasTraitlets):
185 class Component(HasTraitlets):
186
186
187 __metaclass__ = MetaComponent
187 __metaclass__ = MetaComponent
188
188
189 # Traitlets are fun!
189 # Traitlets are fun!
190 config = Instance(Config,(),{})
190 config = Instance(Config,(),{})
191 parent = This()
191 parent = This()
192 root = This()
192 root = This()
193 created = None
193 created = None
194
194
195 def __init__(self, parent, name=None, config=None):
195 def __init__(self, parent, name=None, config=None):
196 """Create a component given a parent and possibly and name and config.
196 """Create a component given a parent and possibly and name and config.
197
197
198 Parameters
198 Parameters
199 ----------
199 ----------
200 parent : Component subclass
200 parent : Component subclass
201 The parent in the component graph. The parent is used
201 The parent in the component graph. The parent is used
202 to get the root of the component graph.
202 to get the root of the component graph.
203 name : str
203 name : str
204 The unique name of the component. If empty, then a unique
204 The unique name of the component. If empty, then a unique
205 one will be autogenerated.
205 one will be autogenerated.
206 config : Config
206 config : Config
207 If this is empty, self.config = parent.config, otherwise
207 If this is empty, self.config = parent.config, otherwise
208 self.config = config and root.config is ignored. This argument
208 self.config = config and root.config is ignored. This argument
209 should only be used to *override* the automatic inheritance of
209 should only be used to *override* the automatic inheritance of
210 parent.config. If a caller wants to modify parent.config
210 parent.config. If a caller wants to modify parent.config
211 (not override), the caller should make a copy and change
211 (not override), the caller should make a copy and change
212 attributes and then pass the copy to this argument.
212 attributes and then pass the copy to this argument.
213
213
214 Notes
214 Notes
215 -----
215 -----
216 Subclasses of Component must call the :meth:`__init__` method of
216 Subclasses of Component must call the :meth:`__init__` method of
217 :class:`Component` *before* doing anything else and using
217 :class:`Component` *before* doing anything else and using
218 :func:`super`::
218 :func:`super`::
219
219
220 class MyComponent(Component):
220 class MyComponent(Component):
221 def __init__(self, parent, name=None, config=None):
221 def __init__(self, parent, name=None, config=None):
222 super(MyComponent, self).__init__(parent, name, config)
222 super(MyComponent, self).__init__(parent, name, config)
223 # Then any other code you need to finish initialization.
223 # Then any other code you need to finish initialization.
224
224
225 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
225 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
226 attributes are handled properly.
226 attributes are handled properly.
227 """
227 """
228 super(Component, self).__init__()
228 super(Component, self).__init__()
229 self._children = []
229 self._children = []
230 if name is None:
230 if name is None:
231 self.name = ComponentNameGenerator()
231 self.name = ComponentNameGenerator()
232 else:
232 else:
233 self.name = name
233 self.name = name
234 self.root = self # This is the default, it is set when parent is set
234 self.root = self # This is the default, it is set when parent is set
235 self.parent = parent
235 self.parent = parent
236 if config is not None:
236 if config is not None:
237 self.config = config
237 self.config = config
238 # We used to deepcopy, but for now we are trying to just save
238 # We used to deepcopy, but for now we are trying to just save
239 # by reference. This *could* have side effects as all components
239 # by reference. This *could* have side effects as all components
240 # will share config. In fact, I did find such a side effect in
240 # will share config. In fact, I did find such a side effect in
241 # _config_changed below. If a config attribute value was a mutable type
241 # _config_changed below. If a config attribute value was a mutable type
242 # all instances of a component were getting the same copy, effectively
242 # all instances of a component were getting the same copy, effectively
243 # making that a class attribute.
243 # making that a class attribute.
244 # self.config = deepcopy(config)
244 # self.config = deepcopy(config)
245 else:
245 else:
246 if self.parent is not None:
246 if self.parent is not None:
247 self.config = self.parent.config
247 self.config = self.parent.config
248 # We used to deepcopy, but for now we are trying to just save
248 # We used to deepcopy, but for now we are trying to just save
249 # by reference. This *could* have side effects as all components
249 # by reference. This *could* have side effects as all components
250 # will share config. In fact, I did find such a side effect in
250 # will share config. In fact, I did find such a side effect in
251 # _config_changed below. If a config attribute value was a mutable type
251 # _config_changed below. If a config attribute value was a mutable type
252 # all instances of a component were getting the same copy, effectively
252 # all instances of a component were getting the same copy, effectively
253 # making that a class attribute.
253 # making that a class attribute.
254 # self.config = deepcopy(self.parent.config)
254 # self.config = deepcopy(self.parent.config)
255
255
256 self.created = datetime.datetime.now()
256 self.created = datetime.datetime.now()
257
257
258 #-------------------------------------------------------------------------
258 #-------------------------------------------------------------------------
259 # Static traitlet notifiations
259 # Static traitlet notifiations
260 #-------------------------------------------------------------------------
260 #-------------------------------------------------------------------------
261
261
262 def _parent_changed(self, name, old, new):
262 def _parent_changed(self, name, old, new):
263 if old is not None:
263 if old is not None:
264 old._remove_child(self)
264 old._remove_child(self)
265 if new is not None:
265 if new is not None:
266 new._add_child(self)
266 new._add_child(self)
267
267
268 if new is None:
268 if new is None:
269 self.root = self
269 self.root = self
270 else:
270 else:
271 self.root = new.root
271 self.root = new.root
272
272
273 def _root_changed(self, name, old, new):
273 def _root_changed(self, name, old, new):
274 if self.parent is None:
274 if self.parent is None:
275 if not (new is self):
275 if not (new is self):
276 raise ComponentError("Root not self, but parent is None.")
276 raise ComponentError("Root not self, but parent is None.")
277 else:
277 else:
278 if not self.parent.root is new:
278 if not self.parent.root is new:
279 raise ComponentError("Error in setting the root attribute: "
279 raise ComponentError("Error in setting the root attribute: "
280 "root != parent.root")
280 "root != parent.root")
281
281
282 def _config_changed(self, name, old, new):
282 def _config_changed(self, name, old, new):
283 """Update all the class traits having ``config=True`` as metadata.
283 """Update all the class traits having ``config=True`` as metadata.
284
284
285 For any class traitlet with a ``config`` metadata attribute that is
285 For any class traitlet with a ``config`` metadata attribute that is
286 ``True``, we update the traitlet with the value of the corresponding
286 ``True``, we update the traitlet with the value of the corresponding
287 config entry.
287 config entry.
288 """
288 """
289 # Get all traitlets with a config metadata entry that is True
289 # Get all traitlets with a config metadata entry that is True
290 traitlets = self.traitlets(config=True)
290 traitlets = self.traitlets(config=True)
291
291
292 # We auto-load config section for this class as well as any parent
292 # We auto-load config section for this class as well as any parent
293 # classes that are Component subclasses. This starts with Component
293 # classes that are Component subclasses. This starts with Component
294 # and works down the mro loading the config for each section.
294 # and works down the mro loading the config for each section.
295 section_names = [cls.__name__ for cls in \
295 section_names = [cls.__name__ for cls in \
296 reversed(self.__class__.__mro__) if
296 reversed(self.__class__.__mro__) if
297 issubclass(cls, Component) and issubclass(self.__class__, cls)]
297 issubclass(cls, Component) and issubclass(self.__class__, cls)]
298
298
299 for sname in section_names:
299 for sname in section_names:
300 # Don't do a blind getattr as that would cause the config to
300 # Don't do a blind getattr as that would cause the config to
301 # dynamically create the section with name self.__class__.__name__.
301 # dynamically create the section with name self.__class__.__name__.
302 if new._has_section(sname):
302 if new._has_section(sname):
303 my_config = new[sname]
303 my_config = new[sname]
304 for k, v in traitlets.items():
304 for k, v in traitlets.items():
305 # Don't allow traitlets with config=True to start with
305 # Don't allow traitlets with config=True to start with
306 # uppercase. Otherwise, they are confused with Config
306 # uppercase. Otherwise, they are confused with Config
307 # subsections. But, developers shouldn't have uppercase
307 # subsections. But, developers shouldn't have uppercase
308 # attributes anyways! (PEP 6)
308 # attributes anyways! (PEP 6)
309 if k[0].upper()==k[0] and not k.startswith('_'):
309 if k[0].upper()==k[0] and not k.startswith('_'):
310 raise ComponentError('Component traitlets with '
310 raise ComponentError('Component traitlets with '
311 'config=True must start with a lowercase so they are '
311 'config=True must start with a lowercase so they are '
312 'not confused with Config subsections: %s.%s' % \
312 'not confused with Config subsections: %s.%s' % \
313 (self.__class__.__name__, k))
313 (self.__class__.__name__, k))
314 try:
314 try:
315 # Here we grab the value from the config
315 # Here we grab the value from the config
316 # If k has the naming convention of a config
316 # If k has the naming convention of a config
317 # section, it will be auto created.
317 # section, it will be auto created.
318 config_value = my_config[k]
318 config_value = my_config[k]
319 except KeyError:
319 except KeyError:
320 pass
320 pass
321 else:
321 else:
322 # print "Setting %s.%s from %s.%s=%r" % \
322 # print "Setting %s.%s from %s.%s=%r" % \
323 # (self.__class__.__name__,k,sname,k,config_value)
323 # (self.__class__.__name__,k,sname,k,config_value)
324 # We have to do a deepcopy here if we don't deepcopy the entire
324 # We have to do a deepcopy here if we don't deepcopy the entire
325 # config object. If we don't, a mutable config_value will be
325 # config object. If we don't, a mutable config_value will be
326 # shared by all instances, effectively making it a class attribute.
326 # shared by all instances, effectively making it a class attribute.
327 setattr(self, k, deepcopy(config_value))
327 setattr(self, k, deepcopy(config_value))
328
328
329 @property
329 @property
330 def children(self):
330 def children(self):
331 """A list of all my child components."""
331 """A list of all my child components."""
332 return self._children
332 return self._children
333
333
334 def _remove_child(self, child):
334 def _remove_child(self, child):
335 """A private method for removing children components."""
335 """A private method for removing children components."""
336 if child in self._children:
336 if child in self._children:
337 index = self._children.index(child)
337 index = self._children.index(child)
338 del self._children[index]
338 del self._children[index]
339
339
340 def _add_child(self, child):
340 def _add_child(self, child):
341 """A private method for adding children components."""
341 """A private method for adding children components."""
342 if child not in self._children:
342 if child not in self._children:
343 self._children.append(child)
343 self._children.append(child)
344
344
345 def __repr__(self):
345 def __repr__(self):
346 return "<%s('%s')>" % (self.__class__.__name__, self.name)
346 return "<%s('%s')>" % (self.__class__.__name__, self.name)
@@ -1,229 +1,180 b''
1 # -*- coding: utf-8 -*-
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 Authors:
4
5
5 Authors
6 * Fernando Perez
6 -------
7 * Brian E. Granger
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
8 """
8 """
9
9
10 #*****************************************************************************
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2008-2010 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #-----------------------------------------------------------------------------
17
17
18 #****************************************************************************
18 #-----------------------------------------------------------------------------
19 # Required modules
19 # Imports
20 #-----------------------------------------------------------------------------
20
21
21 # From the standard library
22 import os
22 import os
23 import sys
23 import sys
24 from pprint import pformat
24 from pprint import pformat
25
25
26 # Our own
27 from IPython.core import release
28 from IPython.core import ultratb
26 from IPython.core import ultratb
29 from IPython.external.Itpl import itpl
27 from IPython.external.Itpl import itpl
28 from IPython.utils.sysinfo import sys_info
30
29
31 from IPython.utils.genutils import *
30 #-----------------------------------------------------------------------------
31 # Code
32 #-----------------------------------------------------------------------------
32
33
33 #****************************************************************************
34 # Template for the user message.
34 class CrashHandler:
35 _default_message_template = """\
35 """Customizable crash handlers for IPython-based systems.
36 Oops, $self.app_name crashed. We do our best to make it stable, but...
36
37
37 Instances of this class provide a __call__ method which can be used as a
38 A crash report was automatically generated with the following information:
38 sys.excepthook, i.e., the __call__ signature is:
39 - A verbatim copy of the crash traceback.
40 - A copy of your input history during this session.
41 - Data on your current $self.app_name configuration.
39
42
40 def __call__(self,etype, evalue, etb)
43 It was left in the file named:
44 \t'$self.crash_report_fname'
45 If you can email this file to the developers, the information in it will help
46 them in understanding and correcting the problem.
41
47
42 """
48 You can mail it to: $self.contact_name at $self.contact_email
49 with the subject '$self.app_name Crash Report'.
43
50
44 def __init__(self,IP,app_name,contact_name,contact_email,
51 If you want to do it now, the following command will work (under Unix):
45 bug_tracker,crash_report_fname,
52 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
46 show_crash_traceback=True):
47 """New crash handler.
48
53
49 Inputs:
54 To ensure accurate tracking of this issue, please file a report about it at:
55 $self.bug_tracker
56 """
50
57
51 - IP: a running IPython instance, which will be queried at crash time
52 for internal information.
53
58
54 - app_name: a string containing the name of your application.
59 class CrashHandler(object):
60 """Customizable crash handlers for IPython applications.
55
61
56 - contact_name: a string with the name of the person to contact.
62 Instances of this class provide a :meth:`__call__` method which can be
63 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
57
64
58 - contact_email: a string with the email address of the contact.
65 def __call__(self, etype, evalue, etb)
66 """
59
67
60 - bug_tracker: a string with the URL for your project's bug tracker.
68 message_template = _default_message_template
61
69
62 - crash_report_fname: a string with the filename for the crash report
70 def __init__(self, app, contact_name=None, contact_email=None,
63 to be saved in. These reports are left in the ipython user directory
71 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
64 as determined by the running IPython instance.
72 """Create a new crash handler
65
73
66 Optional inputs:
74 Parameters
67
75 ----------
68 - show_crash_traceback(True): if false, don't print the crash
76 app : Application
69 traceback on stderr, only generate the on-disk report
77 A running :class:`Application` instance, which will be queried at
78 crash time for internal information.
79
80 contact_name : str
81 A string with the name of the person to contact.
82
83 contact_email : str
84 A string with the email address of the contact.
70
85
86 bug_tracker : str
87 A string with the URL for your project's bug tracker.
88
89 show_crash_traceback : bool
90 If false, don't print the crash traceback on stderr, only generate
91 the on-disk report
71
92
72 Non-argument instance attributes:
93 Non-argument instance attributes:
73
94
74 These instances contain some non-argument attributes which allow for
95 These instances contain some non-argument attributes which allow for
75 further customization of the crash handler's behavior. Please see the
96 further customization of the crash handler's behavior. Please see the
76 source for further details.
97 source for further details.
77 """
98 """
78
99 self.app = app
79 # apply args into instance
100 self.app_name = self.app.name
80 self.IP = IP # IPython instance
81 self.app_name = app_name
82 self.contact_name = contact_name
101 self.contact_name = contact_name
83 self.contact_email = contact_email
102 self.contact_email = contact_email
84 self.bug_tracker = bug_tracker
103 self.bug_tracker = bug_tracker
85 self.crash_report_fname = crash_report_fname
104 self.crash_report_fname = "Crash_report_%s.txt" % self.app_name
86 self.show_crash_traceback = show_crash_traceback
105 self.show_crash_traceback = show_crash_traceback
87
106 self.section_sep = '\n\n'+'*'*75+'\n\n'
88 # Hardcoded defaults, which can be overridden either by subclasses or
107 self.call_pdb = call_pdb
89 # at runtime for the instance.
108 #self.call_pdb = True # dbg
90
91 # Template for the user message. Subclasses which completely override
92 # this, or user apps, can modify it to suit their tastes. It gets
93 # expanded using itpl, so calls of the kind $self.foo are valid.
94 self.user_message_template = """
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
96
97 A crash report was automatically generated with the following information:
98 - A verbatim copy of the crash traceback.
99 - A copy of your input history during this session.
100 - Data on your current $self.app_name configuration.
101
102 It was left in the file named:
103 \t'$self.crash_report_fname'
104 If you can email this file to the developers, the information in it will help
105 them in understanding and correcting the problem.
106
107 You can mail it to: $self.contact_name at $self.contact_email
108 with the subject '$self.app_name Crash Report'.
109
110 If you want to do it now, the following command will work (under Unix):
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
112
109
113 To ensure accurate tracking of this issue, please file a report about it at:
110 def __call__(self, etype, evalue, etb):
114 $self.bug_tracker
115 """
116
117 def __call__(self,etype, evalue, etb):
118 """Handle an exception, call for compatible with sys.excepthook"""
111 """Handle an exception, call for compatible with sys.excepthook"""
119
112
120 # Report tracebacks shouldn't use color in general (safer for users)
113 # Report tracebacks shouldn't use color in general (safer for users)
121 color_scheme = 'NoColor'
114 color_scheme = 'NoColor'
122
115
123 # Use this ONLY for developer debugging (keep commented out for release)
116 # Use this ONLY for developer debugging (keep commented out for release)
124 #color_scheme = 'Linux' # dbg
117 #color_scheme = 'Linux' # dbg
125
118
126 try:
119 try:
127 rptdir = self.IP.ipython_dir
120 rptdir = self.app.ipython_dir
128 except:
121 except:
129 rptdir = os.getcwd()
122 rptdir = os.getcwd()
130 if not os.path.isdir(rptdir):
123 if not os.path.isdir(rptdir):
131 rptdir = os.getcwd()
124 rptdir = os.getcwd()
132 report_name = os.path.join(rptdir,self.crash_report_fname)
125 report_name = os.path.join(rptdir,self.crash_report_fname)
133 # write the report filename into the instance dict so it can get
126 # write the report filename into the instance dict so it can get
134 # properly expanded out in the user message template
127 # properly expanded out in the user message template
135 self.crash_report_fname = report_name
128 self.crash_report_fname = report_name
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
129 TBhandler = ultratb.VerboseTB(
137 long_header=1)
130 color_scheme=color_scheme,
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
131 long_header=1,
132 call_pdb=self.call_pdb,
133 )
134 if self.call_pdb:
135 TBhandler(etype,evalue,etb)
136 return
137 else:
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
139
139
140 # print traceback to screen
140 # print traceback to screen
141 if self.show_crash_traceback:
141 if self.show_crash_traceback:
142 print >> sys.stderr, traceback
142 print >> sys.stderr, traceback
143
143
144 # and generate a complete report on disk
144 # and generate a complete report on disk
145 try:
145 try:
146 report = open(report_name,'w')
146 report = open(report_name,'w')
147 except:
147 except:
148 print >> sys.stderr, 'Could not create crash report on disk.'
148 print >> sys.stderr, 'Could not create crash report on disk.'
149 return
149 return
150
150
151 # Inform user on stderr of what happened
151 # Inform user on stderr of what happened
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
152 msg = itpl('\n'+'*'*70+'\n'+self.message_template)
153 print >> sys.stderr, msg
153 print >> sys.stderr, msg
154
154
155 # Construct report on disk
155 # Construct report on disk
156 report.write(self.make_report(traceback))
156 report.write(self.make_report(traceback))
157 report.close()
157 report.close()
158 raw_input("Press enter to exit:")
158 raw_input("Hit <Enter> to quit this message (your terminal may close):")
159
159
160 def make_report(self,traceback):
160 def make_report(self,traceback):
161 """Return a string containing a crash report."""
161 """Return a string containing a crash report."""
162
163 sec_sep = '\n\n'+'*'*75+'\n\n'
164
165 report = []
166 rpt_add = report.append
167
162
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
163 sec_sep = self.section_sep
169 rpt_add('IPython version: %s \n\n' % release.version)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
172 (os.name,sys.platform) )
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
174 rpt_add(pformat(self.IP.dict()))
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 try:
177 rpt_add(sec_sep+"History of session input:")
178 for line in self.IP.user_ns['_ih']:
179 rpt_add(line)
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
181 rpt_add(self.IP._last_input_line+'\n')
182 except:
183 pass
184
185 return ''.join(report)
186
187 class IPythonCrashHandler(CrashHandler):
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
189
190 def __init__(self,IP):
191
192 # Set here which of the IPython authors should be listed as contact
193 AUTHOR_CONTACT = 'Fernando'
194
164
195 # Set argument defaults
165 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
196 app_name = 'IPython'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
199 crash_report_fname = 'IPython_crash_report.txt'
200 # Call parent constructor
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
202 bug_tracker,crash_report_fname)
203
204 def make_report(self,traceback):
205 """Return a string containing a crash report."""
206
207 sec_sep = '\n\n'+'*'*75+'\n\n'
208
209 report = []
210 rpt_add = report.append
166 rpt_add = report.append
167 rpt_add(sys_info())
211
168
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
213 rpt_add('IPython version: %s \n\n' % release.version)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
216 (os.name,sys.platform) )
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
218 # rpt_add(pformat(self.IP.dict()))
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
220 try:
169 try:
221 rpt_add(sec_sep+"History of session input:")
170 config = pformat(self.app.config)
222 for line in self.IP.user_ns['_ih']:
171 rpt_add(sec_sep)
223 rpt_add(line)
172 rpt_add('Application name: %s\n\n' % self.app_name)
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
173 rpt_add('Current user configuration structure:\n\n')
225 rpt_add(self.IP._last_input_line+'\n')
174 rpt_add(config)
226 except:
175 except:
227 pass
176 pass
177 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
228
178
229 return ''.join(report)
179 return ''.join(report)
180
@@ -1,479 +1,510 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 import bdb
28 import bdb
29 import cmd
30 import linecache
29 import linecache
31 import os
32 import sys
30 import sys
33
31
34 from IPython.utils import PyColorize
32 from IPython.utils import PyColorize
35 from IPython.core import ipapi
33 from IPython.core import ipapi
36 from IPython.utils import coloransi
34 from IPython.utils import coloransi
37 from IPython.utils.genutils import Term
35 from IPython.utils.io import Term
38 from IPython.core.excolors import exception_colors
36 from IPython.core.excolors import exception_colors
39
37
40 # See if we can use pydb.
38 # See if we can use pydb.
41 has_pydb = False
39 has_pydb = False
42 prompt = 'ipdb> '
40 prompt = 'ipdb> '
43 #We have to check this directly from sys.argv, config struct not yet available
41 #We have to check this directly from sys.argv, config struct not yet available
44 if '-pydb' in sys.argv:
42 if '-pydb' in sys.argv:
45 try:
43 try:
46 import pydb
44 import pydb
47 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
48 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
49 # better protect against it.
47 # better protect against it.
50 has_pydb = True
48 has_pydb = True
51 except ImportError:
49 except ImportError:
52 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
53
51
54 if has_pydb:
52 if has_pydb:
55 from pydb import Pdb as OldPdb
53 from pydb import Pdb as OldPdb
56 #print "Using pydb for %run -d and post-mortem" #dbg
54 #print "Using pydb for %run -d and post-mortem" #dbg
57 prompt = 'ipydb> '
55 prompt = 'ipydb> '
58 else:
56 else:
59 from pdb import Pdb as OldPdb
57 from pdb import Pdb as OldPdb
60
58
61 # Allow the set_trace code to operate outside of an ipython instance, even if
59 # Allow the set_trace code to operate outside of an ipython instance, even if
62 # it does so with some limitations. The rest of this support is implemented in
60 # it does so with some limitations. The rest of this support is implemented in
63 # the Tracer constructor.
61 # the Tracer constructor.
64 def BdbQuit_excepthook(et,ev,tb):
62 def BdbQuit_excepthook(et,ev,tb):
65 if et==bdb.BdbQuit:
63 if et==bdb.BdbQuit:
66 print 'Exiting Debugger.'
64 print 'Exiting Debugger.'
67 else:
65 else:
68 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
69
67
70 def BdbQuit_IPython_excepthook(self,et,ev,tb):
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
71 print 'Exiting Debugger.'
69 print 'Exiting Debugger.'
72
70
73
71
74 class Tracer(object):
72 class Tracer(object):
75 """Class for local debugging, similar to pdb.set_trace.
73 """Class for local debugging, similar to pdb.set_trace.
76
74
77 Instances of this class, when called, behave like pdb.set_trace, but
75 Instances of this class, when called, behave like pdb.set_trace, but
78 providing IPython's enhanced capabilities.
76 providing IPython's enhanced capabilities.
79
77
80 This is implemented as a class which must be initialized in your own code
78 This is implemented as a class which must be initialized in your own code
81 and not as a standalone function because we need to detect at runtime
79 and not as a standalone function because we need to detect at runtime
82 whether IPython is already active or not. That detection is done in the
80 whether IPython is already active or not. That detection is done in the
83 constructor, ensuring that this code plays nicely with a running IPython,
81 constructor, ensuring that this code plays nicely with a running IPython,
84 while functioning acceptably (though with limitations) if outside of it.
82 while functioning acceptably (though with limitations) if outside of it.
85 """
83 """
86
84
87 def __init__(self,colors=None):
85 def __init__(self,colors=None):
88 """Create a local debugger instance.
86 """Create a local debugger instance.
89
87
90 :Parameters:
88 :Parameters:
91
89
92 - `colors` (None): a string containing the name of the color scheme to
90 - `colors` (None): a string containing the name of the color scheme to
93 use, it must be one of IPython's valid color schemes. If not given, the
91 use, it must be one of IPython's valid color schemes. If not given, the
94 function will default to the current IPython scheme when running inside
92 function will default to the current IPython scheme when running inside
95 IPython, and to 'NoColor' otherwise.
93 IPython, and to 'NoColor' otherwise.
96
94
97 Usage example:
95 Usage example:
98
96
99 from IPython.core.debugger import Tracer; debug_here = Tracer()
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
100
98
101 ... later in your code
99 ... later in your code
102 debug_here() # -> will open up the debugger at that point.
100 debug_here() # -> will open up the debugger at that point.
103
101
104 Once the debugger activates, you can use all of its regular commands to
102 Once the debugger activates, you can use all of its regular commands to
105 step through code, set breakpoints, etc. See the pdb documentation
103 step through code, set breakpoints, etc. See the pdb documentation
106 from the Python standard library for usage details.
104 from the Python standard library for usage details.
107 """
105 """
108
106
109 try:
107 try:
110 ip = ipapi.get()
108 ip = ipapi.get()
111 except:
109 except:
112 # Outside of ipython, we set our own exception hook manually
110 # Outside of ipython, we set our own exception hook manually
113 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
114 sys.excepthook = BdbQuit_excepthook
112 sys.excepthook = BdbQuit_excepthook
115 def_colors = 'NoColor'
113 def_colors = 'NoColor'
116 try:
114 try:
117 # Limited tab completion support
115 # Limited tab completion support
118 import readline
116 import readline
119 readline.parse_and_bind('tab: complete')
117 readline.parse_and_bind('tab: complete')
120 except ImportError:
118 except ImportError:
121 pass
119 pass
122 else:
120 else:
123 # In ipython, we use its custom exception handler mechanism
121 # In ipython, we use its custom exception handler mechanism
124 def_colors = ip.colors
122 def_colors = ip.colors
125 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
126
124
127 if colors is None:
125 if colors is None:
128 colors = def_colors
126 colors = def_colors
129 self.debugger = Pdb(colors)
127 self.debugger = Pdb(colors)
130
128
131 def __call__(self):
129 def __call__(self):
132 """Starts an interactive debugger at the point where called.
130 """Starts an interactive debugger at the point where called.
133
131
134 This is similar to the pdb.set_trace() function from the std lib, but
132 This is similar to the pdb.set_trace() function from the std lib, but
135 using IPython's enhanced debugger."""
133 using IPython's enhanced debugger."""
136
134
137 self.debugger.set_trace(sys._getframe().f_back)
135 self.debugger.set_trace(sys._getframe().f_back)
138
136
139
137
140 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
141 """Make new_fn have old_fn's doc string. This is particularly useful
139 """Make new_fn have old_fn's doc string. This is particularly useful
142 for the do_... commands that hook into the help system.
140 for the do_... commands that hook into the help system.
143 Adapted from from a comp.lang.python posting
141 Adapted from from a comp.lang.python posting
144 by Duncan Booth."""
142 by Duncan Booth."""
145 def wrapper(*args, **kw):
143 def wrapper(*args, **kw):
146 return new_fn(*args, **kw)
144 return new_fn(*args, **kw)
147 if old_fn.__doc__:
145 if old_fn.__doc__:
148 wrapper.__doc__ = old_fn.__doc__ + additional_text
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
149 return wrapper
147 return wrapper
150
148
151
149
152 def _file_lines(fname):
150 def _file_lines(fname):
153 """Return the contents of a named file as a list of lines.
151 """Return the contents of a named file as a list of lines.
154
152
155 This function never raises an IOError exception: if the file can't be
153 This function never raises an IOError exception: if the file can't be
156 read, it simply returns an empty list."""
154 read, it simply returns an empty list."""
157
155
158 try:
156 try:
159 outfile = open(fname)
157 outfile = open(fname)
160 except IOError:
158 except IOError:
161 return []
159 return []
162 else:
160 else:
163 out = outfile.readlines()
161 out = outfile.readlines()
164 outfile.close()
162 outfile.close()
165 return out
163 return out
166
164
167
165
168 class Pdb(OldPdb):
166 class Pdb(OldPdb):
169 """Modified Pdb class, does not load readline."""
167 """Modified Pdb class, does not load readline."""
170
168
171 def __init__(self,color_scheme='NoColor',completekey=None,
169 def __init__(self,color_scheme='NoColor',completekey=None,
172 stdin=None, stdout=None):
170 stdin=None, stdout=None):
173
171
174 # Parent constructor:
172 # Parent constructor:
175 if has_pydb and completekey is None:
173 if has_pydb and completekey is None:
176 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
177 else:
175 else:
178 OldPdb.__init__(self,completekey,stdin,stdout)
176 OldPdb.__init__(self,completekey,stdin,stdout)
179
177
180 self.prompt = prompt # The default prompt is '(Pdb)'
178 self.prompt = prompt # The default prompt is '(Pdb)'
181
179
182 # IPython changes...
180 # IPython changes...
183 self.is_pydb = has_pydb
181 self.is_pydb = has_pydb
184
182
185 self.shell = ipapi.get()
183 self.shell = ipapi.get()
186
184
187 if self.is_pydb:
185 if self.is_pydb:
188
186
189 # iplib.py's ipalias seems to want pdb's checkline
187 # iplib.py's ipalias seems to want pdb's checkline
190 # which located in pydb.fn
188 # which located in pydb.fn
191 import pydb.fns
189 import pydb.fns
192 self.checkline = lambda filename, lineno: \
190 self.checkline = lambda filename, lineno: \
193 pydb.fns.checkline(self, filename, lineno)
191 pydb.fns.checkline(self, filename, lineno)
194
192
195 self.curframe = None
193 self.curframe = None
196 self.do_restart = self.new_do_restart
194 self.do_restart = self.new_do_restart
197
195
198 self.old_all_completions = self.shell.Completer.all_completions
196 self.old_all_completions = self.shell.Completer.all_completions
199 self.shell.Completer.all_completions=self.all_completions
197 self.shell.Completer.all_completions=self.all_completions
200
198
201 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
202 OldPdb.do_list)
200 OldPdb.do_list)
203 self.do_l = self.do_list
201 self.do_l = self.do_list
204 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
205 OldPdb.do_frame)
203 OldPdb.do_frame)
206
204
207 self.aliases = {}
205 self.aliases = {}
208
206
209 # Create color table: we copy the default one from the traceback
207 # Create color table: we copy the default one from the traceback
210 # module and add a few attributes needed for debugging
208 # module and add a few attributes needed for debugging
211 self.color_scheme_table = exception_colors()
209 self.color_scheme_table = exception_colors()
212
210
213 # shorthands
211 # shorthands
214 C = coloransi.TermColors
212 C = coloransi.TermColors
215 cst = self.color_scheme_table
213 cst = self.color_scheme_table
216
214
217 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
218 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
219
217
220 cst['Linux'].colors.breakpoint_enabled = C.LightRed
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
221 cst['Linux'].colors.breakpoint_disabled = C.Red
219 cst['Linux'].colors.breakpoint_disabled = C.Red
222
220
223 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
224 cst['LightBG'].colors.breakpoint_disabled = C.Red
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
225
223
226 self.set_colors(color_scheme)
224 self.set_colors(color_scheme)
227
225
228 # Add a python parser so we can syntax highlight source while
226 # Add a python parser so we can syntax highlight source while
229 # debugging.
227 # debugging.
230 self.parser = PyColorize.Parser()
228 self.parser = PyColorize.Parser()
231
229
232 def set_colors(self, scheme):
230 def set_colors(self, scheme):
233 """Shorthand access to the color table scheme selector method."""
231 """Shorthand access to the color table scheme selector method."""
234 self.color_scheme_table.set_active_scheme(scheme)
232 self.color_scheme_table.set_active_scheme(scheme)
235
233
236 def interaction(self, frame, traceback):
234 def interaction(self, frame, traceback):
237 self.shell.set_completer_frame(frame)
235 self.shell.set_completer_frame(frame)
238 OldPdb.interaction(self, frame, traceback)
236 OldPdb.interaction(self, frame, traceback)
239
237
240 def new_do_up(self, arg):
238 def new_do_up(self, arg):
241 OldPdb.do_up(self, arg)
239 OldPdb.do_up(self, arg)
242 self.shell.set_completer_frame(self.curframe)
240 self.shell.set_completer_frame(self.curframe)
243 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
244
242
245 def new_do_down(self, arg):
243 def new_do_down(self, arg):
246 OldPdb.do_down(self, arg)
244 OldPdb.do_down(self, arg)
247 self.shell.set_completer_frame(self.curframe)
245 self.shell.set_completer_frame(self.curframe)
248
246
249 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
250
248
251 def new_do_frame(self, arg):
249 def new_do_frame(self, arg):
252 OldPdb.do_frame(self, arg)
250 OldPdb.do_frame(self, arg)
253 self.shell.set_completer_frame(self.curframe)
251 self.shell.set_completer_frame(self.curframe)
254
252
255 def new_do_quit(self, arg):
253 def new_do_quit(self, arg):
256
254
257 if hasattr(self, 'old_all_completions'):
255 if hasattr(self, 'old_all_completions'):
258 self.shell.Completer.all_completions=self.old_all_completions
256 self.shell.Completer.all_completions=self.old_all_completions
259
257
260
258
261 return OldPdb.do_quit(self, arg)
259 return OldPdb.do_quit(self, arg)
262
260
263 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
264
262
265 def new_do_restart(self, arg):
263 def new_do_restart(self, arg):
266 """Restart command. In the context of ipython this is exactly the same
264 """Restart command. In the context of ipython this is exactly the same
267 thing as 'quit'."""
265 thing as 'quit'."""
268 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
269 return self.do_quit(arg)
267 return self.do_quit(arg)
270
268
271 def postloop(self):
269 def postloop(self):
272 self.shell.set_completer_frame(None)
270 self.shell.set_completer_frame(None)
273
271
274 def print_stack_trace(self):
272 def print_stack_trace(self):
275 try:
273 try:
276 for frame_lineno in self.stack:
274 for frame_lineno in self.stack:
277 self.print_stack_entry(frame_lineno, context = 5)
275 self.print_stack_entry(frame_lineno, context = 5)
278 except KeyboardInterrupt:
276 except KeyboardInterrupt:
279 pass
277 pass
280
278
281 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
282 context = 3):
280 context = 3):
283 #frame, lineno = frame_lineno
281 #frame, lineno = frame_lineno
284 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
282 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
285
283
286 # vds: >>
284 # vds: >>
287 frame, lineno = frame_lineno
285 frame, lineno = frame_lineno
288 filename = frame.f_code.co_filename
286 filename = frame.f_code.co_filename
289 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
290 # vds: <<
288 # vds: <<
291
289
292 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
293 import linecache, repr
291 import linecache, repr
294
292
295 ret = []
293 ret = []
296
294
297 Colors = self.color_scheme_table.active_colors
295 Colors = self.color_scheme_table.active_colors
298 ColorsNormal = Colors.Normal
296 ColorsNormal = Colors.Normal
299 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
300 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
301 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
302 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
303 ColorsNormal)
301 ColorsNormal)
304
302
305 frame, lineno = frame_lineno
303 frame, lineno = frame_lineno
306
304
307 return_value = ''
305 return_value = ''
308 if '__return__' in frame.f_locals:
306 if '__return__' in frame.f_locals:
309 rv = frame.f_locals['__return__']
307 rv = frame.f_locals['__return__']
310 #return_value += '->'
308 #return_value += '->'
311 return_value += repr.repr(rv) + '\n'
309 return_value += repr.repr(rv) + '\n'
312 ret.append(return_value)
310 ret.append(return_value)
313
311
314 #s = filename + '(' + `lineno` + ')'
312 #s = filename + '(' + `lineno` + ')'
315 filename = self.canonic(frame.f_code.co_filename)
313 filename = self.canonic(frame.f_code.co_filename)
316 link = tpl_link % filename
314 link = tpl_link % filename
317
315
318 if frame.f_code.co_name:
316 if frame.f_code.co_name:
319 func = frame.f_code.co_name
317 func = frame.f_code.co_name
320 else:
318 else:
321 func = "<lambda>"
319 func = "<lambda>"
322
320
323 call = ''
321 call = ''
324 if func != '?':
322 if func != '?':
325 if '__args__' in frame.f_locals:
323 if '__args__' in frame.f_locals:
326 args = repr.repr(frame.f_locals['__args__'])
324 args = repr.repr(frame.f_locals['__args__'])
327 else:
325 else:
328 args = '()'
326 args = '()'
329 call = tpl_call % (func, args)
327 call = tpl_call % (func, args)
330
328
331 # The level info should be generated in the same format pdb uses, to
329 # The level info should be generated in the same format pdb uses, to
332 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
333 if frame is self.curframe:
331 if frame is self.curframe:
334 ret.append('> ')
332 ret.append('> ')
335 else:
333 else:
336 ret.append(' ')
334 ret.append(' ')
337 ret.append('%s(%s)%s\n' % (link,lineno,call))
335 ret.append('%s(%s)%s\n' % (link,lineno,call))
338
336
339 start = lineno - 1 - context//2
337 start = lineno - 1 - context//2
340 lines = linecache.getlines(filename)
338 lines = linecache.getlines(filename)
341 start = max(start, 0)
339 start = max(start, 0)
342 start = min(start, len(lines) - context)
340 start = min(start, len(lines) - context)
343 lines = lines[start : start + context]
341 lines = lines[start : start + context]
344
342
345 for i,line in enumerate(lines):
343 for i,line in enumerate(lines):
346 show_arrow = (start + 1 + i == lineno)
344 show_arrow = (start + 1 + i == lineno)
347 linetpl = (frame is self.curframe or show_arrow) \
345 linetpl = (frame is self.curframe or show_arrow) \
348 and tpl_line_em \
346 and tpl_line_em \
349 or tpl_line
347 or tpl_line
350 ret.append(self.__format_line(linetpl, filename,
348 ret.append(self.__format_line(linetpl, filename,
351 start + 1 + i, line,
349 start + 1 + i, line,
352 arrow = show_arrow) )
350 arrow = show_arrow) )
353
351
354 return ''.join(ret)
352 return ''.join(ret)
355
353
356 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
357 bp_mark = ""
355 bp_mark = ""
358 bp_mark_color = ""
356 bp_mark_color = ""
359
357
360 scheme = self.color_scheme_table.active_scheme_name
358 scheme = self.color_scheme_table.active_scheme_name
361 new_line, err = self.parser.format2(line, 'str', scheme)
359 new_line, err = self.parser.format2(line, 'str', scheme)
362 if not err: line = new_line
360 if not err: line = new_line
363
361
364 bp = None
362 bp = None
365 if lineno in self.get_file_breaks(filename):
363 if lineno in self.get_file_breaks(filename):
366 bps = self.get_breaks(filename, lineno)
364 bps = self.get_breaks(filename, lineno)
367 bp = bps[-1]
365 bp = bps[-1]
368
366
369 if bp:
367 if bp:
370 Colors = self.color_scheme_table.active_colors
368 Colors = self.color_scheme_table.active_colors
371 bp_mark = str(bp.number)
369 bp_mark = str(bp.number)
372 bp_mark_color = Colors.breakpoint_enabled
370 bp_mark_color = Colors.breakpoint_enabled
373 if not bp.enabled:
371 if not bp.enabled:
374 bp_mark_color = Colors.breakpoint_disabled
372 bp_mark_color = Colors.breakpoint_disabled
375
373
376 numbers_width = 7
374 numbers_width = 7
377 if arrow:
375 if arrow:
378 # This is the line with the error
376 # This is the line with the error
379 pad = numbers_width - len(str(lineno)) - len(bp_mark)
377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
380 if pad >= 3:
378 if pad >= 3:
381 marker = '-'*(pad-3) + '-> '
379 marker = '-'*(pad-3) + '-> '
382 elif pad == 2:
380 elif pad == 2:
383 marker = '> '
381 marker = '> '
384 elif pad == 1:
382 elif pad == 1:
385 marker = '>'
383 marker = '>'
386 else:
384 else:
387 marker = ''
385 marker = ''
388 num = '%s%s' % (marker, str(lineno))
386 num = '%s%s' % (marker, str(lineno))
389 line = tpl_line % (bp_mark_color + bp_mark, num, line)
387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
390 else:
388 else:
391 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
392 line = tpl_line % (bp_mark_color + bp_mark, num, line)
390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
393
391
394 return line
392 return line
395
393
396 def list_command_pydb(self, arg):
394 def list_command_pydb(self, arg):
397 """List command to use if we have a newer pydb installed"""
395 """List command to use if we have a newer pydb installed"""
398 filename, first, last = OldPdb.parse_list_cmd(self, arg)
396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
399 if filename is not None:
397 if filename is not None:
400 self.print_list_lines(filename, first, last)
398 self.print_list_lines(filename, first, last)
401
399
402 def print_list_lines(self, filename, first, last):
400 def print_list_lines(self, filename, first, last):
403 """The printing (as opposed to the parsing part of a 'list'
401 """The printing (as opposed to the parsing part of a 'list'
404 command."""
402 command."""
405 try:
403 try:
406 Colors = self.color_scheme_table.active_colors
404 Colors = self.color_scheme_table.active_colors
407 ColorsNormal = Colors.Normal
405 ColorsNormal = Colors.Normal
408 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
409 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
407 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
410 src = []
408 src = []
411 for lineno in range(first, last+1):
409 for lineno in range(first, last+1):
412 line = linecache.getline(filename, lineno)
410 line = linecache.getline(filename, lineno)
413 if not line:
411 if not line:
414 break
412 break
415
413
416 if lineno == self.curframe.f_lineno:
414 if lineno == self.curframe.f_lineno:
417 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
418 else:
416 else:
419 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
420
418
421 src.append(line)
419 src.append(line)
422 self.lineno = lineno
420 self.lineno = lineno
423
421
424 print >>Term.cout, ''.join(src)
422 print >>Term.cout, ''.join(src)
425
423
426 except KeyboardInterrupt:
424 except KeyboardInterrupt:
427 pass
425 pass
428
426
429 def do_list(self, arg):
427 def do_list(self, arg):
430 self.lastcmd = 'list'
428 self.lastcmd = 'list'
431 last = None
429 last = None
432 if arg:
430 if arg:
433 try:
431 try:
434 x = eval(arg, {}, {})
432 x = eval(arg, {}, {})
435 if type(x) == type(()):
433 if type(x) == type(()):
436 first, last = x
434 first, last = x
437 first = int(first)
435 first = int(first)
438 last = int(last)
436 last = int(last)
439 if last < first:
437 if last < first:
440 # Assume it's a count
438 # Assume it's a count
441 last = first + last
439 last = first + last
442 else:
440 else:
443 first = max(1, int(x) - 5)
441 first = max(1, int(x) - 5)
444 except:
442 except:
445 print '*** Error in argument:', `arg`
443 print '*** Error in argument:', `arg`
446 return
444 return
447 elif self.lineno is None:
445 elif self.lineno is None:
448 first = max(1, self.curframe.f_lineno - 5)
446 first = max(1, self.curframe.f_lineno - 5)
449 else:
447 else:
450 first = self.lineno + 1
448 first = self.lineno + 1
451 if last is None:
449 if last is None:
452 last = first + 10
450 last = first + 10
453 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
454
452
455 # vds: >>
453 # vds: >>
456 lineno = first
454 lineno = first
457 filename = self.curframe.f_code.co_filename
455 filename = self.curframe.f_code.co_filename
458 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
459 # vds: <<
457 # vds: <<
460
458
461 do_l = do_list
459 do_l = do_list
462
460
463 def do_pdef(self, arg):
461 def do_pdef(self, arg):
464 """The debugger interface to magic_pdef"""
462 """The debugger interface to magic_pdef"""
465 namespaces = [('Locals', self.curframe.f_locals),
463 namespaces = [('Locals', self.curframe.f_locals),
466 ('Globals', self.curframe.f_globals)]
464 ('Globals', self.curframe.f_globals)]
467 self.shell.magic_pdef(arg, namespaces=namespaces)
465 self.shell.magic_pdef(arg, namespaces=namespaces)
468
466
469 def do_pdoc(self, arg):
467 def do_pdoc(self, arg):
470 """The debugger interface to magic_pdoc"""
468 """The debugger interface to magic_pdoc"""
471 namespaces = [('Locals', self.curframe.f_locals),
469 namespaces = [('Locals', self.curframe.f_locals),
472 ('Globals', self.curframe.f_globals)]
470 ('Globals', self.curframe.f_globals)]
473 self.shell.magic_pdoc(arg, namespaces=namespaces)
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
474
472
475 def do_pinfo(self, arg):
473 def do_pinfo(self, arg):
476 """The debugger equivalant of ?obj"""
474 """The debugger equivalant of ?obj"""
477 namespaces = [('Locals', self.curframe.f_locals),
475 namespaces = [('Locals', self.curframe.f_locals),
478 ('Globals', self.curframe.f_globals)]
476 ('Globals', self.curframe.f_globals)]
479 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
478
479 def checkline(self, filename, lineno):
480 """Check whether specified line seems to be executable.
481
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
483 line or EOF). Warning: testing is not comprehensive.
484 """
485 #######################################################################
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
488 # changing:
489 #
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
491 # to:
492 #
493 line = linecache.getline(filename, lineno)
494 #
495 # does the trick. But in reality, we need to fix this by reconciling
496 # our updates with the new Pdb APIs in Python 2.6.
497 #
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
499 #######################################################################
500
501 if not line:
502 print >>self.stdout, 'End of file'
503 return 0
504 line = line.strip()
505 # Don't allow setting breakpoint at a blank line
506 if (not line or (line[0] == '#') or
507 (line[:3] == '"""') or line[:3] == "'''"):
508 print >>self.stdout, '*** Blank or comment'
509 return 0
510 return lineno
@@ -1,77 +1,75 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A context manager for handling sys.displayhook.
4 A context manager for handling sys.displayhook.
5
5
6 Authors:
6 Authors:
7
7
8 * Robert Kern
8 * Robert Kern
9 * Brian Granger
9 * Brian Granger
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import sys
23 import sys
24
24
25 from IPython.core.component import Component
25 from IPython.core.component import Component
26
26
27 from IPython.utils.autoattr import auto_attr
28
29 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
30 # Classes and functions
28 # Classes and functions
31 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
32
30
33
31
34 class DisplayTrap(Component):
32 class DisplayTrap(Component):
35 """Object to manage sys.displayhook.
33 """Object to manage sys.displayhook.
36
34
37 This came from IPython.core.kernel.display_hook, but is simplified
35 This came from IPython.core.kernel.display_hook, but is simplified
38 (no callbacks or formatters) until more of the core is refactored.
36 (no callbacks or formatters) until more of the core is refactored.
39 """
37 """
40
38
41 def __init__(self, parent, hook):
39 def __init__(self, parent, hook):
42 super(DisplayTrap, self).__init__(parent, None, None)
40 super(DisplayTrap, self).__init__(parent, None, None)
43 self.hook = hook
41 self.hook = hook
44 self.old_hook = None
42 self.old_hook = None
45 # We define this to track if a single BuiltinTrap is nested.
43 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
44 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
45 self._nested_level = 0
48
46
49 # @auto_attr
47 # @auto_attr
50 # def shell(self):
48 # def shell(self):
51 # return Component.get_instances(
49 # return Component.get_instances(
52 # root=self.root,
50 # root=self.root,
53 # klass='IPython.core.iplib.InteractiveShell')[0]
51 # klass='IPython.core.iplib.InteractiveShell')[0]
54
52
55 def __enter__(self):
53 def __enter__(self):
56 if self._nested_level == 0:
54 if self._nested_level == 0:
57 self.set()
55 self.set()
58 self._nested_level += 1
56 self._nested_level += 1
59 return self
57 return self
60
58
61 def __exit__(self, type, value, traceback):
59 def __exit__(self, type, value, traceback):
62 if self._nested_level == 1:
60 if self._nested_level == 1:
63 self.unset()
61 self.unset()
64 self._nested_level -= 1
62 self._nested_level -= 1
65 # Returning False will cause exceptions to propagate
63 # Returning False will cause exceptions to propagate
66 return False
64 return False
67
65
68 def set(self):
66 def set(self):
69 """Set the hook."""
67 """Set the hook."""
70 if sys.displayhook is not self.hook:
68 if sys.displayhook is not self.hook:
71 self.old_hook = sys.displayhook
69 self.old_hook = sys.displayhook
72 sys.displayhook = self.hook
70 sys.displayhook = self.hook
73
71
74 def unset(self):
72 def unset(self):
75 """Unset the hook."""
73 """Unset the hook."""
76 sys.displayhook = self.old_hook
74 sys.displayhook = self.old_hook
77
75
@@ -1,272 +1,273 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An embedded IPython shell.
4 An embedded IPython shell.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import with_statement
26 from __future__ import with_statement
27 import __main__
27
28
28 import sys
29 import sys
29 from contextlib import nested
30 from contextlib import nested
30
31
31 from IPython.core import ultratb
32 from IPython.core import ultratb
32 from IPython.core.iplib import InteractiveShell
33 from IPython.core.iplib import InteractiveShell
33 from IPython.core.ipapp import load_default_config
34 from IPython.core.ipapp import load_default_config
34
35
35 from IPython.utils.traitlets import Bool, Str, CBool
36 from IPython.utils.traitlets import Bool, Str, CBool
36 from IPython.utils.genutils import ask_yes_no
37 from IPython.utils.io import ask_yes_no
37
38
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Classes and functions
41 # Classes and functions
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42
43
43 # This is an additional magic that is exposed in embedded shells.
44 # This is an additional magic that is exposed in embedded shells.
44 def kill_embedded(self,parameter_s=''):
45 def kill_embedded(self,parameter_s=''):
45 """%kill_embedded : deactivate for good the current embedded IPython.
46 """%kill_embedded : deactivate for good the current embedded IPython.
46
47
47 This function (after asking for confirmation) sets an internal flag so that
48 This function (after asking for confirmation) sets an internal flag so that
48 an embedded IPython will never activate again. This is useful to
49 an embedded IPython will never activate again. This is useful to
49 permanently disable a shell that is being called inside a loop: once you've
50 permanently disable a shell that is being called inside a loop: once you've
50 figured out what you needed from it, you may then kill it and the program
51 figured out what you needed from it, you may then kill it and the program
51 will then continue to run without the interactive shell interfering again.
52 will then continue to run without the interactive shell interfering again.
52 """
53 """
53
54
54 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
55 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
55 "(y/n)? [y/N] ",'n')
56 "(y/n)? [y/N] ",'n')
56 if kill:
57 if kill:
57 self.embedded_active = False
58 self.embedded_active = False
58 print "This embedded IPython will not reactivate anymore once you exit."
59 print "This embedded IPython will not reactivate anymore once you exit."
59
60
60
61
61 class InteractiveShellEmbed(InteractiveShell):
62 class InteractiveShellEmbed(InteractiveShell):
62
63
63 dummy_mode = Bool(False)
64 dummy_mode = Bool(False)
64 exit_msg = Str('')
65 exit_msg = Str('')
65 embedded = CBool(True)
66 embedded = CBool(True)
66 embedded_active = CBool(True)
67 embedded_active = CBool(True)
67 # Like the base class display_banner is not configurable, but here it
68 # Like the base class display_banner is not configurable, but here it
68 # is True by default.
69 # is True by default.
69 display_banner = CBool(True)
70 display_banner = CBool(True)
70
71
71 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
72 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
72 user_ns=None, user_global_ns=None,
73 user_ns=None, user_global_ns=None,
73 banner1=None, banner2=None, display_banner=None,
74 banner1=None, banner2=None, display_banner=None,
74 custom_exceptions=((),None), exit_msg=''):
75 custom_exceptions=((),None), exit_msg=''):
75
76
76 self.save_sys_ipcompleter()
77 self.save_sys_ipcompleter()
77
78
78 super(InteractiveShellEmbed,self).__init__(
79 super(InteractiveShellEmbed,self).__init__(
79 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
80 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
80 user_ns=user_ns, user_global_ns=user_global_ns,
81 user_ns=user_ns, user_global_ns=user_global_ns,
81 banner1=banner1, banner2=banner2, display_banner=display_banner,
82 banner1=banner1, banner2=banner2, display_banner=display_banner,
82 custom_exceptions=custom_exceptions)
83 custom_exceptions=custom_exceptions)
83
84
84 self.exit_msg = exit_msg
85 self.exit_msg = exit_msg
85 self.define_magic("kill_embedded", kill_embedded)
86 self.define_magic("kill_embedded", kill_embedded)
86
87
87 # don't use the ipython crash handler so that user exceptions aren't
88 # don't use the ipython crash handler so that user exceptions aren't
88 # trapped
89 # trapped
89 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
90 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
90 mode=self.xmode,
91 mode=self.xmode,
91 call_pdb=self.pdb)
92 call_pdb=self.pdb)
92
93
93 self.restore_sys_ipcompleter()
94 self.restore_sys_ipcompleter()
94
95
95 def init_sys_modules(self):
96 def init_sys_modules(self):
96 pass
97 pass
97
98
98 def save_sys_ipcompleter(self):
99 def save_sys_ipcompleter(self):
99 """Save readline completer status."""
100 """Save readline completer status."""
100 try:
101 try:
101 #print 'Save completer',sys.ipcompleter # dbg
102 #print 'Save completer',sys.ipcompleter # dbg
102 self.sys_ipcompleter_orig = sys.ipcompleter
103 self.sys_ipcompleter_orig = sys.ipcompleter
103 except:
104 except:
104 pass # not nested with IPython
105 pass # not nested with IPython
105
106
106 def restore_sys_ipcompleter(self):
107 def restore_sys_ipcompleter(self):
107 """Restores the readline completer which was in place.
108 """Restores the readline completer which was in place.
108
109
109 This allows embedded IPython within IPython not to disrupt the
110 This allows embedded IPython within IPython not to disrupt the
110 parent's completion.
111 parent's completion.
111 """
112 """
112 try:
113 try:
113 self.readline.set_completer(self.sys_ipcompleter_orig)
114 self.readline.set_completer(self.sys_ipcompleter_orig)
114 sys.ipcompleter = self.sys_ipcompleter_orig
115 sys.ipcompleter = self.sys_ipcompleter_orig
115 except:
116 except:
116 pass
117 pass
117
118
118 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
119 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
119 stack_depth=1):
120 stack_depth=1):
120 """Activate the interactive interpreter.
121 """Activate the interactive interpreter.
121
122
122 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
123 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
123 the interpreter shell with the given local and global namespaces, and
124 the interpreter shell with the given local and global namespaces, and
124 optionally print a header string at startup.
125 optionally print a header string at startup.
125
126
126 The shell can be globally activated/deactivated using the
127 The shell can be globally activated/deactivated using the
127 set/get_dummy_mode methods. This allows you to turn off a shell used
128 set/get_dummy_mode methods. This allows you to turn off a shell used
128 for debugging globally.
129 for debugging globally.
129
130
130 However, *each* time you call the shell you can override the current
131 However, *each* time you call the shell you can override the current
131 state of dummy_mode with the optional keyword parameter 'dummy'. For
132 state of dummy_mode with the optional keyword parameter 'dummy'. For
132 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
133 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
133 can still have a specific call work by making it as IPShell(dummy=0).
134 can still have a specific call work by making it as IPShell(dummy=0).
134
135
135 The optional keyword parameter dummy controls whether the call
136 The optional keyword parameter dummy controls whether the call
136 actually does anything.
137 actually does anything.
137 """
138 """
138
139
139 # If the user has turned it off, go away
140 # If the user has turned it off, go away
140 if not self.embedded_active:
141 if not self.embedded_active:
141 return
142 return
142
143
143 # Normal exits from interactive mode set this flag, so the shell can't
144 # Normal exits from interactive mode set this flag, so the shell can't
144 # re-enter (it checks this variable at the start of interactive mode).
145 # re-enter (it checks this variable at the start of interactive mode).
145 self.exit_now = False
146 self.exit_now = False
146
147
147 # Allow the dummy parameter to override the global __dummy_mode
148 # Allow the dummy parameter to override the global __dummy_mode
148 if dummy or (dummy != 0 and self.dummy_mode):
149 if dummy or (dummy != 0 and self.dummy_mode):
149 return
150 return
150
151
151 if self.has_readline:
152 if self.has_readline:
152 self.set_completer()
153 self.set_completer()
153
154
154 # self.banner is auto computed
155 # self.banner is auto computed
155 if header:
156 if header:
156 self.old_banner2 = self.banner2
157 self.old_banner2 = self.banner2
157 self.banner2 = self.banner2 + '\n' + header + '\n'
158 self.banner2 = self.banner2 + '\n' + header + '\n'
158
159
159 # Call the embedding code with a stack depth of 1 so it can skip over
160 # Call the embedding code with a stack depth of 1 so it can skip over
160 # our call and get the original caller's namespaces.
161 # our call and get the original caller's namespaces.
161 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
162 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
162
163
163 self.banner2 = self.old_banner2
164 self.banner2 = self.old_banner2
164
165
165 if self.exit_msg is not None:
166 if self.exit_msg is not None:
166 print self.exit_msg
167 print self.exit_msg
167
168
168 self.restore_sys_ipcompleter()
169 self.restore_sys_ipcompleter()
169
170
170 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
171 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
171 display_banner=None):
172 display_banner=None):
172 """Embeds IPython into a running python program.
173 """Embeds IPython into a running python program.
173
174
174 Input:
175 Input:
175
176
176 - header: An optional header message can be specified.
177 - header: An optional header message can be specified.
177
178
178 - local_ns, global_ns: working namespaces. If given as None, the
179 - local_ns, global_ns: working namespaces. If given as None, the
179 IPython-initialized one is updated with __main__.__dict__, so that
180 IPython-initialized one is updated with __main__.__dict__, so that
180 program variables become visible but user-specific configuration
181 program variables become visible but user-specific configuration
181 remains possible.
182 remains possible.
182
183
183 - stack_depth: specifies how many levels in the stack to go to
184 - stack_depth: specifies how many levels in the stack to go to
184 looking for namespaces (when local_ns and global_ns are None). This
185 looking for namespaces (when local_ns and global_ns are None). This
185 allows an intermediate caller to make sure that this function gets
186 allows an intermediate caller to make sure that this function gets
186 the namespace from the intended level in the stack. By default (0)
187 the namespace from the intended level in the stack. By default (0)
187 it will get its locals and globals from the immediate caller.
188 it will get its locals and globals from the immediate caller.
188
189
189 Warning: it's possible to use this in a program which is being run by
190 Warning: it's possible to use this in a program which is being run by
190 IPython itself (via %run), but some funny things will happen (a few
191 IPython itself (via %run), but some funny things will happen (a few
191 globals get overwritten). In the future this will be cleaned up, as
192 globals get overwritten). In the future this will be cleaned up, as
192 there is no fundamental reason why it can't work perfectly."""
193 there is no fundamental reason why it can't work perfectly."""
193
194
194 # Get locals and globals from caller
195 # Get locals and globals from caller
195 if local_ns is None or global_ns is None:
196 if local_ns is None or global_ns is None:
196 call_frame = sys._getframe(stack_depth).f_back
197 call_frame = sys._getframe(stack_depth).f_back
197
198
198 if local_ns is None:
199 if local_ns is None:
199 local_ns = call_frame.f_locals
200 local_ns = call_frame.f_locals
200 if global_ns is None:
201 if global_ns is None:
201 global_ns = call_frame.f_globals
202 global_ns = call_frame.f_globals
202
203
203 # Update namespaces and fire up interpreter
204 # Update namespaces and fire up interpreter
204
205
205 # The global one is easy, we can just throw it in
206 # The global one is easy, we can just throw it in
206 self.user_global_ns = global_ns
207 self.user_global_ns = global_ns
207
208
208 # but the user/local one is tricky: ipython needs it to store internal
209 # but the user/local one is tricky: ipython needs it to store internal
209 # data, but we also need the locals. We'll copy locals in the user
210 # data, but we also need the locals. We'll copy locals in the user
210 # one, but will track what got copied so we can delete them at exit.
211 # one, but will track what got copied so we can delete them at exit.
211 # This is so that a later embedded call doesn't see locals from a
212 # This is so that a later embedded call doesn't see locals from a
212 # previous call (which most likely existed in a separate scope).
213 # previous call (which most likely existed in a separate scope).
213 local_varnames = local_ns.keys()
214 local_varnames = local_ns.keys()
214 self.user_ns.update(local_ns)
215 self.user_ns.update(local_ns)
215 #self.user_ns['local_ns'] = local_ns # dbg
216 #self.user_ns['local_ns'] = local_ns # dbg
216
217
217 # Patch for global embedding to make sure that things don't overwrite
218 # Patch for global embedding to make sure that things don't overwrite
218 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
219 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
219 # FIXME. Test this a bit more carefully (the if.. is new)
220 # FIXME. Test this a bit more carefully (the if.. is new)
220 if local_ns is None and global_ns is None:
221 if local_ns is None and global_ns is None:
221 self.user_global_ns.update(__main__.__dict__)
222 self.user_global_ns.update(__main__.__dict__)
222
223
223 # make sure the tab-completer has the correct frame information, so it
224 # make sure the tab-completer has the correct frame information, so it
224 # actually completes using the frame's locals/globals
225 # actually completes using the frame's locals/globals
225 self.set_completer_frame()
226 self.set_completer_frame()
226
227
227 with nested(self.builtin_trap, self.display_trap):
228 with nested(self.builtin_trap, self.display_trap):
228 self.interact(display_banner=display_banner)
229 self.interact(display_banner=display_banner)
229
230
230 # now, purge out the user namespace from anything we might have added
231 # now, purge out the user namespace from anything we might have added
231 # from the caller's local namespace
232 # from the caller's local namespace
232 delvar = self.user_ns.pop
233 delvar = self.user_ns.pop
233 for var in local_varnames:
234 for var in local_varnames:
234 delvar(var,None)
235 delvar(var,None)
235
236
236
237
237 _embedded_shell = None
238 _embedded_shell = None
238
239
239
240
240 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
241 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
241 display_banner=True, exit_msg=''):
242 display_banner=True, exit_msg=''):
242 """Call this to embed IPython at the current point in your program.
243 """Call this to embed IPython at the current point in your program.
243
244
244 The first invocation of this will create an :class:`InteractiveShellEmbed`
245 The first invocation of this will create an :class:`InteractiveShellEmbed`
245 instance and then call it. Consecutive calls just call the already
246 instance and then call it. Consecutive calls just call the already
246 created instance.
247 created instance.
247
248
248 Here is a simple example::
249 Here is a simple example::
249
250
250 from IPython import embed
251 from IPython import embed
251 a = 10
252 a = 10
252 b = 20
253 b = 20
253 embed('First time')
254 embed('First time')
254 c = 30
255 c = 30
255 d = 40
256 d = 40
256 embed
257 embed
257
258
258 Full customization can be done by passing a :class:`Struct` in as the
259 Full customization can be done by passing a :class:`Struct` in as the
259 config argument.
260 config argument.
260 """
261 """
261 if config is None:
262 if config is None:
262 config = load_default_config()
263 config = load_default_config()
263 config.InteractiveShellEmbed = config.InteractiveShell
264 config.InteractiveShellEmbed = config.InteractiveShell
264 global _embedded_shell
265 global _embedded_shell
265 if _embedded_shell is None:
266 if _embedded_shell is None:
266 _embedded_shell = InteractiveShellEmbed(
267 _embedded_shell = InteractiveShellEmbed(
267 config=config, usage=usage,
268 config=config, usage=usage,
268 banner1=banner1, banner2=banner2,
269 banner1=banner1, banner2=banner2,
269 display_banner=display_banner, exit_msg=exit_msg
270 display_banner=display_banner, exit_msg=exit_msg
270 )
271 )
271 _embedded_shell(header=header, stack_depth=2)
272 _embedded_shell(header=header, stack_depth=2)
272
273
@@ -1,137 +1,135 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Color schemes for exception handling code in IPython.
3 Color schemes for exception handling code in IPython.
4 """
4 """
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
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 #****************************************************************************
14 # Required modules
15 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
13 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
16
14
17 def exception_colors():
15 def exception_colors():
18 """Return a color table with fields for exception reporting.
16 """Return a color table with fields for exception reporting.
19
17
20 The table is an instance of ColorSchemeTable with schemes added for
18 The table is an instance of ColorSchemeTable with schemes added for
21 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
19 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
22 in.
20 in.
23
21
24 Examples:
22 Examples:
25
23
26 >>> ec = exception_colors()
24 >>> ec = exception_colors()
27 >>> ec.active_scheme_name
25 >>> ec.active_scheme_name
28 ''
26 ''
29 >>> print ec.active_colors
27 >>> print ec.active_colors
30 None
28 None
31
29
32 Now we activate a color scheme:
30 Now we activate a color scheme:
33 >>> ec.set_active_scheme('NoColor')
31 >>> ec.set_active_scheme('NoColor')
34 >>> ec.active_scheme_name
32 >>> ec.active_scheme_name
35 'NoColor'
33 'NoColor'
36 >>> ec.active_colors.keys()
34 >>> ec.active_colors.keys()
37 ['em', 'filenameEm', 'excName', 'valEm', 'nameEm', 'line', 'topline',
35 ['em', 'filenameEm', 'excName', 'valEm', 'nameEm', 'line', 'topline',
38 'name', 'caret', 'val', 'vName', 'Normal', 'filename', 'linenoEm',
36 'name', 'caret', 'val', 'vName', 'Normal', 'filename', 'linenoEm',
39 'lineno', 'normalEm']
37 'lineno', 'normalEm']
40 """
38 """
41
39
42 ex_colors = ColorSchemeTable()
40 ex_colors = ColorSchemeTable()
43
41
44 # Populate it with color schemes
42 # Populate it with color schemes
45 C = TermColors # shorthand and local lookup
43 C = TermColors # shorthand and local lookup
46 ex_colors.add_scheme(ColorScheme(
44 ex_colors.add_scheme(ColorScheme(
47 'NoColor',
45 'NoColor',
48 # The color to be used for the top line
46 # The color to be used for the top line
49 topline = C.NoColor,
47 topline = C.NoColor,
50
48
51 # The colors to be used in the traceback
49 # The colors to be used in the traceback
52 filename = C.NoColor,
50 filename = C.NoColor,
53 lineno = C.NoColor,
51 lineno = C.NoColor,
54 name = C.NoColor,
52 name = C.NoColor,
55 vName = C.NoColor,
53 vName = C.NoColor,
56 val = C.NoColor,
54 val = C.NoColor,
57 em = C.NoColor,
55 em = C.NoColor,
58
56
59 # Emphasized colors for the last frame of the traceback
57 # Emphasized colors for the last frame of the traceback
60 normalEm = C.NoColor,
58 normalEm = C.NoColor,
61 filenameEm = C.NoColor,
59 filenameEm = C.NoColor,
62 linenoEm = C.NoColor,
60 linenoEm = C.NoColor,
63 nameEm = C.NoColor,
61 nameEm = C.NoColor,
64 valEm = C.NoColor,
62 valEm = C.NoColor,
65
63
66 # Colors for printing the exception
64 # Colors for printing the exception
67 excName = C.NoColor,
65 excName = C.NoColor,
68 line = C.NoColor,
66 line = C.NoColor,
69 caret = C.NoColor,
67 caret = C.NoColor,
70 Normal = C.NoColor
68 Normal = C.NoColor
71 ))
69 ))
72
70
73 # make some schemes as instances so we can copy them for modification easily
71 # make some schemes as instances so we can copy them for modification easily
74 ex_colors.add_scheme(ColorScheme(
72 ex_colors.add_scheme(ColorScheme(
75 'Linux',
73 'Linux',
76 # The color to be used for the top line
74 # The color to be used for the top line
77 topline = C.LightRed,
75 topline = C.LightRed,
78
76
79 # The colors to be used in the traceback
77 # The colors to be used in the traceback
80 filename = C.Green,
78 filename = C.Green,
81 lineno = C.Green,
79 lineno = C.Green,
82 name = C.Purple,
80 name = C.Purple,
83 vName = C.Cyan,
81 vName = C.Cyan,
84 val = C.Green,
82 val = C.Green,
85 em = C.LightCyan,
83 em = C.LightCyan,
86
84
87 # Emphasized colors for the last frame of the traceback
85 # Emphasized colors for the last frame of the traceback
88 normalEm = C.LightCyan,
86 normalEm = C.LightCyan,
89 filenameEm = C.LightGreen,
87 filenameEm = C.LightGreen,
90 linenoEm = C.LightGreen,
88 linenoEm = C.LightGreen,
91 nameEm = C.LightPurple,
89 nameEm = C.LightPurple,
92 valEm = C.LightBlue,
90 valEm = C.LightBlue,
93
91
94 # Colors for printing the exception
92 # Colors for printing the exception
95 excName = C.LightRed,
93 excName = C.LightRed,
96 line = C.Yellow,
94 line = C.Yellow,
97 caret = C.White,
95 caret = C.White,
98 Normal = C.Normal
96 Normal = C.Normal
99 ))
97 ))
100
98
101 # For light backgrounds, swap dark/light colors
99 # For light backgrounds, swap dark/light colors
102 ex_colors.add_scheme(ColorScheme(
100 ex_colors.add_scheme(ColorScheme(
103 'LightBG',
101 'LightBG',
104 # The color to be used for the top line
102 # The color to be used for the top line
105 topline = C.Red,
103 topline = C.Red,
106
104
107 # The colors to be used in the traceback
105 # The colors to be used in the traceback
108 filename = C.LightGreen,
106 filename = C.LightGreen,
109 lineno = C.LightGreen,
107 lineno = C.LightGreen,
110 name = C.LightPurple,
108 name = C.LightPurple,
111 vName = C.Cyan,
109 vName = C.Cyan,
112 val = C.LightGreen,
110 val = C.LightGreen,
113 em = C.Cyan,
111 em = C.Cyan,
114
112
115 # Emphasized colors for the last frame of the traceback
113 # Emphasized colors for the last frame of the traceback
116 normalEm = C.Cyan,
114 normalEm = C.Cyan,
117 filenameEm = C.Green,
115 filenameEm = C.Green,
118 linenoEm = C.Green,
116 linenoEm = C.Green,
119 nameEm = C.Purple,
117 nameEm = C.Purple,
120 valEm = C.Blue,
118 valEm = C.Blue,
121
119
122 # Colors for printing the exception
120 # Colors for printing the exception
123 excName = C.Red,
121 excName = C.Red,
124 #line = C.Brown, # brown often is displayed as yellow
122 #line = C.Brown, # brown often is displayed as yellow
125 line = C.Red,
123 line = C.Red,
126 caret = C.Normal,
124 caret = C.Normal,
127 Normal = C.Normal,
125 Normal = C.Normal,
128 ))
126 ))
129
127
130 return ex_colors
128 return ex_colors
131
129
132
130
133 # For backwards compatibility, keep around a single global object. Note that
131 # For backwards compatibility, keep around a single global object. Note that
134 # this should NOT be used, the factory function should be used instead, since
132 # this should NOT be used, the factory function should be used instead, since
135 # these objects are stateful and it's very easy to get strange bugs if any code
133 # these objects are stateful and it's very easy to get strange bugs if any code
136 # modifies the module-level object's state.
134 # modifies the module-level object's state.
137 ExceptionColors = exception_colors()
135 ExceptionColors = exception_colors()
@@ -1,254 +1,277 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ History related magics and functionality """
2 """ History related magics and functionality """
3
3
4 # Stdlib imports
4 # Stdlib imports
5 import fnmatch
5 import fnmatch
6 import os
6 import os
7
7
8 from IPython.utils.genutils import Term, ask_yes_no, warn
8 from IPython.utils.io import Term, ask_yes_no
9 from IPython.utils.warn import warn
9 from IPython.core import ipapi
10 from IPython.core import ipapi
10
11
11 def magic_history(self, parameter_s = ''):
12 def magic_history(self, parameter_s = ''):
12 """Print input history (_i<n> variables), with most recent last.
13 """Print input history (_i<n> variables), with most recent last.
13
14
14 %history -> print at most 40 inputs (some may be multi-line)\\
15 %history -> print at most 40 inputs (some may be multi-line)\\
15 %history n -> print at most n inputs\\
16 %history n -> print at most n inputs\\
16 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
17 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
17
18 Each input's number <n> is shown, and is accessible as the
19 automatically generated variable _i<n>. Multi-line statements are
20 printed starting at a new line for easy copy/paste.
21
22
18
23 Options:
19 By default, input history is printed without line numbers so it can be
20 directly pasted into an editor.
24
21
25 -n: do NOT print line numbers. This is useful if you want to get a
22 With -n, each input's number <n> is shown, and is accessible as the
26 printout of many lines which can be directly pasted into a text
23 automatically generated variable _i<n> as well as In[<n>]. Multi-line
27 editor.
24 statements are printed starting at a new line for easy copy/paste.
25
26 Options:
28
27
28 -n: print line numbers for each input.
29 This feature is only available if numbered prompts are in use.
29 This feature is only available if numbered prompts are in use.
30
30
31 -o: also print outputs for each input.
32
33 -p: print classic '>>>' python prompts before each input. This is useful
34 for making documentation, and in conjunction with -o, for producing
35 doctest-ready output.
36
31 -t: (default) print the 'translated' history, as IPython understands it.
37 -t: (default) print the 'translated' history, as IPython understands it.
32 IPython filters your input and converts it all into valid Python source
38 IPython filters your input and converts it all into valid Python source
33 before executing it (things like magics or aliases are turned into
39 before executing it (things like magics or aliases are turned into
34 function calls, for example). With this option, you'll see the native
40 function calls, for example). With this option, you'll see the native
35 history instead of the user-entered version: '%cd /' will be seen as
41 history instead of the user-entered version: '%cd /' will be seen as
36 '_ip.magic("%cd /")' instead of '%cd /'.
42 '_ip.magic("%cd /")' instead of '%cd /'.
37
43
38 -r: print the 'raw' history, i.e. the actual commands you typed.
44 -r: print the 'raw' history, i.e. the actual commands you typed.
39
45
40 -g: treat the arg as a pattern to grep for in (full) history.
46 -g: treat the arg as a pattern to grep for in (full) history.
41 This includes the "shadow history" (almost all commands ever written).
47 This includes the "shadow history" (almost all commands ever written).
42 Use '%hist -g' to show full shadow history (may be very long).
48 Use '%hist -g' to show full shadow history (may be very long).
43 In shadow history, every index nuwber starts with 0.
49 In shadow history, every index nuwber starts with 0.
44
50
45 -f FILENAME: instead of printing the output to the screen, redirect it to
51 -f FILENAME: instead of printing the output to the screen, redirect it to
46 the given file. The file is always overwritten, though IPython asks for
52 the given file. The file is always overwritten, though IPython asks for
47 confirmation first if it already exists.
53 confirmation first if it already exists.
48 """
54 """
49
55
50 if not self.outputcache.do_full_cache:
56 if not self.outputcache.do_full_cache:
51 print 'This feature is only available if numbered prompts are in use.'
57 print 'This feature is only available if numbered prompts are in use.'
52 return
58 return
53 opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
59 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
54
60
55 # Check if output to specific file was requested.
61 # Check if output to specific file was requested.
56 try:
62 try:
57 outfname = opts['f']
63 outfname = opts['f']
58 except KeyError:
64 except KeyError:
59 outfile = Term.cout # default
65 outfile = Term.cout # default
60 # We don't want to close stdout at the end!
66 # We don't want to close stdout at the end!
61 close_at_end = False
67 close_at_end = False
62 else:
68 else:
63 if os.path.exists(outfname):
69 if os.path.exists(outfname):
64 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
70 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
65 print 'Aborting.'
71 print 'Aborting.'
66 return
72 return
67
73
68 outfile = open(outfname,'w')
74 outfile = open(outfname,'w')
69 close_at_end = True
75 close_at_end = True
70
76
71 if 't' in opts:
77 if 't' in opts:
72 input_hist = self.input_hist
78 input_hist = self.input_hist
73 elif 'r' in opts:
79 elif 'r' in opts:
74 input_hist = self.input_hist_raw
80 input_hist = self.input_hist_raw
75 else:
81 else:
76 input_hist = self.input_hist
82 input_hist = self.input_hist
77
83
78 default_length = 40
84 default_length = 40
79 pattern = None
85 pattern = None
80 if 'g' in opts:
86 if 'g' in opts:
81 init = 1
87 init = 1
82 final = len(input_hist)
88 final = len(input_hist)
83 parts = parameter_s.split(None,1)
89 parts = parameter_s.split(None, 1)
84 if len(parts) == 1:
90 if len(parts) == 1:
85 parts += '*'
91 parts += '*'
86 head, pattern = parts
92 head, pattern = parts
87 pattern = "*" + pattern + "*"
93 pattern = "*" + pattern + "*"
88 elif len(args) == 0:
94 elif len(args) == 0:
89 final = len(input_hist)
95 final = len(input_hist)-1
90 init = max(1,final-default_length)
96 init = max(1,final-default_length)
91 elif len(args) == 1:
97 elif len(args) == 1:
92 final = len(input_hist)
98 final = len(input_hist)
93 init = max(1,final-int(args[0]))
99 init = max(1, final-int(args[0]))
94 elif len(args) == 2:
100 elif len(args) == 2:
95 init,final = map(int,args)
101 init, final = map(int, args)
96 else:
102 else:
97 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
103 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
98 print self.magic_hist.__doc__
104 print >> Term.cout, self.magic_hist.__doc__
99 return
105 return
106
100 width = len(str(final))
107 width = len(str(final))
101 line_sep = ['','\n']
108 line_sep = ['','\n']
102 print_nums = not opts.has_key('n')
109 print_nums = 'n' in opts
110 print_outputs = 'o' in opts
111 pyprompts = 'p' in opts
103
112
104 found = False
113 found = False
105 if pattern is not None:
114 if pattern is not None:
106 sh = self.shadowhist.all()
115 sh = self.shadowhist.all()
107 for idx, s in sh:
116 for idx, s in sh:
108 if fnmatch.fnmatch(s, pattern):
117 if fnmatch.fnmatch(s, pattern):
109 print "0%d: %s" %(idx, s)
118 print >> outfile, "0%d: %s" %(idx, s)
110 found = True
119 found = True
111
120
112 if found:
121 if found:
113 print "==="
122 print >> outfile, "==="
114 print "shadow history ends, fetch by %rep <number> (must start with 0)"
123 print >> outfile, \
115 print "=== start of normal history ==="
124 "shadow history ends, fetch by %rep <number> (must start with 0)"
125 print >> outfile, "=== start of normal history ==="
116
126
117 for in_num in range(init,final):
127 for in_num in range(init,final):
118 inline = input_hist[in_num]
128 inline = input_hist[in_num]
119 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
129 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
120 continue
130 continue
121
131
122 multiline = int(inline.count('\n') > 1)
132 multiline = int(inline.count('\n') > 1)
123 if print_nums:
133 if print_nums:
124 print >> outfile, \
134 print >> outfile, \
125 '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
135 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
126 print >> outfile, inline,
136 if pyprompts:
137 print >> outfile, '>>>',
138 if multiline:
139 lines = inline.splitlines()
140 print >> outfile, '\n... '.join(lines)
141 print >> outfile, '... '
142 else:
143 print >> outfile, inline,
144 else:
145 print >> outfile, inline,
146 if print_outputs:
147 output = self.shell.user_ns['Out'].get(in_num)
148 if output is not None:
149 print >> outfile, repr(output)
127
150
128 if close_at_end:
151 if close_at_end:
129 outfile.close()
152 outfile.close()
130
153
131
154
132 def magic_hist(self, parameter_s=''):
155 def magic_hist(self, parameter_s=''):
133 """Alternate name for %history."""
156 """Alternate name for %history."""
134 return self.magic_history(parameter_s)
157 return self.magic_history(parameter_s)
135
158
136
159
137 def rep_f(self, arg):
160 def rep_f(self, arg):
138 r""" Repeat a command, or get command to input line for editing
161 r""" Repeat a command, or get command to input line for editing
139
162
140 - %rep (no arguments):
163 - %rep (no arguments):
141
164
142 Place a string version of last computation result (stored in the special '_'
165 Place a string version of last computation result (stored in the special '_'
143 variable) to the next input prompt. Allows you to create elaborate command
166 variable) to the next input prompt. Allows you to create elaborate command
144 lines without using copy-paste::
167 lines without using copy-paste::
145
168
146 $ l = ["hei", "vaan"]
169 $ l = ["hei", "vaan"]
147 $ "".join(l)
170 $ "".join(l)
148 ==> heivaan
171 ==> heivaan
149 $ %rep
172 $ %rep
150 $ heivaan_ <== cursor blinking
173 $ heivaan_ <== cursor blinking
151
174
152 %rep 45
175 %rep 45
153
176
154 Place history line 45 to next input prompt. Use %hist to find out the
177 Place history line 45 to next input prompt. Use %hist to find out the
155 number.
178 number.
156
179
157 %rep 1-4 6-7 3
180 %rep 1-4 6-7 3
158
181
159 Repeat the specified lines immediately. Input slice syntax is the same as
182 Repeat the specified lines immediately. Input slice syntax is the same as
160 in %macro and %save.
183 in %macro and %save.
161
184
162 %rep foo
185 %rep foo
163
186
164 Place the most recent line that has the substring "foo" to next input.
187 Place the most recent line that has the substring "foo" to next input.
165 (e.g. 'svn ci -m foobar').
188 (e.g. 'svn ci -m foobar').
166 """
189 """
167
190
168 opts,args = self.parse_options(arg,'',mode='list')
191 opts,args = self.parse_options(arg,'',mode='list')
169 if not args:
192 if not args:
170 self.set_next_input(str(self.user_ns["_"]))
193 self.set_next_input(str(self.user_ns["_"]))
171 return
194 return
172
195
173 if len(args) == 1 and not '-' in args[0]:
196 if len(args) == 1 and not '-' in args[0]:
174 arg = args[0]
197 arg = args[0]
175 if len(arg) > 1 and arg.startswith('0'):
198 if len(arg) > 1 and arg.startswith('0'):
176 # get from shadow hist
199 # get from shadow hist
177 num = int(arg[1:])
200 num = int(arg[1:])
178 line = self.shadowhist.get(num)
201 line = self.shadowhist.get(num)
179 self.set_next_input(str(line))
202 self.set_next_input(str(line))
180 return
203 return
181 try:
204 try:
182 num = int(args[0])
205 num = int(args[0])
183 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
206 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
184 return
207 return
185 except ValueError:
208 except ValueError:
186 pass
209 pass
187
210
188 for h in reversed(self.input_hist_raw):
211 for h in reversed(self.input_hist_raw):
189 if 'rep' in h:
212 if 'rep' in h:
190 continue
213 continue
191 if fnmatch.fnmatch(h,'*' + arg + '*'):
214 if fnmatch.fnmatch(h,'*' + arg + '*'):
192 self.set_next_input(str(h).rstrip())
215 self.set_next_input(str(h).rstrip())
193 return
216 return
194
217
195 try:
218 try:
196 lines = self.extract_input_slices(args, True)
219 lines = self.extract_input_slices(args, True)
197 print "lines",lines
220 print "lines",lines
198 self.runlines(lines)
221 self.runlines(lines)
199 except ValueError:
222 except ValueError:
200 print "Not found in recent history:", args
223 print "Not found in recent history:", args
201
224
202
225
203 _sentinel = object()
226 _sentinel = object()
204
227
205 class ShadowHist(object):
228 class ShadowHist(object):
206 def __init__(self,db):
229 def __init__(self,db):
207 # cmd => idx mapping
230 # cmd => idx mapping
208 self.curidx = 0
231 self.curidx = 0
209 self.db = db
232 self.db = db
210 self.disabled = False
233 self.disabled = False
211
234
212 def inc_idx(self):
235 def inc_idx(self):
213 idx = self.db.get('shadowhist_idx', 1)
236 idx = self.db.get('shadowhist_idx', 1)
214 self.db['shadowhist_idx'] = idx + 1
237 self.db['shadowhist_idx'] = idx + 1
215 return idx
238 return idx
216
239
217 def add(self, ent):
240 def add(self, ent):
218 if self.disabled:
241 if self.disabled:
219 return
242 return
220 try:
243 try:
221 old = self.db.hget('shadowhist', ent, _sentinel)
244 old = self.db.hget('shadowhist', ent, _sentinel)
222 if old is not _sentinel:
245 if old is not _sentinel:
223 return
246 return
224 newidx = self.inc_idx()
247 newidx = self.inc_idx()
225 #print "new",newidx # dbg
248 #print "new",newidx # dbg
226 self.db.hset('shadowhist',ent, newidx)
249 self.db.hset('shadowhist',ent, newidx)
227 except:
250 except:
228 ipapi.get().showtraceback()
251 ipapi.get().showtraceback()
229 print "WARNING: disabling shadow history"
252 print "WARNING: disabling shadow history"
230 self.disabled = True
253 self.disabled = True
231
254
232 def all(self):
255 def all(self):
233 d = self.db.hdict('shadowhist')
256 d = self.db.hdict('shadowhist')
234 items = [(i,s) for (s,i) in d.items()]
257 items = [(i,s) for (s,i) in d.items()]
235 items.sort()
258 items.sort()
236 return items
259 return items
237
260
238 def get(self, idx):
261 def get(self, idx):
239 all = self.all()
262 all = self.all()
240
263
241 for k, v in all:
264 for k, v in all:
242 #print k,v
265 #print k,v
243 if k == idx:
266 if k == idx:
244 return v
267 return v
245
268
246
269
247 def init_ipython(ip):
270 def init_ipython(ip):
248 import ipy_completers
249
250 ip.define_magic("rep",rep_f)
271 ip.define_magic("rep",rep_f)
251 ip.define_magic("hist",magic_hist)
272 ip.define_magic("hist",magic_hist)
252 ip.define_magic("history",magic_history)
273 ip.define_magic("history",magic_history)
253
274
254 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
275 # XXX - ipy_completers are in quarantine, need to be updated to new apis
276 #import ipy_completers
277 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,274 +1,276 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 import os, bisect
44 import os, bisect
45 import sys
45 import sys
46 from IPython.utils.genutils import Term, shell
46
47 from pprint import PrettyPrinter
47 from pprint import PrettyPrinter
48
48
49 from IPython.utils.io import Term
50 from IPython.utils.process import shell
51
49 from IPython.core.error import TryNext
52 from IPython.core.error import TryNext
50
53
51 # List here all the default hooks. For now it's just the editor functions
54 # List here all the default hooks. For now it's just the editor functions
52 # but over time we'll move here all the public API for user-accessible things.
55 # but over time we'll move here all the public API for user-accessible things.
53
56
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
56 'generate_prompt', 'generate_output_prompt','shell_hook',
59 'generate_prompt', 'generate_output_prompt','shell_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
58 'clipboard_get']
61 'clipboard_get']
59
62
60 pformat = PrettyPrinter().pformat
63 pformat = PrettyPrinter().pformat
61
64
62 def editor(self,filename, linenum=None):
65 def editor(self,filename, linenum=None):
63 """Open the default editor at the given filename and linenumber.
66 """Open the default editor at the given filename and linenumber.
64
67
65 This is IPython's default editor hook, you can use it as an example to
68 This is IPython's default editor hook, you can use it as an example to
66 write your own modified one. To set your own editor function as the
69 write your own modified one. To set your own editor function as the
67 new editor hook, call ip.set_hook('editor',yourfunc)."""
70 new editor hook, call ip.set_hook('editor',yourfunc)."""
68
71
69 # IPython configures a default editor at startup by reading $EDITOR from
72 # IPython configures a default editor at startup by reading $EDITOR from
70 # the environment, and falling back on vi (unix) or notepad (win32).
73 # the environment, and falling back on vi (unix) or notepad (win32).
71 editor = self.editor
74 editor = self.editor
72
75
73 # marker for at which line to open the file (for existing objects)
76 # marker for at which line to open the file (for existing objects)
74 if linenum is None or editor=='notepad':
77 if linenum is None or editor=='notepad':
75 linemark = ''
78 linemark = ''
76 else:
79 else:
77 linemark = '+%d' % int(linenum)
80 linemark = '+%d' % int(linenum)
78
81
79 # Enclose in quotes if necessary and legal
82 # Enclose in quotes if necessary and legal
80 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
83 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
81 editor = '"%s"' % editor
84 editor = '"%s"' % editor
82
85
83 # Call the actual editor
86 # Call the actual editor
84 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
87 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
85 raise TryNext()
88 raise TryNext()
86
89
87 import tempfile
90 import tempfile
88 def fix_error_editor(self,filename,linenum,column,msg):
91 def fix_error_editor(self,filename,linenum,column,msg):
89 """Open the editor at the given filename, linenumber, column and
92 """Open the editor at the given filename, linenumber, column and
90 show an error message. This is used for correcting syntax errors.
93 show an error message. This is used for correcting syntax errors.
91 The current implementation only has special support for the VIM editor,
94 The current implementation only has special support for the VIM editor,
92 and falls back on the 'editor' hook if VIM is not used.
95 and falls back on the 'editor' hook if VIM is not used.
93
96
94 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
97 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
95 """
98 """
96 def vim_quickfix_file():
99 def vim_quickfix_file():
97 t = tempfile.NamedTemporaryFile()
100 t = tempfile.NamedTemporaryFile()
98 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
101 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
99 t.flush()
102 t.flush()
100 return t
103 return t
101 if os.path.basename(self.editor) != 'vim':
104 if os.path.basename(self.editor) != 'vim':
102 self.hooks.editor(filename,linenum)
105 self.hooks.editor(filename,linenum)
103 return
106 return
104 t = vim_quickfix_file()
107 t = vim_quickfix_file()
105 try:
108 try:
106 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
109 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
107 raise TryNext()
110 raise TryNext()
108 finally:
111 finally:
109 t.close()
112 t.close()
110
113
111
114
112 def synchronize_with_editor(self, filename, linenum, column):
115 def synchronize_with_editor(self, filename, linenum, column):
113 pass
116 pass
114
117
115
118
116 class CommandChainDispatcher:
119 class CommandChainDispatcher:
117 """ Dispatch calls to a chain of commands until some func can handle it
120 """ Dispatch calls to a chain of commands until some func can handle it
118
121
119 Usage: instantiate, execute "add" to add commands (with optional
122 Usage: instantiate, execute "add" to add commands (with optional
120 priority), execute normally via f() calling mechanism.
123 priority), execute normally via f() calling mechanism.
121
124
122 """
125 """
123 def __init__(self,commands=None):
126 def __init__(self,commands=None):
124 if commands is None:
127 if commands is None:
125 self.chain = []
128 self.chain = []
126 else:
129 else:
127 self.chain = commands
130 self.chain = commands
128
131
129
132
130 def __call__(self,*args, **kw):
133 def __call__(self,*args, **kw):
131 """ Command chain is called just like normal func.
134 """ Command chain is called just like normal func.
132
135
133 This will call all funcs in chain with the same args as were given to this
136 This will call all funcs in chain with the same args as were given to this
134 function, and return the result of first func that didn't raise
137 function, and return the result of first func that didn't raise
135 TryNext """
138 TryNext """
136
139
137 for prio,cmd in self.chain:
140 for prio,cmd in self.chain:
138 #print "prio",prio,"cmd",cmd #dbg
141 #print "prio",prio,"cmd",cmd #dbg
139 try:
142 try:
140 ret = cmd(*args, **kw)
143 return cmd(*args, **kw)
141 return ret
142 except TryNext, exc:
144 except TryNext, exc:
143 if exc.args or exc.kwargs:
145 if exc.args or exc.kwargs:
144 args = exc.args
146 args = exc.args
145 kw = exc.kwargs
147 kw = exc.kwargs
146 # if no function will accept it, raise TryNext up to the caller
148 # if no function will accept it, raise TryNext up to the caller
147 raise TryNext
149 raise TryNext
148
150
149 def __str__(self):
151 def __str__(self):
150 return str(self.chain)
152 return str(self.chain)
151
153
152 def add(self, func, priority=0):
154 def add(self, func, priority=0):
153 """ Add a func to the cmd chain with given priority """
155 """ Add a func to the cmd chain with given priority """
154 bisect.insort(self.chain,(priority,func))
156 bisect.insort(self.chain,(priority,func))
155
157
156 def __iter__(self):
158 def __iter__(self):
157 """ Return all objects in chain.
159 """ Return all objects in chain.
158
160
159 Handy if the objects are not callable.
161 Handy if the objects are not callable.
160 """
162 """
161 return iter(self.chain)
163 return iter(self.chain)
162
164
163
165
164 def result_display(self,arg):
166 def result_display(self,arg):
165 """ Default display hook.
167 """ Default display hook.
166
168
167 Called for displaying the result to the user.
169 Called for displaying the result to the user.
168 """
170 """
169
171
170 if self.pprint:
172 if self.pprint:
171 out = pformat(arg)
173 out = pformat(arg)
172 if '\n' in out:
174 if '\n' in out:
173 # So that multi-line strings line up with the left column of
175 # So that multi-line strings line up with the left column of
174 # the screen, instead of having the output prompt mess up
176 # the screen, instead of having the output prompt mess up
175 # their first line.
177 # their first line.
176 Term.cout.write('\n')
178 Term.cout.write('\n')
177 print >>Term.cout, out
179 print >>Term.cout, out
178 else:
180 else:
179 # By default, the interactive prompt uses repr() to display results,
181 # By default, the interactive prompt uses repr() to display results,
180 # so we should honor this. Users who'd rather use a different
182 # so we should honor this. Users who'd rather use a different
181 # mechanism can easily override this hook.
183 # mechanism can easily override this hook.
182 print >>Term.cout, repr(arg)
184 print >>Term.cout, repr(arg)
183 # the default display hook doesn't manipulate the value to put in history
185 # the default display hook doesn't manipulate the value to put in history
184 return None
186 return None
185
187
186
188
187 def input_prefilter(self,line):
189 def input_prefilter(self,line):
188 """ Default input prefilter
190 """ Default input prefilter
189
191
190 This returns the line as unchanged, so that the interpreter
192 This returns the line as unchanged, so that the interpreter
191 knows that nothing was done and proceeds with "classic" prefiltering
193 knows that nothing was done and proceeds with "classic" prefiltering
192 (%magics, !shell commands etc.).
194 (%magics, !shell commands etc.).
193
195
194 Note that leading whitespace is not passed to this hook. Prefilter
196 Note that leading whitespace is not passed to this hook. Prefilter
195 can't alter indentation.
197 can't alter indentation.
196
198
197 """
199 """
198 #print "attempt to rewrite",line #dbg
200 #print "attempt to rewrite",line #dbg
199 return line
201 return line
200
202
201
203
202 def shutdown_hook(self):
204 def shutdown_hook(self):
203 """ default shutdown hook
205 """ default shutdown hook
204
206
205 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
207 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
206 """
208 """
207
209
208 #print "default shutdown hook ok" # dbg
210 #print "default shutdown hook ok" # dbg
209 return
211 return
210
212
211
213
212 def late_startup_hook(self):
214 def late_startup_hook(self):
213 """ Executed after ipython has been constructed and configured
215 """ Executed after ipython has been constructed and configured
214
216
215 """
217 """
216 #print "default startup hook ok" # dbg
218 #print "default startup hook ok" # dbg
217
219
218
220
219 def generate_prompt(self, is_continuation):
221 def generate_prompt(self, is_continuation):
220 """ calculate and return a string with the prompt to display """
222 """ calculate and return a string with the prompt to display """
221 if is_continuation:
223 if is_continuation:
222 return str(self.outputcache.prompt2)
224 return str(self.outputcache.prompt2)
223 return str(self.outputcache.prompt1)
225 return str(self.outputcache.prompt1)
224
226
225
227
226 def generate_output_prompt(self):
228 def generate_output_prompt(self):
227 return str(self.outputcache.prompt_out)
229 return str(self.outputcache.prompt_out)
228
230
229
231
230 def shell_hook(self,cmd):
232 def shell_hook(self,cmd):
231 """ Run system/shell command a'la os.system() """
233 """ Run system/shell command a'la os.system() """
232
234
233 shell(cmd, header=self.system_header, verbose=self.system_verbose)
235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
234
236
235
237
236 def show_in_pager(self,s):
238 def show_in_pager(self,s):
237 """ Run a string through pager """
239 """ Run a string through pager """
238 # raising TryNext here will use the default paging functionality
240 # raising TryNext here will use the default paging functionality
239 raise TryNext
241 raise TryNext
240
242
241
243
242 def pre_prompt_hook(self):
244 def pre_prompt_hook(self):
243 """ Run before displaying the next prompt
245 """ Run before displaying the next prompt
244
246
245 Use this e.g. to display output from asynchronous operations (in order
247 Use this e.g. to display output from asynchronous operations (in order
246 to not mess up text entry)
248 to not mess up text entry)
247 """
249 """
248
250
249 return None
251 return None
250
252
251
253
252 def pre_runcode_hook(self):
254 def pre_runcode_hook(self):
253 """ Executed before running the (prefiltered) code in IPython """
255 """ Executed before running the (prefiltered) code in IPython """
254 return None
256 return None
255
257
256
258
257 def clipboard_get(self):
259 def clipboard_get(self):
258 """ Get text from the clipboard.
260 """ Get text from the clipboard.
259 """
261 """
260 from IPython.lib.clipboard import (
262 from IPython.lib.clipboard import (
261 osx_clipboard_get, tkinter_clipboard_get,
263 osx_clipboard_get, tkinter_clipboard_get,
262 win32_clipboard_get
264 win32_clipboard_get
263 )
265 )
264 if sys.platform == 'win32':
266 if sys.platform == 'win32':
265 chain = [win32_clipboard_get, tkinter_clipboard_get]
267 chain = [win32_clipboard_get, tkinter_clipboard_get]
266 elif sys.platform == 'darwin':
268 elif sys.platform == 'darwin':
267 chain = [osx_clipboard_get, tkinter_clipboard_get]
269 chain = [osx_clipboard_get, tkinter_clipboard_get]
268 else:
270 else:
269 chain = [tkinter_clipboard_get]
271 chain = [tkinter_clipboard_get]
270 dispatcher = CommandChainDispatcher()
272 dispatcher = CommandChainDispatcher()
271 for func in chain:
273 for func in chain:
272 dispatcher.add(func)
274 dispatcher.add(func)
273 text = dispatcher()
275 text = dispatcher()
274 return text
276 return text
@@ -1,38 +1,36 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 This module is *completely* deprecated and should no longer be used for
4 This module is *completely* deprecated and should no longer be used for
5 any purpose. Currently, we have a few parts of the core that have
5 any purpose. Currently, we have a few parts of the core that have
6 not been componentized and thus, still rely on this module. When everything
6 not been componentized and thus, still rely on this module. When everything
7 has been made into a component, this module will be sent to deathrow.
7 has been made into a component, this module will be sent to deathrow.
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 from IPython.core.error import TryNext, UsageError, IPythonCoreError
22
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
24 # Classes and functions
22 # Classes and functions
25 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
26
24
27
25
28 def get():
26 def get():
29 """Get the most recently created InteractiveShell instance."""
27 """Get the most recently created InteractiveShell instance."""
30 from IPython.core.iplib import InteractiveShell
28 from IPython.core.iplib import InteractiveShell
31 insts = InteractiveShell.get_instances()
29 insts = InteractiveShell.get_instances()
32 if len(insts)==0:
30 if len(insts)==0:
33 return None
31 return None
34 most_recent = insts[0]
32 most_recent = insts[0]
35 for inst in insts[1:]:
33 for inst in insts[1:]:
36 if inst.created > most_recent.created:
34 if inst.created > most_recent.created:
37 most_recent = inst
35 most_recent = inst
38 return most_recent
36 return most_recent
This diff has been collapsed as it changes many lines, (699 lines changed) Show them Hide them
@@ -1,544 +1,653 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors:
7 Authors
8 -------
8
9
9 * Brian Granger
10 * Brian Granger
10 * Fernando Perez
11 * Fernando Perez
11
12 Notes
13 -----
14 """
12 """
15
13
16 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008-2009 The IPython Development Team
15 # Copyright (C) 2008-2010 The IPython Development Team
18 #
16 #
19 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
22
20
23 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
24 # Imports
22 # Imports
25 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
26
24
25 from __future__ import absolute_import
26
27 import logging
27 import logging
28 import os
28 import os
29 import sys
29 import sys
30 import warnings
31
30
32 from IPython.core.application import Application, BaseAppArgParseConfigLoader
33 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.core.iplib import InteractiveShell
34 from IPython.core.iplib import InteractiveShell
35 from IPython.config.loader import (
35 from IPython.config.loader import (
36 NoConfigDefault,
37 Config,
36 Config,
38 PyFileConfigLoader
37 PyFileConfigLoader
39 )
38 )
40
41 from IPython.lib import inputhook
39 from IPython.lib import inputhook
40 from IPython.utils.path import filefind, get_ipython_dir
41 from . import usage
42
43 #-----------------------------------------------------------------------------
44 # Globals, utilities and helpers
45 #-----------------------------------------------------------------------------
46
47 #: The default config file name for this application.
48 default_config_file_name = u'ipython_config.py'
49
50
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
58 help=
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
69 help=
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
75 metavar='Global.config_file')
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
78 help=
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
102 action='store_true', dest='InteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='InteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
146 action='store_true', dest='InteractiveShell.confirm_exit',
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
152 action='store_false', dest='InteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
165 dreload()].""")
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
170 type=str, dest='InteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='InteractiveShell.editor')
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
191 action='store_true', dest='InteractiveShell.pprint',
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
194 action='store_false', dest='InteractiveShell.pprint',
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
231 type=int, dest='InteractiveShell.screen_length',
232 help=
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
242 metavar='InteractiveShell.screen_length')
243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
259 action='store_true', dest='InteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
262 action='store_false', dest='InteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
277 """,
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
283 paa('-c',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
289 help=
290 "If running code from the command line, become interactive afterwards.")
291
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
42
319
43 from IPython.utils.genutils import filefind, get_ipython_dir
44
320
45 #-----------------------------------------------------------------------------
321 #-----------------------------------------------------------------------------
46 # Utilities and helpers
322 # Crash handler for this application
47 #-----------------------------------------------------------------------------
323 #-----------------------------------------------------------------------------
48
324
49
325
50 ipython_desc = """
326 _message_template = """\
51 A Python shell with automatic history (input and output), dynamic object
327 Oops, $self.app_name crashed. We do our best to make it stable, but...
52 introspection, easier configuration, command completion, access to the system
53 shell and more.
54 """
55
328
56 def pylab_warning():
329 A crash report was automatically generated with the following information:
57 msg = """
330 - A verbatim copy of the crash traceback.
331 - A copy of your input history during this session.
332 - Data on your current $self.app_name configuration.
58
333
59 IPython's -pylab mode has been disabled until matplotlib supports this version
334 It was left in the file named:
60 of IPython. This version of IPython has greatly improved GUI integration that
335 \t'$self.crash_report_fname'
61 matplotlib will soon be able to take advantage of. This will eventually
336 If you can email this file to the developers, the information in it will help
62 result in greater stability and a richer API for matplotlib under IPython.
337 them in understanding and correcting the problem.
63 However during this transition, you will either need to use an older version
64 of IPython, or do the following to use matplotlib interactively::
65
338
66 import matplotlib
339 You can mail it to: $self.contact_name at $self.contact_email
67 matplotlib.interactive(True)
340 with the subject '$self.app_name Crash Report'.
68 matplotlib.use('wxagg') # adjust for your backend
69 %gui -a wx # adjust for your GUI
70 from matplotlib import pyplot as plt
71
341
72 See the %gui magic for information on the new interface.
342 If you want to do it now, the following command will work (under Unix):
73 """
343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
74 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
75
344
345 To ensure accurate tracking of this issue, please file a report about it at:
346 $self.bug_tracker
347 """
76
348
77 #-----------------------------------------------------------------------------
349 class IPAppCrashHandler(CrashHandler):
78 # Main classes and functions
350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
79 #-----------------------------------------------------------------------------
80
351
81 cl_args = (
352 message_template = _message_template
82 (('--autocall',), dict(
83 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
84 help='Set the autocall value (0,1,2).',
85 metavar='InteractiveShell.autocall')
86 ),
87 (('--autoindent',), dict(
88 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
89 help='Turn on autoindenting.')
90 ),
91 (('--no-autoindent',), dict(
92 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
93 help='Turn off autoindenting.')
94 ),
95 (('--automagic',), dict(
96 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
97 help='Turn on the auto calling of magic commands.')
98 ),
99 (('--no-automagic',), dict(
100 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
101 help='Turn off the auto calling of magic commands.')
102 ),
103 (('--autoedit-syntax',), dict(
104 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
105 help='Turn on auto editing of files with syntax errors.')
106 ),
107 (('--no-autoedit-syntax',), dict(
108 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
109 help='Turn off auto editing of files with syntax errors.')
110 ),
111 (('--banner',), dict(
112 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
113 help='Display a banner upon starting IPython.')
114 ),
115 (('--no-banner',), dict(
116 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
117 help="Don't display a banner upon starting IPython.")
118 ),
119 (('--cache-size',), dict(
120 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
121 help="Set the size of the output cache.",
122 metavar='InteractiveShell.cache_size')
123 ),
124 (('--classic',), dict(
125 action='store_true', dest='Global.classic', default=NoConfigDefault,
126 help="Gives IPython a similar feel to the classic Python prompt.")
127 ),
128 (('--colors',), dict(
129 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
130 help="Set the color scheme (NoColor, Linux, and LightBG).",
131 metavar='InteractiveShell.colors')
132 ),
133 (('--color-info',), dict(
134 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
135 help="Enable using colors for info related things.")
136 ),
137 (('--no-color-info',), dict(
138 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
139 help="Disable using colors for info related things.")
140 ),
141 (('--confirm-exit',), dict(
142 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
143 help="Prompt the user when existing.")
144 ),
145 (('--no-confirm-exit',), dict(
146 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
147 help="Don't prompt the user when existing.")
148 ),
149 (('--deep-reload',), dict(
150 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
151 help="Enable deep (recursive) reloading by default.")
152 ),
153 (('--no-deep-reload',), dict(
154 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
155 help="Disable deep (recursive) reloading by default.")
156 ),
157 (('--editor',), dict(
158 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
159 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
160 metavar='InteractiveShell.editor')
161 ),
162 (('--log','-l'), dict(
163 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
164 help="Start logging to the default file (./ipython_log.py).")
165 ),
166 (('--logfile','-lf'), dict(
167 type=unicode, dest='InteractiveShell.logfile', default=NoConfigDefault,
168 help="Start logging to logfile.",
169 metavar='InteractiveShell.logfile')
170 ),
171 (('--log-append','-la'), dict(
172 type=unicode, dest='InteractiveShell.logappend', default=NoConfigDefault,
173 help="Start logging to the give file in append mode.",
174 metavar='InteractiveShell.logfile')
175 ),
176 (('--pdb',), dict(
177 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
178 help="Enable auto calling the pdb debugger after every exception.")
179 ),
180 (('--no-pdb',), dict(
181 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
182 help="Disable auto calling the pdb debugger after every exception.")
183 ),
184 (('--pprint',), dict(
185 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
186 help="Enable auto pretty printing of results.")
187 ),
188 (('--no-pprint',), dict(
189 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
190 help="Disable auto auto pretty printing of results.")
191 ),
192 (('--prompt-in1','-pi1'), dict(
193 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
194 help="Set the main input prompt ('In [\#]: ')",
195 metavar='InteractiveShell.prompt_in1')
196 ),
197 (('--prompt-in2','-pi2'), dict(
198 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
199 help="Set the secondary input prompt (' .\D.: ')",
200 metavar='InteractiveShell.prompt_in2')
201 ),
202 (('--prompt-out','-po'), dict(
203 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
204 help="Set the output prompt ('Out[\#]:')",
205 metavar='InteractiveShell.prompt_out')
206 ),
207 (('--quick',), dict(
208 action='store_true', dest='Global.quick', default=NoConfigDefault,
209 help="Enable quick startup with no config files.")
210 ),
211 (('--readline',), dict(
212 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
213 help="Enable readline for command line usage.")
214 ),
215 (('--no-readline',), dict(
216 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
217 help="Disable readline for command line usage.")
218 ),
219 (('--screen-length','-sl'), dict(
220 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
221 help='Number of lines on screen, used to control printing of long strings.',
222 metavar='InteractiveShell.screen_length')
223 ),
224 (('--separate-in','-si'), dict(
225 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
226 help="Separator before input prompts. Default '\n'.",
227 metavar='InteractiveShell.separate_in')
228 ),
229 (('--separate-out','-so'), dict(
230 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
231 help="Separator before output prompts. Default 0 (nothing).",
232 metavar='InteractiveShell.separate_out')
233 ),
234 (('--separate-out2','-so2'), dict(
235 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
236 help="Separator after output prompts. Default 0 (nonight).",
237 metavar='InteractiveShell.separate_out2')
238 ),
239 (('-no-sep',), dict(
240 action='store_true', dest='Global.nosep', default=NoConfigDefault,
241 help="Eliminate all spacing between prompts.")
242 ),
243 (('--term-title',), dict(
244 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
245 help="Enable auto setting the terminal title.")
246 ),
247 (('--no-term-title',), dict(
248 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
249 help="Disable auto setting the terminal title.")
250 ),
251 (('--xmode',), dict(
252 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
253 help="Exception mode ('Plain','Context','Verbose')",
254 metavar='InteractiveShell.xmode')
255 ),
256 (('--ext',), dict(
257 type=str, dest='Global.extra_extension', default=NoConfigDefault,
258 help="The dotted module name of an IPython extension to load.",
259 metavar='Global.extra_extension')
260 ),
261 (('-c',), dict(
262 type=str, dest='Global.code_to_run', default=NoConfigDefault,
263 help="Execute the given command string.",
264 metavar='Global.code_to_run')
265 ),
266 (('-i',), dict(
267 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
268 help="If running code from the command line, become interactive afterwards.")
269 ),
270 (('--wthread',), dict(
271 action='store_true', dest='Global.wthread', default=NoConfigDefault,
272 help="Enable wxPython event loop integration.")
273 ),
274 (('--q4thread','--qthread'), dict(
275 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
276 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
277 ),
278 (('--gthread',), dict(
279 action='store_true', dest='Global.gthread', default=NoConfigDefault,
280 help="Enable GTK event loop integration.")
281 ),
282 # # These are only here to get the proper deprecation warnings
283 (('--pylab',), dict(
284 action='store_true', dest='Global.pylab', default=NoConfigDefault,
285 help="Disabled. Pylab has been disabled until matplotlib "
286 "supports this version of IPython.")
287 )
288 )
289
353
354 def __init__(self, app):
355 contact_name = release.authors['Fernando'][0]
356 contact_email = release.authors['Fernando'][1]
357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
358 super(IPAppCrashHandler,self).__init__(
359 app, contact_name, contact_email, bug_tracker
360 )
290
361
291 class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader):
362 def make_report(self,traceback):
363 """Return a string containing a crash report."""
292
364
293 arguments = cl_args
365 sec_sep = self.section_sep
366 # Start with parent report
367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
368 # Add interactive-specific info we may have
369 rpt_add = report.append
370 try:
371 rpt_add(sec_sep+"History of session input:")
372 for line in self.app.shell.user_ns['_ih']:
373 rpt_add(line)
374 rpt_add('\n*** Last line of input (may not be in above history):\n')
375 rpt_add(self.app.shell._last_input_line+'\n')
376 except:
377 pass
294
378
379 return ''.join(report)
295
380
296 default_config_file_name = u'ipython_config.py'
297
381
382 #-----------------------------------------------------------------------------
383 # Main classes and functions
384 #-----------------------------------------------------------------------------
298
385
299 class IPythonApp(Application):
386 class IPythonApp(Application):
300 name = u'ipython'
387 name = u'ipython'
301 description = 'IPython: an enhanced interactive Python shell.'
388 #: argparse formats better the 'usage' than the 'description' field
302 config_file_name = default_config_file_name
389 description = None
390 usage = usage.cl_usage
391 command_line_loader = IPAppConfigLoader
392 default_config_file_name = default_config_file_name
393 crash_handler_class = IPAppCrashHandler
303
394
304 def create_default_config(self):
395 def create_default_config(self):
305 super(IPythonApp, self).create_default_config()
396 super(IPythonApp, self).create_default_config()
306 self.default_config.Global.display_banner = True
397 # Eliminate multiple lookups
398 Global = self.default_config.Global
399
400 # Set all default values
401 Global.display_banner = True
307
402
308 # If the -c flag is given or a file is given to run at the cmd line
403 # If the -c flag is given or a file is given to run at the cmd line
309 # like "ipython foo.py", normally we exit without starting the main
404 # like "ipython foo.py", normally we exit without starting the main
310 # loop. The force_interact config variable allows a user to override
405 # loop. The force_interact config variable allows a user to override
311 # this and interact. It is also set by the -i cmd line flag, just
406 # this and interact. It is also set by the -i cmd line flag, just
312 # like Python.
407 # like Python.
313 self.default_config.Global.force_interact = False
408 Global.force_interact = False
314
409
315 # By default always interact by starting the IPython mainloop.
410 # By default always interact by starting the IPython mainloop.
316 self.default_config.Global.interact = True
411 Global.interact = True
317
412
318 # No GUI integration by default
413 # No GUI integration by default
319 self.default_config.Global.wthread = False
414 Global.gui = False
320 self.default_config.Global.q4thread = False
415 # Pylab off by default
321 self.default_config.Global.gthread = False
416 Global.pylab = False
322
417
323 def create_command_line_config(self):
418 # Deprecated versions of gui support that used threading, we support
324 """Create and return a command line config loader."""
419 # them just for bacwards compatibility as an alternate spelling for
325 return IPythonAppCLConfigLoader(
420 # '--gui X'
326 description=self.description,
421 Global.qthread = False
327 version=release.version
422 Global.q4thread = False
328 )
423 Global.wthread = False
329
424 Global.gthread = False
330 def post_load_command_line_config(self):
331 """Do actions after loading cl config."""
332 clc = self.command_line_config
333
334 # Display the deprecation warnings about threaded shells
335 if hasattr(clc.Global, 'pylab'):
336 pylab_warning()
337 del clc.Global['pylab']
338
425
339 def load_file_config(self):
426 def load_file_config(self):
340 if hasattr(self.command_line_config.Global, 'quick'):
427 if hasattr(self.command_line_config.Global, 'quick'):
341 if self.command_line_config.Global.quick:
428 if self.command_line_config.Global.quick:
342 self.file_config = Config()
429 self.file_config = Config()
343 return
430 return
344 super(IPythonApp, self).load_file_config()
431 super(IPythonApp, self).load_file_config()
345
432
346 def post_load_file_config(self):
433 def post_load_file_config(self):
347 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 if hasattr(self.command_line_config.Global, 'extra_extension'):
348 if not hasattr(self.file_config.Global, 'extensions'):
435 if not hasattr(self.file_config.Global, 'extensions'):
349 self.file_config.Global.extensions = []
436 self.file_config.Global.extensions = []
350 self.file_config.Global.extensions.append(
437 self.file_config.Global.extensions.append(
351 self.command_line_config.Global.extra_extension)
438 self.command_line_config.Global.extra_extension)
352 del self.command_line_config.Global.extra_extension
439 del self.command_line_config.Global.extra_extension
353
440
354 def pre_construct(self):
441 def pre_construct(self):
355 config = self.master_config
442 config = self.master_config
356
443
357 if hasattr(config.Global, 'classic'):
444 if hasattr(config.Global, 'classic'):
358 if config.Global.classic:
445 if config.Global.classic:
359 config.InteractiveShell.cache_size = 0
446 config.InteractiveShell.cache_size = 0
360 config.InteractiveShell.pprint = 0
447 config.InteractiveShell.pprint = 0
361 config.InteractiveShell.prompt_in1 = '>>> '
448 config.InteractiveShell.prompt_in1 = '>>> '
362 config.InteractiveShell.prompt_in2 = '... '
449 config.InteractiveShell.prompt_in2 = '... '
363 config.InteractiveShell.prompt_out = ''
450 config.InteractiveShell.prompt_out = ''
364 config.InteractiveShell.separate_in = \
451 config.InteractiveShell.separate_in = \
365 config.InteractiveShell.separate_out = \
452 config.InteractiveShell.separate_out = \
366 config.InteractiveShell.separate_out2 = ''
453 config.InteractiveShell.separate_out2 = ''
367 config.InteractiveShell.colors = 'NoColor'
454 config.InteractiveShell.colors = 'NoColor'
368 config.InteractiveShell.xmode = 'Plain'
455 config.InteractiveShell.xmode = 'Plain'
369
456
370 if hasattr(config.Global, 'nosep'):
457 if hasattr(config.Global, 'nosep'):
371 if config.Global.nosep:
458 if config.Global.nosep:
372 config.InteractiveShell.separate_in = \
459 config.InteractiveShell.separate_in = \
373 config.InteractiveShell.separate_out = \
460 config.InteractiveShell.separate_out = \
374 config.InteractiveShell.separate_out2 = ''
461 config.InteractiveShell.separate_out2 = ''
375
462
376 # if there is code of files to run from the cmd line, don't interact
463 # if there is code of files to run from the cmd line, don't interact
377 # unless the -i flag (Global.force_interact) is true.
464 # unless the -i flag (Global.force_interact) is true.
378 code_to_run = config.Global.get('code_to_run','')
465 code_to_run = config.Global.get('code_to_run','')
379 file_to_run = False
466 file_to_run = False
380 if len(self.extra_args)>=1:
467 if self.extra_args and self.extra_args[0]:
381 if self.extra_args[0]:
382 file_to_run = True
468 file_to_run = True
383 if file_to_run or code_to_run:
469 if file_to_run or code_to_run:
384 if not config.Global.force_interact:
470 if not config.Global.force_interact:
385 config.Global.interact = False
471 config.Global.interact = False
386
472
387 def construct(self):
473 def construct(self):
388 # I am a little hesitant to put these into InteractiveShell itself.
474 # I am a little hesitant to put these into InteractiveShell itself.
389 # But that might be the place for them
475 # But that might be the place for them
390 sys.path.insert(0, '')
476 sys.path.insert(0, '')
391
477
392 # Create an InteractiveShell instance
478 # Create an InteractiveShell instance
393 self.shell = InteractiveShell(
479 self.shell = InteractiveShell(None, self.master_config)
394 parent=None,
395 config=self.master_config
396 )
397
480
398 def post_construct(self):
481 def post_construct(self):
399 """Do actions after construct, but before starting the app."""
482 """Do actions after construct, but before starting the app."""
400 config = self.master_config
483 config = self.master_config
401
484
402 # shell.display_banner should always be False for the terminal
485 # shell.display_banner should always be False for the terminal
403 # based app, because we call shell.show_banner() by hand below
486 # based app, because we call shell.show_banner() by hand below
404 # so the banner shows *before* all extension loading stuff.
487 # so the banner shows *before* all extension loading stuff.
405 self.shell.display_banner = False
488 self.shell.display_banner = False
406
407 if config.Global.display_banner and \
489 if config.Global.display_banner and \
408 config.Global.interact:
490 config.Global.interact:
409 self.shell.show_banner()
491 self.shell.show_banner()
410
492
411 # Make sure there is a space below the banner.
493 # Make sure there is a space below the banner.
412 if self.log_level <= logging.INFO: print
494 if self.log_level <= logging.INFO: print
413
495
414 # Now a variety of things that happen after the banner is printed.
496 # Now a variety of things that happen after the banner is printed.
415 self._enable_gui()
497 self._enable_gui_pylab()
416 self._load_extensions()
498 self._load_extensions()
417 self._run_exec_lines()
499 self._run_exec_lines()
418 self._run_exec_files()
500 self._run_exec_files()
419 self._run_cmd_line_code()
501 self._run_cmd_line_code()
420
502
421 def _enable_gui(self):
503 def _enable_gui_pylab(self):
422 """Enable GUI event loop integration."""
504 """Enable GUI event loop integration, taking pylab into account."""
423 config = self.master_config
505 Global = self.master_config.Global
424 try:
506
425 # Enable GUI integration
507 # Select which gui to use
426 if config.Global.wthread:
508 if Global.gui:
427 self.log.info("Enabling wx GUI event loop integration")
509 gui = Global.gui
428 inputhook.enable_wx(app=True)
510 # The following are deprecated, but there's likely to be a lot of use
429 elif config.Global.q4thread:
511 # of this form out there, so we might as well support it for now. But
430 self.log.info("Enabling Qt4 GUI event loop integration")
512 # the --gui option above takes precedence.
431 inputhook.enable_qt4(app=True)
513 elif Global.wthread:
432 elif config.Global.gthread:
514 gui = inputhook.GUI_WX
433 self.log.info("Enabling GTK GUI event loop integration")
515 elif Global.qthread:
434 inputhook.enable_gtk(app=True)
516 gui = inputhook.GUI_QT
435 except:
517 elif Global.gthread:
436 self.log.warn("Error in enabling GUI event loop integration:")
518 gui = inputhook.GUI_GTK
437 self.shell.showtraceback()
519 else:
520 gui = None
521
522 # Using --pylab will also require gui activation, though which toolkit
523 # to use may be chosen automatically based on mpl configuration.
524 if Global.pylab:
525 activate = self.shell.enable_pylab
526 if Global.pylab == 'auto':
527 gui = None
528 else:
529 gui = Global.pylab
530 else:
531 # Enable only GUI integration, no pylab
532 activate = inputhook.enable_gui
533
534 if gui or Global.pylab:
535 try:
536 self.log.info("Enabling GUI event loop integration, "
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
538 activate(gui)
539 except:
540 self.log.warn("Error in enabling GUI event loop integration:")
541 self.shell.showtraceback()
438
542
439 def _load_extensions(self):
543 def _load_extensions(self):
440 """Load all IPython extensions in Global.extensions.
544 """Load all IPython extensions in Global.extensions.
441
545
442 This uses the :meth:`InteractiveShell.load_extensions` to load all
546 This uses the :meth:`InteractiveShell.load_extensions` to load all
443 the extensions listed in ``self.master_config.Global.extensions``.
547 the extensions listed in ``self.master_config.Global.extensions``.
444 """
548 """
445 try:
549 try:
446 if hasattr(self.master_config.Global, 'extensions'):
550 if hasattr(self.master_config.Global, 'extensions'):
447 self.log.debug("Loading IPython extensions...")
551 self.log.debug("Loading IPython extensions...")
448 extensions = self.master_config.Global.extensions
552 extensions = self.master_config.Global.extensions
449 for ext in extensions:
553 for ext in extensions:
450 try:
554 try:
451 self.log.info("Loading IPython extension: %s" % ext)
555 self.log.info("Loading IPython extension: %s" % ext)
452 self.shell.load_extension(ext)
556 self.shell.load_extension(ext)
453 except:
557 except:
454 self.log.warn("Error in loading extension: %s" % ext)
558 self.log.warn("Error in loading extension: %s" % ext)
455 self.shell.showtraceback()
559 self.shell.showtraceback()
456 except:
560 except:
457 self.log.warn("Unknown error in loading extensions:")
561 self.log.warn("Unknown error in loading extensions:")
458 self.shell.showtraceback()
562 self.shell.showtraceback()
459
563
460 def _run_exec_lines(self):
564 def _run_exec_lines(self):
461 """Run lines of code in Global.exec_lines in the user's namespace."""
565 """Run lines of code in Global.exec_lines in the user's namespace."""
462 try:
566 try:
463 if hasattr(self.master_config.Global, 'exec_lines'):
567 if hasattr(self.master_config.Global, 'exec_lines'):
464 self.log.debug("Running code from Global.exec_lines...")
568 self.log.debug("Running code from Global.exec_lines...")
465 exec_lines = self.master_config.Global.exec_lines
569 exec_lines = self.master_config.Global.exec_lines
466 for line in exec_lines:
570 for line in exec_lines:
467 try:
571 try:
468 self.log.info("Running code in user namespace: %s" % line)
572 self.log.info("Running code in user namespace: %s" % line)
469 self.shell.runlines(line)
573 self.shell.runlines(line)
470 except:
574 except:
471 self.log.warn("Error in executing line in user namespace: %s" % line)
575 self.log.warn("Error in executing line in user namespace: %s" % line)
472 self.shell.showtraceback()
576 self.shell.showtraceback()
473 except:
577 except:
474 self.log.warn("Unknown error in handling Global.exec_lines:")
578 self.log.warn("Unknown error in handling Global.exec_lines:")
475 self.shell.showtraceback()
579 self.shell.showtraceback()
476
580
477 def _exec_file(self, fname):
581 def _exec_file(self, fname):
478 full_filename = filefind(fname, [u'.', self.ipython_dir])
582 full_filename = filefind(fname, [u'.', self.ipython_dir])
479 if os.path.isfile(full_filename):
583 if os.path.isfile(full_filename):
480 if full_filename.endswith(u'.py'):
584 if full_filename.endswith(u'.py'):
481 self.log.info("Running file in user namespace: %s" % full_filename)
585 self.log.info("Running file in user namespace: %s" % full_filename)
482 self.shell.safe_execfile(full_filename, self.shell.user_ns)
586 self.shell.safe_execfile(full_filename, self.shell.user_ns)
483 elif full_filename.endswith('.ipy'):
587 elif full_filename.endswith('.ipy'):
484 self.log.info("Running file in user namespace: %s" % full_filename)
588 self.log.info("Running file in user namespace: %s" % full_filename)
485 self.shell.safe_execfile_ipy(full_filename)
589 self.shell.safe_execfile_ipy(full_filename)
486 else:
590 else:
487 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
591 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
488
592
489 def _run_exec_files(self):
593 def _run_exec_files(self):
490 try:
594 try:
491 if hasattr(self.master_config.Global, 'exec_files'):
595 if hasattr(self.master_config.Global, 'exec_files'):
492 self.log.debug("Running files in Global.exec_files...")
596 self.log.debug("Running files in Global.exec_files...")
493 exec_files = self.master_config.Global.exec_files
597 exec_files = self.master_config.Global.exec_files
494 for fname in exec_files:
598 for fname in exec_files:
495 self._exec_file(fname)
599 self._exec_file(fname)
496 except:
600 except:
497 self.log.warn("Unknown error in handling Global.exec_files:")
601 self.log.warn("Unknown error in handling Global.exec_files:")
498 self.shell.showtraceback()
602 self.shell.showtraceback()
499
603
500 def _run_cmd_line_code(self):
604 def _run_cmd_line_code(self):
501 if hasattr(self.master_config.Global, 'code_to_run'):
605 if hasattr(self.master_config.Global, 'code_to_run'):
502 line = self.master_config.Global.code_to_run
606 line = self.master_config.Global.code_to_run
503 try:
607 try:
504 self.log.info("Running code given at command line (-c): %s" % line)
608 self.log.info("Running code given at command line (-c): %s" % line)
505 self.shell.runlines(line)
609 self.shell.runlines(line)
506 except:
610 except:
507 self.log.warn("Error in executing line in user namespace: %s" % line)
611 self.log.warn("Error in executing line in user namespace: %s" % line)
508 self.shell.showtraceback()
612 self.shell.showtraceback()
509 return
613 return
510 # Like Python itself, ignore the second if the first of these is present
614 # Like Python itself, ignore the second if the first of these is present
511 try:
615 try:
512 fname = self.extra_args[0]
616 fname = self.extra_args[0]
513 except:
617 except:
514 pass
618 pass
515 else:
619 else:
516 try:
620 try:
517 self._exec_file(fname)
621 self._exec_file(fname)
518 except:
622 except:
519 self.log.warn("Error in executing file in user namespace: %s" % fname)
623 self.log.warn("Error in executing file in user namespace: %s" % fname)
520 self.shell.showtraceback()
624 self.shell.showtraceback()
521
625
522 def start_app(self):
626 def start_app(self):
523 if self.master_config.Global.interact:
627 if self.master_config.Global.interact:
524 self.log.debug("Starting IPython's mainloop...")
628 self.log.debug("Starting IPython's mainloop...")
525 self.shell.mainloop()
629 self.shell.mainloop()
630 else:
631 self.log.debug("IPython not interactive, start_app is no-op...")
526
632
527
633
528 def load_default_config(ipython_dir=None):
634 def load_default_config(ipython_dir=None):
529 """Load the default config file from the default ipython_dir.
635 """Load the default config file from the default ipython_dir.
530
636
531 This is useful for embedded shells.
637 This is useful for embedded shells.
532 """
638 """
533 if ipython_dir is None:
639 if ipython_dir is None:
534 ipython_dir = get_ipython_dir()
640 ipython_dir = get_ipython_dir()
535 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
641 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
536 config = cl.load_config()
642 config = cl.load_config()
537 return config
643 return config
538
644
539
645
540 def launch_new_instance():
646 def launch_new_instance():
541 """Create and run a full blown IPython instance"""
647 """Create and run a full blown IPython instance"""
542 app = IPythonApp()
648 app = IPythonApp()
543 app.start()
649 app.start()
544
650
651
652 if __name__ == '__main__':
653 launch_new_instance()
@@ -1,2488 +1,2561 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from __future__ import with_statement
19 from __future__ import with_statement
20 from __future__ import absolute_import
20
21
21 import __builtin__
22 import __builtin__
22 import StringIO
23 import bdb
23 import bdb
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.core import ultratb
35 from IPython.core import debugger, oinspect
34 from IPython.core import debugger, oinspect
36 from IPython.core import shadowns
37 from IPython.core import history as ipcorehist
35 from IPython.core import history as ipcorehist
38 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.component import Component
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.error import TryNext, UsageError
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
44 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
45 from IPython.core.prompts import CachedOutput
46 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.component import Component
48 from IPython.core.prompts import CachedOutput
48 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
50 import IPython.core.hooks
50
51 from IPython.utils import pickleshare
52 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
52 from IPython.lib.inputhook import enable_gui
53 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils.ipstruct import Struct
54 from IPython.lib.pylabtools import pylab_activate
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils.genutils import *
56 from IPython.utils import pickleshare
57 from IPython.utils.genutils import get_ipython_dir
57 from IPython.utils.doctestreload import doctest_reload
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
58 from IPython.utils.ipstruct import Struct
59 from IPython.utils.io import Term, ask_yes_no
60 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
61 from IPython.utils.process import (
62 abbrev_cwd,
63 getoutput,
64 getoutputerror
65 )
66 # import IPython.utils.rlineimpl as readline
59 from IPython.utils.strdispatch import StrDispatch
67 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
68 from IPython.utils.syspathcontext import prepended_to_syspath
61
69 from IPython.utils.terminal import toggle_set_term_title, set_term_title
62 # from IPython.utils import growl
70 from IPython.utils.warn import warn, error, fatal
63 # growl.start("IPython")
64
65 from IPython.utils.traitlets import (
71 from IPython.utils.traitlets import (
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
72 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
67 )
73 )
68
74
75 # from IPython.utils import growl
76 # growl.start("IPython")
77
69 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
70 # Globals
79 # Globals
71 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
72
81
73
74 # 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
75 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
76 raw_input_original = raw_input
84 raw_input_original = raw_input
77
85
78 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80
88
81
82 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
83 # Utilities
90 # Utilities
84 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
85
92
86
87 ini_spaces_re = re.compile(r'^(\s+)')
93 ini_spaces_re = re.compile(r'^(\s+)')
88
94
89
95
90 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
91 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
92
98
93 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
94 if ini_spaces:
100 if ini_spaces:
95 return ini_spaces.end()
101 return ini_spaces.end()
96 else:
102 else:
97 return 0
103 return 0
98
104
99
105
100 def softspace(file, newvalue):
106 def softspace(file, newvalue):
101 """Copied from code.py, to remove the dependency"""
107 """Copied from code.py, to remove the dependency"""
102
108
103 oldvalue = 0
109 oldvalue = 0
104 try:
110 try:
105 oldvalue = file.softspace
111 oldvalue = file.softspace
106 except AttributeError:
112 except AttributeError:
107 pass
113 pass
108 try:
114 try:
109 file.softspace = newvalue
115 file.softspace = newvalue
110 except (AttributeError, TypeError):
116 except (AttributeError, TypeError):
111 # "attribute-less object" or "read-only attributes"
117 # "attribute-less object" or "read-only attributes"
112 pass
118 pass
113 return oldvalue
119 return oldvalue
114
120
115
121
122 def no_op(*a, **kw): pass
123
116 class SpaceInInput(exceptions.Exception): pass
124 class SpaceInInput(exceptions.Exception): pass
117
125
118 class Bunch: pass
126 class Bunch: pass
119
127
120 class InputList(list):
128 class InputList(list):
121 """Class to store user input.
129 """Class to store user input.
122
130
123 It's basically a list, but slices return a string instead of a list, thus
131 It's basically a list, but slices return a string instead of a list, thus
124 allowing things like (assuming 'In' is an instance):
132 allowing things like (assuming 'In' is an instance):
125
133
126 exec In[4:7]
134 exec In[4:7]
127
135
128 or
136 or
129
137
130 exec In[5:9] + In[14] + In[21:25]"""
138 exec In[5:9] + In[14] + In[21:25]"""
131
139
132 def __getslice__(self,i,j):
140 def __getslice__(self,i,j):
133 return ''.join(list.__getslice__(self,i,j))
141 return ''.join(list.__getslice__(self,i,j))
134
142
135
143
136 class SyntaxTB(ultratb.ListTB):
144 class SyntaxTB(ultratb.ListTB):
137 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
138
146
139 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
140 ultratb.ListTB.__init__(self,color_scheme)
148 ultratb.ListTB.__init__(self,color_scheme)
141 self.last_syntax_error = None
149 self.last_syntax_error = None
142
150
143 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
144 self.last_syntax_error = value
152 self.last_syntax_error = value
145 ultratb.ListTB.__call__(self,etype,value,elist)
153 ultratb.ListTB.__call__(self,etype,value,elist)
146
154
147 def clear_err_state(self):
155 def clear_err_state(self):
148 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
149 e = self.last_syntax_error
157 e = self.last_syntax_error
150 self.last_syntax_error = None
158 self.last_syntax_error = None
151 return e
159 return e
152
160
153
161
154 def get_default_editor():
162 def get_default_editor():
155 try:
163 try:
156 ed = os.environ['EDITOR']
164 ed = os.environ['EDITOR']
157 except KeyError:
165 except KeyError:
158 if os.name == 'posix':
166 if os.name == 'posix':
159 ed = 'vi' # the only one guaranteed to be there!
167 ed = 'vi' # the only one guaranteed to be there!
160 else:
168 else:
161 ed = 'notepad' # same in Windows!
169 ed = 'notepad' # same in Windows!
162 return ed
170 return ed
163
171
164
172
165 def get_default_colors():
173 def get_default_colors():
166 if sys.platform=='darwin':
174 if sys.platform=='darwin':
167 return "LightBG"
175 return "LightBG"
168 elif os.name=='nt':
176 elif os.name=='nt':
169 return 'Linux'
177 return 'Linux'
170 else:
178 else:
171 return 'Linux'
179 return 'Linux'
172
180
173
181
174 class SeparateStr(Str):
182 class SeparateStr(Str):
175 """A Str subclass to validate separate_in, separate_out, etc.
183 """A Str subclass to validate separate_in, separate_out, etc.
176
184
177 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
185 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
178 """
186 """
179
187
180 def validate(self, obj, value):
188 def validate(self, obj, value):
181 if value == '0': value = ''
189 if value == '0': value = ''
182 value = value.replace('\\n','\n')
190 value = value.replace('\\n','\n')
183 return super(SeparateStr, self).validate(obj, value)
191 return super(SeparateStr, self).validate(obj, value)
184
192
185
193
186 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
187 # Main IPython class
195 # Main IPython class
188 #-----------------------------------------------------------------------------
196 #-----------------------------------------------------------------------------
189
197
190
198
191 class InteractiveShell(Component, Magic):
199 class InteractiveShell(Component, Magic):
192 """An enhanced, interactive shell for Python."""
200 """An enhanced, interactive shell for Python."""
193
201
194 autocall = Enum((0,1,2), default_value=1, config=True)
202 autocall = Enum((0,1,2), default_value=1, config=True)
195 autoedit_syntax = CBool(False, config=True)
203 autoedit_syntax = CBool(False, config=True)
196 autoindent = CBool(True, config=True)
204 autoindent = CBool(True, config=True)
197 automagic = CBool(True, config=True)
205 automagic = CBool(True, config=True)
198 banner = Str('')
206 banner = Str('')
199 banner1 = Str(default_banner, config=True)
207 banner1 = Str(default_banner, config=True)
200 banner2 = Str('', config=True)
208 banner2 = Str('', config=True)
201 cache_size = Int(1000, config=True)
209 cache_size = Int(1000, config=True)
202 color_info = CBool(True, config=True)
210 color_info = CBool(True, config=True)
203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
211 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
204 default_value=get_default_colors(), config=True)
212 default_value=get_default_colors(), config=True)
205 confirm_exit = CBool(True, config=True)
213 confirm_exit = CBool(True, config=True)
206 debug = CBool(False, config=True)
214 debug = CBool(False, config=True)
207 deep_reload = CBool(False, config=True)
215 deep_reload = CBool(False, config=True)
208 # This display_banner only controls whether or not self.show_banner()
216 # This display_banner only controls whether or not self.show_banner()
209 # is called when mainloop/interact are called. The default is False
217 # is called when mainloop/interact are called. The default is False
210 # because for the terminal based application, the banner behavior
218 # because for the terminal based application, the banner behavior
211 # is controlled by Global.display_banner, which IPythonApp looks at
219 # is controlled by Global.display_banner, which IPythonApp looks at
212 # to determine if *it* should call show_banner() by hand or not.
220 # to determine if *it* should call show_banner() by hand or not.
213 display_banner = CBool(False) # This isn't configurable!
221 display_banner = CBool(False) # This isn't configurable!
214 embedded = CBool(False)
222 embedded = CBool(False)
215 embedded_active = CBool(False)
223 embedded_active = CBool(False)
216 editor = Str(get_default_editor(), config=True)
224 editor = Str(get_default_editor(), config=True)
217 filename = Str("<ipython console>")
225 filename = Str("<ipython console>")
218 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
226 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
219 logstart = CBool(False, config=True)
227 logstart = CBool(False, config=True)
220 logfile = Str('', config=True)
228 logfile = Str('', config=True)
221 logappend = Str('', config=True)
229 logappend = Str('', config=True)
222 object_info_string_level = Enum((0,1,2), default_value=0,
230 object_info_string_level = Enum((0,1,2), default_value=0,
223 config=True)
231 config=True)
224 pager = Str('less', config=True)
232 pager = Str('less', config=True)
225 pdb = CBool(False, config=True)
233 pdb = CBool(False, config=True)
226 pprint = CBool(True, config=True)
234 pprint = CBool(True, config=True)
227 profile = Str('', config=True)
235 profile = Str('', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
236 prompt_in1 = Str('In [\\#]: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
237 prompt_in2 = Str(' .\\D.: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
238 prompt_out = Str('Out[\\#]: ', config=True)
231 prompts_pad_left = CBool(True, config=True)
239 prompts_pad_left = CBool(True, config=True)
232 quiet = CBool(False, config=True)
240 quiet = CBool(False, config=True)
233
241
234 readline_use = CBool(True, config=True)
242 readline_use = CBool(True, config=True)
235 readline_merge_completions = CBool(True, config=True)
243 readline_merge_completions = CBool(True, config=True)
236 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
244 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
237 readline_remove_delims = Str('-/~', config=True)
245 readline_remove_delims = Str('-/~', config=True)
238 readline_parse_and_bind = List([
246 readline_parse_and_bind = List([
239 'tab: complete',
247 'tab: complete',
240 '"\C-l": possible-completions',
248 '"\C-l": possible-completions',
241 'set show-all-if-ambiguous on',
249 'set show-all-if-ambiguous on',
242 '"\C-o": tab-insert',
250 '"\C-o": tab-insert',
243 '"\M-i": " "',
251 '"\M-i": " "',
244 '"\M-o": "\d\d\d\d"',
252 '"\M-o": "\d\d\d\d"',
245 '"\M-I": "\d\d\d\d"',
253 '"\M-I": "\d\d\d\d"',
246 '"\C-r": reverse-search-history',
254 '"\C-r": reverse-search-history',
247 '"\C-s": forward-search-history',
255 '"\C-s": forward-search-history',
248 '"\C-p": history-search-backward',
256 '"\C-p": history-search-backward',
249 '"\C-n": history-search-forward',
257 '"\C-n": history-search-forward',
250 '"\e[A": history-search-backward',
258 '"\e[A": history-search-backward',
251 '"\e[B": history-search-forward',
259 '"\e[B": history-search-forward',
252 '"\C-k": kill-line',
260 '"\C-k": kill-line',
253 '"\C-u": unix-line-discard',
261 '"\C-u": unix-line-discard',
254 ], allow_none=False, config=True)
262 ], allow_none=False, config=True)
255
263
256 screen_length = Int(0, config=True)
264 screen_length = Int(0, config=True)
257
265
258 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
266 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
259 separate_in = SeparateStr('\n', config=True)
267 separate_in = SeparateStr('\n', config=True)
260 separate_out = SeparateStr('', config=True)
268 separate_out = SeparateStr('', config=True)
261 separate_out2 = SeparateStr('', config=True)
269 separate_out2 = SeparateStr('', config=True)
262
270
263 system_header = Str('IPython system call: ', config=True)
271 system_header = Str('IPython system call: ', config=True)
264 system_verbose = CBool(False, config=True)
272 system_verbose = CBool(False, config=True)
265 term_title = CBool(False, config=True)
273 term_title = CBool(False, config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
274 wildcards_case_sensitive = CBool(True, config=True)
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
275 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
268 default_value='Context', config=True)
276 default_value='Context', config=True)
269
277
270 autoexec = List(allow_none=False)
278 autoexec = List(allow_none=False)
271
279
272 # class attribute to indicate whether the class supports threads or not.
280 # class attribute to indicate whether the class supports threads or not.
273 # Subclasses with thread support should override this as needed.
281 # Subclasses with thread support should override this as needed.
274 isthreaded = False
282 isthreaded = False
275
283
276 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
284 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
277 user_ns=None, user_global_ns=None,
285 user_ns=None, user_global_ns=None,
278 banner1=None, banner2=None, display_banner=None,
286 banner1=None, banner2=None, display_banner=None,
279 custom_exceptions=((),None)):
287 custom_exceptions=((),None)):
280
288
281 # This is where traitlets with a config_key argument are updated
289 # This is where traitlets with a config_key argument are updated
282 # from the values on config.
290 # from the values on config.
283 super(InteractiveShell, self).__init__(parent, config=config)
291 super(InteractiveShell, self).__init__(parent, config=config)
284
292
285 # These are relatively independent and stateless
293 # These are relatively independent and stateless
286 self.init_ipython_dir(ipython_dir)
294 self.init_ipython_dir(ipython_dir)
287 self.init_instance_attrs()
295 self.init_instance_attrs()
288 self.init_term_title()
296 self.init_term_title()
289 self.init_usage(usage)
297 self.init_usage(usage)
290 self.init_banner(banner1, banner2, display_banner)
298 self.init_banner(banner1, banner2, display_banner)
291
299
292 # Create namespaces (user_ns, user_global_ns, etc.)
300 # Create namespaces (user_ns, user_global_ns, etc.)
293 self.init_create_namespaces(user_ns, user_global_ns)
301 self.init_create_namespaces(user_ns, user_global_ns)
294 # This has to be done after init_create_namespaces because it uses
302 # This has to be done after init_create_namespaces because it uses
295 # something in self.user_ns, but before init_sys_modules, which
303 # something in self.user_ns, but before init_sys_modules, which
296 # is the first thing to modify sys.
304 # is the first thing to modify sys.
297 self.save_sys_module_state()
305 self.save_sys_module_state()
298 self.init_sys_modules()
306 self.init_sys_modules()
299
307
300 self.init_history()
308 self.init_history()
301 self.init_encoding()
309 self.init_encoding()
302 self.init_prefilter()
310 self.init_prefilter()
303
311
304 Magic.__init__(self, self)
312 Magic.__init__(self, self)
305
313
306 self.init_syntax_highlighting()
314 self.init_syntax_highlighting()
307 self.init_hooks()
315 self.init_hooks()
308 self.init_pushd_popd_magic()
316 self.init_pushd_popd_magic()
309 self.init_traceback_handlers(custom_exceptions)
317 self.init_traceback_handlers(custom_exceptions)
310 self.init_user_ns()
318 self.init_user_ns()
311 self.init_logger()
319 self.init_logger()
312 self.init_alias()
320 self.init_alias()
313 self.init_builtins()
321 self.init_builtins()
314
322
315 # pre_config_initialization
323 # pre_config_initialization
316 self.init_shadow_hist()
324 self.init_shadow_hist()
317
325
318 # The next section should contain averything that was in ipmaker.
326 # The next section should contain averything that was in ipmaker.
319 self.init_logstart()
327 self.init_logstart()
320
328
321 # The following was in post_config_initialization
329 # The following was in post_config_initialization
322 self.init_inspector()
330 self.init_inspector()
323 self.init_readline()
331 self.init_readline()
324 self.init_prompts()
332 self.init_prompts()
325 self.init_displayhook()
333 self.init_displayhook()
326 self.init_reload_doctest()
334 self.init_reload_doctest()
327 self.init_magics()
335 self.init_magics()
328 self.init_pdb()
336 self.init_pdb()
329 self.hooks.late_startup_hook()
337 self.hooks.late_startup_hook()
330
338
331 def get_ipython(self):
339 def get_ipython(self):
340 """Return the currently running IPython instance."""
332 return self
341 return self
333
342
334 #-------------------------------------------------------------------------
343 #-------------------------------------------------------------------------
335 # Traitlet changed handlers
344 # Traitlet changed handlers
336 #-------------------------------------------------------------------------
345 #-------------------------------------------------------------------------
337
346
338 def _banner1_changed(self):
347 def _banner1_changed(self):
339 self.compute_banner()
348 self.compute_banner()
340
349
341 def _banner2_changed(self):
350 def _banner2_changed(self):
342 self.compute_banner()
351 self.compute_banner()
343
352
344 def _ipython_dir_changed(self, name, new):
353 def _ipython_dir_changed(self, name, new):
345 if not os.path.isdir(new):
354 if not os.path.isdir(new):
346 os.makedirs(new, mode = 0777)
355 os.makedirs(new, mode = 0777)
347 if not os.path.isdir(self.ipython_extension_dir):
356 if not os.path.isdir(self.ipython_extension_dir):
348 os.makedirs(self.ipython_extension_dir, mode = 0777)
357 os.makedirs(self.ipython_extension_dir, mode = 0777)
349
358
350 @property
359 @property
351 def ipython_extension_dir(self):
360 def ipython_extension_dir(self):
352 return os.path.join(self.ipython_dir, 'extensions')
361 return os.path.join(self.ipython_dir, 'extensions')
353
362
354 @property
363 @property
355 def usable_screen_length(self):
364 def usable_screen_length(self):
356 if self.screen_length == 0:
365 if self.screen_length == 0:
357 return 0
366 return 0
358 else:
367 else:
359 num_lines_bot = self.separate_in.count('\n')+1
368 num_lines_bot = self.separate_in.count('\n')+1
360 return self.screen_length - num_lines_bot
369 return self.screen_length - num_lines_bot
361
370
362 def _term_title_changed(self, name, new_value):
371 def _term_title_changed(self, name, new_value):
363 self.init_term_title()
372 self.init_term_title()
364
373
365 def set_autoindent(self,value=None):
374 def set_autoindent(self,value=None):
366 """Set the autoindent flag, checking for readline support.
375 """Set the autoindent flag, checking for readline support.
367
376
368 If called with no arguments, it acts as a toggle."""
377 If called with no arguments, it acts as a toggle."""
369
378
370 if not self.has_readline:
379 if not self.has_readline:
371 if os.name == 'posix':
380 if os.name == 'posix':
372 warn("The auto-indent feature requires the readline library")
381 warn("The auto-indent feature requires the readline library")
373 self.autoindent = 0
382 self.autoindent = 0
374 return
383 return
375 if value is None:
384 if value is None:
376 self.autoindent = not self.autoindent
385 self.autoindent = not self.autoindent
377 else:
386 else:
378 self.autoindent = value
387 self.autoindent = value
379
388
380 #-------------------------------------------------------------------------
389 #-------------------------------------------------------------------------
381 # init_* methods called by __init__
390 # init_* methods called by __init__
382 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
383
392
384 def init_ipython_dir(self, ipython_dir):
393 def init_ipython_dir(self, ipython_dir):
385 if ipython_dir is not None:
394 if ipython_dir is not None:
386 self.ipython_dir = ipython_dir
395 self.ipython_dir = ipython_dir
387 self.config.Global.ipython_dir = self.ipython_dir
396 self.config.Global.ipython_dir = self.ipython_dir
388 return
397 return
389
398
390 if hasattr(self.config.Global, 'ipython_dir'):
399 if hasattr(self.config.Global, 'ipython_dir'):
391 self.ipython_dir = self.config.Global.ipython_dir
400 self.ipython_dir = self.config.Global.ipython_dir
392 else:
401 else:
393 self.ipython_dir = get_ipython_dir()
402 self.ipython_dir = get_ipython_dir()
394
403
395 # All children can just read this
404 # All children can just read this
396 self.config.Global.ipython_dir = self.ipython_dir
405 self.config.Global.ipython_dir = self.ipython_dir
397
406
398 def init_instance_attrs(self):
407 def init_instance_attrs(self):
399 self.jobs = BackgroundJobManager()
408 self.jobs = BackgroundJobManager()
400 self.more = False
409 self.more = False
401
410
402 # command compiler
411 # command compiler
403 self.compile = codeop.CommandCompiler()
412 self.compile = codeop.CommandCompiler()
404
413
405 # User input buffer
414 # User input buffer
406 self.buffer = []
415 self.buffer = []
407
416
408 # Make an empty namespace, which extension writers can rely on both
417 # Make an empty namespace, which extension writers can rely on both
409 # existing and NEVER being used by ipython itself. This gives them a
418 # existing and NEVER being used by ipython itself. This gives them a
410 # convenient location for storing additional information and state
419 # convenient location for storing additional information and state
411 # their extensions may require, without fear of collisions with other
420 # their extensions may require, without fear of collisions with other
412 # ipython names that may develop later.
421 # ipython names that may develop later.
413 self.meta = Struct()
422 self.meta = Struct()
414
423
415 # Object variable to store code object waiting execution. This is
424 # Object variable to store code object waiting execution. This is
416 # used mainly by the multithreaded shells, but it can come in handy in
425 # used mainly by the multithreaded shells, but it can come in handy in
417 # other situations. No need to use a Queue here, since it's a single
426 # other situations. No need to use a Queue here, since it's a single
418 # item which gets cleared once run.
427 # item which gets cleared once run.
419 self.code_to_run = None
428 self.code_to_run = None
420
429
421 # Flag to mark unconditional exit
430 # Flag to mark unconditional exit
422 self.exit_now = False
431 self.exit_now = False
423
432
424 # Temporary files used for various purposes. Deleted at exit.
433 # Temporary files used for various purposes. Deleted at exit.
425 self.tempfiles = []
434 self.tempfiles = []
426
435
427 # Keep track of readline usage (later set by init_readline)
436 # Keep track of readline usage (later set by init_readline)
428 self.has_readline = False
437 self.has_readline = False
429
438
430 # keep track of where we started running (mainly for crash post-mortem)
439 # keep track of where we started running (mainly for crash post-mortem)
431 # This is not being used anywhere currently.
440 # This is not being used anywhere currently.
432 self.starting_dir = os.getcwd()
441 self.starting_dir = os.getcwd()
433
442
434 # Indentation management
443 # Indentation management
435 self.indent_current_nsp = 0
444 self.indent_current_nsp = 0
436
445
437 def init_term_title(self):
446 def init_term_title(self):
438 # Enable or disable the terminal title.
447 # Enable or disable the terminal title.
439 if self.term_title:
448 if self.term_title:
440 toggle_set_term_title(True)
449 toggle_set_term_title(True)
441 set_term_title('IPython: ' + abbrev_cwd())
450 set_term_title('IPython: ' + abbrev_cwd())
442 else:
451 else:
443 toggle_set_term_title(False)
452 toggle_set_term_title(False)
444
453
445 def init_usage(self, usage=None):
454 def init_usage(self, usage=None):
446 if usage is None:
455 if usage is None:
447 self.usage = interactive_usage
456 self.usage = interactive_usage
448 else:
457 else:
449 self.usage = usage
458 self.usage = usage
450
459
451 def init_encoding(self):
460 def init_encoding(self):
452 # Get system encoding at startup time. Certain terminals (like Emacs
461 # Get system encoding at startup time. Certain terminals (like Emacs
453 # under Win32 have it set to None, and we need to have a known valid
462 # under Win32 have it set to None, and we need to have a known valid
454 # encoding to use in the raw_input() method
463 # encoding to use in the raw_input() method
455 try:
464 try:
456 self.stdin_encoding = sys.stdin.encoding or 'ascii'
465 self.stdin_encoding = sys.stdin.encoding or 'ascii'
457 except AttributeError:
466 except AttributeError:
458 self.stdin_encoding = 'ascii'
467 self.stdin_encoding = 'ascii'
459
468
460 def init_syntax_highlighting(self):
469 def init_syntax_highlighting(self):
461 # Python source parser/formatter for syntax highlighting
470 # Python source parser/formatter for syntax highlighting
462 pyformat = PyColorize.Parser().format
471 pyformat = PyColorize.Parser().format
463 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
472 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
464
473
465 def init_pushd_popd_magic(self):
474 def init_pushd_popd_magic(self):
466 # for pushd/popd management
475 # for pushd/popd management
467 try:
476 try:
468 self.home_dir = get_home_dir()
477 self.home_dir = get_home_dir()
469 except HomeDirError, msg:
478 except HomeDirError, msg:
470 fatal(msg)
479 fatal(msg)
471
480
472 self.dir_stack = []
481 self.dir_stack = []
473
482
474 def init_logger(self):
483 def init_logger(self):
475 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
484 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
476 # local shortcut, this is used a LOT
485 # local shortcut, this is used a LOT
477 self.log = self.logger.log
486 self.log = self.logger.log
478
487
479 def init_logstart(self):
488 def init_logstart(self):
480 if self.logappend:
489 if self.logappend:
481 self.magic_logstart(self.logappend + ' append')
490 self.magic_logstart(self.logappend + ' append')
482 elif self.logfile:
491 elif self.logfile:
483 self.magic_logstart(self.logfile)
492 self.magic_logstart(self.logfile)
484 elif self.logstart:
493 elif self.logstart:
485 self.magic_logstart()
494 self.magic_logstart()
486
495
487 def init_builtins(self):
496 def init_builtins(self):
488 self.builtin_trap = BuiltinTrap(self)
497 self.builtin_trap = BuiltinTrap(self)
489
498
490 def init_inspector(self):
499 def init_inspector(self):
491 # Object inspector
500 # Object inspector
492 self.inspector = oinspect.Inspector(oinspect.InspectColors,
501 self.inspector = oinspect.Inspector(oinspect.InspectColors,
493 PyColorize.ANSICodeColors,
502 PyColorize.ANSICodeColors,
494 'NoColor',
503 'NoColor',
495 self.object_info_string_level)
504 self.object_info_string_level)
496
505
497 def init_prompts(self):
506 def init_prompts(self):
498 # Initialize cache, set in/out prompts and printing system
507 # Initialize cache, set in/out prompts and printing system
499 self.outputcache = CachedOutput(self,
508 self.outputcache = CachedOutput(self,
500 self.cache_size,
509 self.cache_size,
501 self.pprint,
510 self.pprint,
502 input_sep = self.separate_in,
511 input_sep = self.separate_in,
503 output_sep = self.separate_out,
512 output_sep = self.separate_out,
504 output_sep2 = self.separate_out2,
513 output_sep2 = self.separate_out2,
505 ps1 = self.prompt_in1,
514 ps1 = self.prompt_in1,
506 ps2 = self.prompt_in2,
515 ps2 = self.prompt_in2,
507 ps_out = self.prompt_out,
516 ps_out = self.prompt_out,
508 pad_left = self.prompts_pad_left)
517 pad_left = self.prompts_pad_left)
509
518
510 # user may have over-ridden the default print hook:
519 # user may have over-ridden the default print hook:
511 try:
520 try:
512 self.outputcache.__class__.display = self.hooks.display
521 self.outputcache.__class__.display = self.hooks.display
513 except AttributeError:
522 except AttributeError:
514 pass
523 pass
515
524
516 def init_displayhook(self):
525 def init_displayhook(self):
517 self.display_trap = DisplayTrap(self, self.outputcache)
526 self.display_trap = DisplayTrap(self, self.outputcache)
518
527
519 def init_reload_doctest(self):
528 def init_reload_doctest(self):
520 # Do a proper resetting of doctest, including the necessary displayhook
529 # Do a proper resetting of doctest, including the necessary displayhook
521 # monkeypatching
530 # monkeypatching
522 try:
531 try:
523 doctest_reload()
532 doctest_reload()
524 except ImportError:
533 except ImportError:
525 warn("doctest module does not exist.")
534 warn("doctest module does not exist.")
526
535
527 #-------------------------------------------------------------------------
536 #-------------------------------------------------------------------------
528 # Things related to the banner
537 # Things related to the banner
529 #-------------------------------------------------------------------------
538 #-------------------------------------------------------------------------
530
539
531 def init_banner(self, banner1, banner2, display_banner):
540 def init_banner(self, banner1, banner2, display_banner):
532 if banner1 is not None:
541 if banner1 is not None:
533 self.banner1 = banner1
542 self.banner1 = banner1
534 if banner2 is not None:
543 if banner2 is not None:
535 self.banner2 = banner2
544 self.banner2 = banner2
536 if display_banner is not None:
545 if display_banner is not None:
537 self.display_banner = display_banner
546 self.display_banner = display_banner
538 self.compute_banner()
547 self.compute_banner()
539
548
540 def show_banner(self, banner=None):
549 def show_banner(self, banner=None):
541 if banner is None:
550 if banner is None:
542 banner = self.banner
551 banner = self.banner
543 self.write(banner)
552 self.write(banner)
544
553
545 def compute_banner(self):
554 def compute_banner(self):
546 self.banner = self.banner1 + '\n'
555 self.banner = self.banner1 + '\n'
547 if self.profile:
556 if self.profile:
548 self.banner += '\nIPython profile: %s\n' % self.profile
557 self.banner += '\nIPython profile: %s\n' % self.profile
549 if self.banner2:
558 if self.banner2:
550 self.banner += '\n' + self.banner2 + '\n'
559 self.banner += '\n' + self.banner2 + '\n'
551
560
552 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
553 # Things related to injections into the sys module
562 # Things related to injections into the sys module
554 #-------------------------------------------------------------------------
563 #-------------------------------------------------------------------------
555
564
556 def save_sys_module_state(self):
565 def save_sys_module_state(self):
557 """Save the state of hooks in the sys module.
566 """Save the state of hooks in the sys module.
558
567
559 This has to be called after self.user_ns is created.
568 This has to be called after self.user_ns is created.
560 """
569 """
561 self._orig_sys_module_state = {}
570 self._orig_sys_module_state = {}
562 self._orig_sys_module_state['stdin'] = sys.stdin
571 self._orig_sys_module_state['stdin'] = sys.stdin
563 self._orig_sys_module_state['stdout'] = sys.stdout
572 self._orig_sys_module_state['stdout'] = sys.stdout
564 self._orig_sys_module_state['stderr'] = sys.stderr
573 self._orig_sys_module_state['stderr'] = sys.stderr
565 self._orig_sys_module_state['excepthook'] = sys.excepthook
574 self._orig_sys_module_state['excepthook'] = sys.excepthook
566 try:
575 try:
567 self._orig_sys_modules_main_name = self.user_ns['__name__']
576 self._orig_sys_modules_main_name = self.user_ns['__name__']
568 except KeyError:
577 except KeyError:
569 pass
578 pass
570
579
571 def restore_sys_module_state(self):
580 def restore_sys_module_state(self):
572 """Restore the state of the sys module."""
581 """Restore the state of the sys module."""
573 try:
582 try:
574 for k, v in self._orig_sys_module_state.items():
583 for k, v in self._orig_sys_module_state.items():
575 setattr(sys, k, v)
584 setattr(sys, k, v)
576 except AttributeError:
585 except AttributeError:
577 pass
586 pass
578 try:
587 try:
579 delattr(sys, 'ipcompleter')
588 delattr(sys, 'ipcompleter')
580 except AttributeError:
589 except AttributeError:
581 pass
590 pass
582 # Reset what what done in self.init_sys_modules
591 # Reset what what done in self.init_sys_modules
583 try:
592 try:
584 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
593 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
585 except (AttributeError, KeyError):
594 except (AttributeError, KeyError):
586 pass
595 pass
587
596
588 #-------------------------------------------------------------------------
597 #-------------------------------------------------------------------------
589 # Things related to hooks
598 # Things related to hooks
590 #-------------------------------------------------------------------------
599 #-------------------------------------------------------------------------
591
600
592 def init_hooks(self):
601 def init_hooks(self):
593 # hooks holds pointers used for user-side customizations
602 # hooks holds pointers used for user-side customizations
594 self.hooks = Struct()
603 self.hooks = Struct()
595
604
596 self.strdispatchers = {}
605 self.strdispatchers = {}
597
606
598 # Set all default hooks, defined in the IPython.hooks module.
607 # Set all default hooks, defined in the IPython.hooks module.
599 import IPython.core.hooks
600 hooks = IPython.core.hooks
608 hooks = IPython.core.hooks
601 for hook_name in hooks.__all__:
609 for hook_name in hooks.__all__:
602 # default hooks have priority 100, i.e. low; user hooks should have
610 # default hooks have priority 100, i.e. low; user hooks should have
603 # 0-100 priority
611 # 0-100 priority
604 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
612 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
605
613
606 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
614 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
607 """set_hook(name,hook) -> sets an internal IPython hook.
615 """set_hook(name,hook) -> sets an internal IPython hook.
608
616
609 IPython exposes some of its internal API as user-modifiable hooks. By
617 IPython exposes some of its internal API as user-modifiable hooks. By
610 adding your function to one of these hooks, you can modify IPython's
618 adding your function to one of these hooks, you can modify IPython's
611 behavior to call at runtime your own routines."""
619 behavior to call at runtime your own routines."""
612
620
613 # At some point in the future, this should validate the hook before it
621 # At some point in the future, this should validate the hook before it
614 # accepts it. Probably at least check that the hook takes the number
622 # accepts it. Probably at least check that the hook takes the number
615 # of args it's supposed to.
623 # of args it's supposed to.
616
624
617 f = new.instancemethod(hook,self,self.__class__)
625 f = new.instancemethod(hook,self,self.__class__)
618
626
619 # check if the hook is for strdispatcher first
627 # check if the hook is for strdispatcher first
620 if str_key is not None:
628 if str_key is not None:
621 sdp = self.strdispatchers.get(name, StrDispatch())
629 sdp = self.strdispatchers.get(name, StrDispatch())
622 sdp.add_s(str_key, f, priority )
630 sdp.add_s(str_key, f, priority )
623 self.strdispatchers[name] = sdp
631 self.strdispatchers[name] = sdp
624 return
632 return
625 if re_key is not None:
633 if re_key is not None:
626 sdp = self.strdispatchers.get(name, StrDispatch())
634 sdp = self.strdispatchers.get(name, StrDispatch())
627 sdp.add_re(re.compile(re_key), f, priority )
635 sdp.add_re(re.compile(re_key), f, priority )
628 self.strdispatchers[name] = sdp
636 self.strdispatchers[name] = sdp
629 return
637 return
630
638
631 dp = getattr(self.hooks, name, None)
639 dp = getattr(self.hooks, name, None)
632 if name not in IPython.core.hooks.__all__:
640 if name not in IPython.core.hooks.__all__:
633 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
641 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
634 if not dp:
642 if not dp:
635 dp = IPython.core.hooks.CommandChainDispatcher()
643 dp = IPython.core.hooks.CommandChainDispatcher()
636
644
637 try:
645 try:
638 dp.add(f,priority)
646 dp.add(f,priority)
639 except AttributeError:
647 except AttributeError:
640 # it was not commandchain, plain old func - replace
648 # it was not commandchain, plain old func - replace
641 dp = f
649 dp = f
642
650
643 setattr(self.hooks,name, dp)
651 setattr(self.hooks,name, dp)
644
652
645 #-------------------------------------------------------------------------
653 #-------------------------------------------------------------------------
646 # Things related to the "main" module
654 # Things related to the "main" module
647 #-------------------------------------------------------------------------
655 #-------------------------------------------------------------------------
648
656
649 def new_main_mod(self,ns=None):
657 def new_main_mod(self,ns=None):
650 """Return a new 'main' module object for user code execution.
658 """Return a new 'main' module object for user code execution.
651 """
659 """
652 main_mod = self._user_main_module
660 main_mod = self._user_main_module
653 init_fakemod_dict(main_mod,ns)
661 init_fakemod_dict(main_mod,ns)
654 return main_mod
662 return main_mod
655
663
656 def cache_main_mod(self,ns,fname):
664 def cache_main_mod(self,ns,fname):
657 """Cache a main module's namespace.
665 """Cache a main module's namespace.
658
666
659 When scripts are executed via %run, we must keep a reference to the
667 When scripts are executed via %run, we must keep a reference to the
660 namespace of their __main__ module (a FakeModule instance) around so
668 namespace of their __main__ module (a FakeModule instance) around so
661 that Python doesn't clear it, rendering objects defined therein
669 that Python doesn't clear it, rendering objects defined therein
662 useless.
670 useless.
663
671
664 This method keeps said reference in a private dict, keyed by the
672 This method keeps said reference in a private dict, keyed by the
665 absolute path of the module object (which corresponds to the script
673 absolute path of the module object (which corresponds to the script
666 path). This way, for multiple executions of the same script we only
674 path). This way, for multiple executions of the same script we only
667 keep one copy of the namespace (the last one), thus preventing memory
675 keep one copy of the namespace (the last one), thus preventing memory
668 leaks from old references while allowing the objects from the last
676 leaks from old references while allowing the objects from the last
669 execution to be accessible.
677 execution to be accessible.
670
678
671 Note: we can not allow the actual FakeModule instances to be deleted,
679 Note: we can not allow the actual FakeModule instances to be deleted,
672 because of how Python tears down modules (it hard-sets all their
680 because of how Python tears down modules (it hard-sets all their
673 references to None without regard for reference counts). This method
681 references to None without regard for reference counts). This method
674 must therefore make a *copy* of the given namespace, to allow the
682 must therefore make a *copy* of the given namespace, to allow the
675 original module's __dict__ to be cleared and reused.
683 original module's __dict__ to be cleared and reused.
676
684
677
685
678 Parameters
686 Parameters
679 ----------
687 ----------
680 ns : a namespace (a dict, typically)
688 ns : a namespace (a dict, typically)
681
689
682 fname : str
690 fname : str
683 Filename associated with the namespace.
691 Filename associated with the namespace.
684
692
685 Examples
693 Examples
686 --------
694 --------
687
695
688 In [10]: import IPython
696 In [10]: import IPython
689
697
690 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
698 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
691
699
692 In [12]: IPython.__file__ in _ip._main_ns_cache
700 In [12]: IPython.__file__ in _ip._main_ns_cache
693 Out[12]: True
701 Out[12]: True
694 """
702 """
695 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
703 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
696
704
697 def clear_main_mod_cache(self):
705 def clear_main_mod_cache(self):
698 """Clear the cache of main modules.
706 """Clear the cache of main modules.
699
707
700 Mainly for use by utilities like %reset.
708 Mainly for use by utilities like %reset.
701
709
702 Examples
710 Examples
703 --------
711 --------
704
712
705 In [15]: import IPython
713 In [15]: import IPython
706
714
707 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
715 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
708
716
709 In [17]: len(_ip._main_ns_cache) > 0
717 In [17]: len(_ip._main_ns_cache) > 0
710 Out[17]: True
718 Out[17]: True
711
719
712 In [18]: _ip.clear_main_mod_cache()
720 In [18]: _ip.clear_main_mod_cache()
713
721
714 In [19]: len(_ip._main_ns_cache) == 0
722 In [19]: len(_ip._main_ns_cache) == 0
715 Out[19]: True
723 Out[19]: True
716 """
724 """
717 self._main_ns_cache.clear()
725 self._main_ns_cache.clear()
718
726
719 #-------------------------------------------------------------------------
727 #-------------------------------------------------------------------------
720 # Things related to debugging
728 # Things related to debugging
721 #-------------------------------------------------------------------------
729 #-------------------------------------------------------------------------
722
730
723 def init_pdb(self):
731 def init_pdb(self):
724 # Set calling of pdb on exceptions
732 # Set calling of pdb on exceptions
725 # self.call_pdb is a property
733 # self.call_pdb is a property
726 self.call_pdb = self.pdb
734 self.call_pdb = self.pdb
727
735
728 def _get_call_pdb(self):
736 def _get_call_pdb(self):
729 return self._call_pdb
737 return self._call_pdb
730
738
731 def _set_call_pdb(self,val):
739 def _set_call_pdb(self,val):
732
740
733 if val not in (0,1,False,True):
741 if val not in (0,1,False,True):
734 raise ValueError,'new call_pdb value must be boolean'
742 raise ValueError,'new call_pdb value must be boolean'
735
743
736 # store value in instance
744 # store value in instance
737 self._call_pdb = val
745 self._call_pdb = val
738
746
739 # notify the actual exception handlers
747 # notify the actual exception handlers
740 self.InteractiveTB.call_pdb = val
748 self.InteractiveTB.call_pdb = val
741 if self.isthreaded:
749 if self.isthreaded:
742 try:
750 try:
743 self.sys_excepthook.call_pdb = val
751 self.sys_excepthook.call_pdb = val
744 except:
752 except:
745 warn('Failed to activate pdb for threaded exception handler')
753 warn('Failed to activate pdb for threaded exception handler')
746
754
747 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
755 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
748 'Control auto-activation of pdb at exceptions')
756 'Control auto-activation of pdb at exceptions')
749
757
750 def debugger(self,force=False):
758 def debugger(self,force=False):
751 """Call the pydb/pdb debugger.
759 """Call the pydb/pdb debugger.
752
760
753 Keywords:
761 Keywords:
754
762
755 - force(False): by default, this routine checks the instance call_pdb
763 - force(False): by default, this routine checks the instance call_pdb
756 flag and does not actually invoke the debugger if the flag is false.
764 flag and does not actually invoke the debugger if the flag is false.
757 The 'force' option forces the debugger to activate even if the flag
765 The 'force' option forces the debugger to activate even if the flag
758 is false.
766 is false.
759 """
767 """
760
768
761 if not (force or self.call_pdb):
769 if not (force or self.call_pdb):
762 return
770 return
763
771
764 if not hasattr(sys,'last_traceback'):
772 if not hasattr(sys,'last_traceback'):
765 error('No traceback has been produced, nothing to debug.')
773 error('No traceback has been produced, nothing to debug.')
766 return
774 return
767
775
768 # use pydb if available
776 # use pydb if available
769 if debugger.has_pydb:
777 if debugger.has_pydb:
770 from pydb import pm
778 from pydb import pm
771 else:
779 else:
772 # fallback to our internal debugger
780 # fallback to our internal debugger
773 pm = lambda : self.InteractiveTB.debugger(force=True)
781 pm = lambda : self.InteractiveTB.debugger(force=True)
774 self.history_saving_wrapper(pm)()
782 self.history_saving_wrapper(pm)()
775
783
776 #-------------------------------------------------------------------------
784 #-------------------------------------------------------------------------
777 # Things related to IPython's various namespaces
785 # Things related to IPython's various namespaces
778 #-------------------------------------------------------------------------
786 #-------------------------------------------------------------------------
779
787
780 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
788 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
781 # Create the namespace where the user will operate. user_ns is
789 # Create the namespace where the user will operate. user_ns is
782 # normally the only one used, and it is passed to the exec calls as
790 # normally the only one used, and it is passed to the exec calls as
783 # the locals argument. But we do carry a user_global_ns namespace
791 # the locals argument. But we do carry a user_global_ns namespace
784 # given as the exec 'globals' argument, This is useful in embedding
792 # given as the exec 'globals' argument, This is useful in embedding
785 # situations where the ipython shell opens in a context where the
793 # situations where the ipython shell opens in a context where the
786 # distinction between locals and globals is meaningful. For
794 # distinction between locals and globals is meaningful. For
787 # non-embedded contexts, it is just the same object as the user_ns dict.
795 # non-embedded contexts, it is just the same object as the user_ns dict.
788
796
789 # FIXME. For some strange reason, __builtins__ is showing up at user
797 # FIXME. For some strange reason, __builtins__ is showing up at user
790 # level as a dict instead of a module. This is a manual fix, but I
798 # level as a dict instead of a module. This is a manual fix, but I
791 # should really track down where the problem is coming from. Alex
799 # should really track down where the problem is coming from. Alex
792 # Schmolck reported this problem first.
800 # Schmolck reported this problem first.
793
801
794 # A useful post by Alex Martelli on this topic:
802 # A useful post by Alex Martelli on this topic:
795 # Re: inconsistent value from __builtins__
803 # Re: inconsistent value from __builtins__
796 # Von: Alex Martelli <aleaxit@yahoo.com>
804 # Von: Alex Martelli <aleaxit@yahoo.com>
797 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
805 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
798 # Gruppen: comp.lang.python
806 # Gruppen: comp.lang.python
799
807
800 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
808 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
801 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
809 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
802 # > <type 'dict'>
810 # > <type 'dict'>
803 # > >>> print type(__builtins__)
811 # > >>> print type(__builtins__)
804 # > <type 'module'>
812 # > <type 'module'>
805 # > Is this difference in return value intentional?
813 # > Is this difference in return value intentional?
806
814
807 # Well, it's documented that '__builtins__' can be either a dictionary
815 # Well, it's documented that '__builtins__' can be either a dictionary
808 # or a module, and it's been that way for a long time. Whether it's
816 # or a module, and it's been that way for a long time. Whether it's
809 # intentional (or sensible), I don't know. In any case, the idea is
817 # intentional (or sensible), I don't know. In any case, the idea is
810 # that if you need to access the built-in namespace directly, you
818 # that if you need to access the built-in namespace directly, you
811 # should start with "import __builtin__" (note, no 's') which will
819 # should start with "import __builtin__" (note, no 's') which will
812 # definitely give you a module. Yeah, it's somewhat confusing:-(.
820 # definitely give you a module. Yeah, it's somewhat confusing:-(.
813
821
814 # These routines return properly built dicts as needed by the rest of
822 # These routines return properly built dicts as needed by the rest of
815 # the code, and can also be used by extension writers to generate
823 # the code, and can also be used by extension writers to generate
816 # properly initialized namespaces.
824 # properly initialized namespaces.
817 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
825 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
818 user_global_ns)
819
826
820 # Assign namespaces
827 # Assign namespaces
821 # This is the namespace where all normal user variables live
828 # This is the namespace where all normal user variables live
822 self.user_ns = user_ns
829 self.user_ns = user_ns
823 self.user_global_ns = user_global_ns
830 self.user_global_ns = user_global_ns
824
831
825 # An auxiliary namespace that checks what parts of the user_ns were
832 # An auxiliary namespace that checks what parts of the user_ns were
826 # loaded at startup, so we can list later only variables defined in
833 # loaded at startup, so we can list later only variables defined in
827 # actual interactive use. Since it is always a subset of user_ns, it
834 # actual interactive use. Since it is always a subset of user_ns, it
828 # doesn't need to be seaparately tracked in the ns_table
835 # doesn't need to be separately tracked in the ns_table.
829 self.user_config_ns = {}
836 self.user_ns_hidden = {}
830
837
831 # A namespace to keep track of internal data structures to prevent
838 # A namespace to keep track of internal data structures to prevent
832 # them from cluttering user-visible stuff. Will be updated later
839 # them from cluttering user-visible stuff. Will be updated later
833 self.internal_ns = {}
840 self.internal_ns = {}
834
841
835 # Now that FakeModule produces a real module, we've run into a nasty
842 # Now that FakeModule produces a real module, we've run into a nasty
836 # problem: after script execution (via %run), the module where the user
843 # problem: after script execution (via %run), the module where the user
837 # code ran is deleted. Now that this object is a true module (needed
844 # code ran is deleted. Now that this object is a true module (needed
838 # so docetst and other tools work correctly), the Python module
845 # so docetst and other tools work correctly), the Python module
839 # teardown mechanism runs over it, and sets to None every variable
846 # teardown mechanism runs over it, and sets to None every variable
840 # present in that module. Top-level references to objects from the
847 # present in that module. Top-level references to objects from the
841 # script survive, because the user_ns is updated with them. However,
848 # script survive, because the user_ns is updated with them. However,
842 # calling functions defined in the script that use other things from
849 # calling functions defined in the script that use other things from
843 # the script will fail, because the function's closure had references
850 # the script will fail, because the function's closure had references
844 # to the original objects, which are now all None. So we must protect
851 # to the original objects, which are now all None. So we must protect
845 # these modules from deletion by keeping a cache.
852 # these modules from deletion by keeping a cache.
846 #
853 #
847 # To avoid keeping stale modules around (we only need the one from the
854 # To avoid keeping stale modules around (we only need the one from the
848 # last run), we use a dict keyed with the full path to the script, so
855 # last run), we use a dict keyed with the full path to the script, so
849 # only the last version of the module is held in the cache. Note,
856 # only the last version of the module is held in the cache. Note,
850 # however, that we must cache the module *namespace contents* (their
857 # however, that we must cache the module *namespace contents* (their
851 # __dict__). Because if we try to cache the actual modules, old ones
858 # __dict__). Because if we try to cache the actual modules, old ones
852 # (uncached) could be destroyed while still holding references (such as
859 # (uncached) could be destroyed while still holding references (such as
853 # those held by GUI objects that tend to be long-lived)>
860 # those held by GUI objects that tend to be long-lived)>
854 #
861 #
855 # The %reset command will flush this cache. See the cache_main_mod()
862 # The %reset command will flush this cache. See the cache_main_mod()
856 # and clear_main_mod_cache() methods for details on use.
863 # and clear_main_mod_cache() methods for details on use.
857
864
858 # This is the cache used for 'main' namespaces
865 # This is the cache used for 'main' namespaces
859 self._main_ns_cache = {}
866 self._main_ns_cache = {}
860 # And this is the single instance of FakeModule whose __dict__ we keep
867 # And this is the single instance of FakeModule whose __dict__ we keep
861 # copying and clearing for reuse on each %run
868 # copying and clearing for reuse on each %run
862 self._user_main_module = FakeModule()
869 self._user_main_module = FakeModule()
863
870
864 # A table holding all the namespaces IPython deals with, so that
871 # A table holding all the namespaces IPython deals with, so that
865 # introspection facilities can search easily.
872 # introspection facilities can search easily.
866 self.ns_table = {'user':user_ns,
873 self.ns_table = {'user':user_ns,
867 'user_global':user_global_ns,
874 'user_global':user_global_ns,
868 'internal':self.internal_ns,
875 'internal':self.internal_ns,
869 'builtin':__builtin__.__dict__
876 'builtin':__builtin__.__dict__
870 }
877 }
871
878
872 # Similarly, track all namespaces where references can be held and that
879 # Similarly, track all namespaces where references can be held and that
873 # we can safely clear (so it can NOT include builtin). This one can be
880 # we can safely clear (so it can NOT include builtin). This one can be
874 # a simple list.
881 # a simple list.
875 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
882 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
876 self.internal_ns, self._main_ns_cache ]
883 self.internal_ns, self._main_ns_cache ]
877
884
878 def init_sys_modules(self):
879 # We need to insert into sys.modules something that looks like a
880 # module but which accesses the IPython namespace, for shelve and
881 # pickle to work interactively. Normally they rely on getting
882 # everything out of __main__, but for embedding purposes each IPython
883 # instance has its own private namespace, so we can't go shoving
884 # everything into __main__.
885
886 # note, however, that we should only do this for non-embedded
887 # ipythons, which really mimic the __main__.__dict__ with their own
888 # namespace. Embedded instances, on the other hand, should not do
889 # this because they need to manage the user local/global namespaces
890 # only, but they live within a 'normal' __main__ (meaning, they
891 # shouldn't overtake the execution environment of the script they're
892 # embedded in).
893
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
895
896 try:
897 main_name = self.user_ns['__name__']
898 except KeyError:
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
900 else:
901 sys.modules[main_name] = FakeModule(self.user_ns)
902
903 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
885 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
904 """Return a valid local and global user interactive namespaces.
886 """Return a valid local and global user interactive namespaces.
905
887
906 This builds a dict with the minimal information needed to operate as a
888 This builds a dict with the minimal information needed to operate as a
907 valid IPython user namespace, which you can pass to the various
889 valid IPython user namespace, which you can pass to the various
908 embedding classes in ipython. The default implementation returns the
890 embedding classes in ipython. The default implementation returns the
909 same dict for both the locals and the globals to allow functions to
891 same dict for both the locals and the globals to allow functions to
910 refer to variables in the namespace. Customized implementations can
892 refer to variables in the namespace. Customized implementations can
911 return different dicts. The locals dictionary can actually be anything
893 return different dicts. The locals dictionary can actually be anything
912 following the basic mapping protocol of a dict, but the globals dict
894 following the basic mapping protocol of a dict, but the globals dict
913 must be a true dict, not even a subclass. It is recommended that any
895 must be a true dict, not even a subclass. It is recommended that any
914 custom object for the locals namespace synchronize with the globals
896 custom object for the locals namespace synchronize with the globals
915 dict somehow.
897 dict somehow.
916
898
917 Raises TypeError if the provided globals namespace is not a true dict.
899 Raises TypeError if the provided globals namespace is not a true dict.
918
900
919 :Parameters:
901 Parameters
920 user_ns : dict-like, optional
902 ----------
921 The current user namespace. The items in this namespace should
903 user_ns : dict-like, optional
922 be included in the output. If None, an appropriate blank
904 The current user namespace. The items in this namespace should
923 namespace should be created.
905 be included in the output. If None, an appropriate blank
924 user_global_ns : dict, optional
906 namespace should be created.
925 The current user global namespace. The items in this namespace
907 user_global_ns : dict, optional
926 should be included in the output. If None, an appropriate
908 The current user global namespace. The items in this namespace
927 blank namespace should be created.
909 should be included in the output. If None, an appropriate
928
910 blank namespace should be created.
929 :Returns:
911
930 A tuple pair of dictionary-like object to be used as the local namespace
912 Returns
913 -------
914 A pair of dictionary-like object to be used as the local namespace
931 of the interpreter and a dict to be used as the global namespace.
915 of the interpreter and a dict to be used as the global namespace.
932 """
916 """
933
917
918
919 # We must ensure that __builtin__ (without the final 's') is always
920 # available and pointing to the __builtin__ *module*. For more details:
921 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
922
934 if user_ns is None:
923 if user_ns is None:
935 # Set __name__ to __main__ to better match the behavior of the
924 # Set __name__ to __main__ to better match the behavior of the
936 # normal interpreter.
925 # normal interpreter.
937 user_ns = {'__name__' :'__main__',
926 user_ns = {'__name__' :'__main__',
927 '__builtin__' : __builtin__,
938 '__builtins__' : __builtin__,
928 '__builtins__' : __builtin__,
939 }
929 }
940 else:
930 else:
941 user_ns.setdefault('__name__','__main__')
931 user_ns.setdefault('__name__','__main__')
932 user_ns.setdefault('__builtin__',__builtin__)
942 user_ns.setdefault('__builtins__',__builtin__)
933 user_ns.setdefault('__builtins__',__builtin__)
943
934
944 if user_global_ns is None:
935 if user_global_ns is None:
945 user_global_ns = user_ns
936 user_global_ns = user_ns
946 if type(user_global_ns) is not dict:
937 if type(user_global_ns) is not dict:
947 raise TypeError("user_global_ns must be a true dict; got %r"
938 raise TypeError("user_global_ns must be a true dict; got %r"
948 % type(user_global_ns))
939 % type(user_global_ns))
949
940
950 return user_ns, user_global_ns
941 return user_ns, user_global_ns
951
942
943 def init_sys_modules(self):
944 # We need to insert into sys.modules something that looks like a
945 # module but which accesses the IPython namespace, for shelve and
946 # pickle to work interactively. Normally they rely on getting
947 # everything out of __main__, but for embedding purposes each IPython
948 # instance has its own private namespace, so we can't go shoving
949 # everything into __main__.
950
951 # note, however, that we should only do this for non-embedded
952 # ipythons, which really mimic the __main__.__dict__ with their own
953 # namespace. Embedded instances, on the other hand, should not do
954 # this because they need to manage the user local/global namespaces
955 # only, but they live within a 'normal' __main__ (meaning, they
956 # shouldn't overtake the execution environment of the script they're
957 # embedded in).
958
959 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
960
961 try:
962 main_name = self.user_ns['__name__']
963 except KeyError:
964 raise KeyError('user_ns dictionary MUST have a "__name__" key')
965 else:
966 sys.modules[main_name] = FakeModule(self.user_ns)
967
952 def init_user_ns(self):
968 def init_user_ns(self):
953 """Initialize all user-visible namespaces to their minimum defaults.
969 """Initialize all user-visible namespaces to their minimum defaults.
954
970
955 Certain history lists are also initialized here, as they effectively
971 Certain history lists are also initialized here, as they effectively
956 act as user namespaces.
972 act as user namespaces.
957
973
958 Notes
974 Notes
959 -----
975 -----
960 All data structures here are only filled in, they are NOT reset by this
976 All data structures here are only filled in, they are NOT reset by this
961 method. If they were not empty before, data will simply be added to
977 method. If they were not empty before, data will simply be added to
962 therm.
978 therm.
963 """
979 """
964 # Store myself as the public api!!!
980 # This function works in two parts: first we put a few things in
965 self.user_ns['get_ipython'] = self.get_ipython
981 # user_ns, and we sync that contents into user_ns_hidden so that these
966
982 # initial variables aren't shown by %who. After the sync, we add the
967 # make global variables for user access to the histories
983 # rest of what we *do* want the user to see with %who even on a new
968 self.user_ns['_ih'] = self.input_hist
984 # session (probably nothing, so theye really only see their own stuff)
969 self.user_ns['_oh'] = self.output_hist
985
970 self.user_ns['_dh'] = self.dir_hist
986 # The user dict must *always* have a __builtin__ reference to the
971
987 # Python standard __builtin__ namespace, which must be imported.
972 # user aliases to input and output histories
988 # This is so that certain operations in prompt evaluation can be
973 self.user_ns['In'] = self.input_hist
989 # reliably executed with builtins. Note that we can NOT use
974 self.user_ns['Out'] = self.output_hist
990 # __builtins__ (note the 's'), because that can either be a dict or a
975
991 # module, and can even mutate at runtime, depending on the context
976 self.user_ns['_sh'] = shadowns
992 # (Python makes no guarantees on it). In contrast, __builtin__ is
977
993 # always a module object, though it must be explicitly imported.
994
995 # For more details:
996 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
997 ns = dict(__builtin__ = __builtin__)
998
978 # Put 'help' in the user namespace
999 # Put 'help' in the user namespace
979 try:
1000 try:
980 from site import _Helper
1001 from site import _Helper
981 self.user_ns['help'] = _Helper()
1002 ns['help'] = _Helper()
982 except ImportError:
1003 except ImportError:
983 warn('help() not available - check site.py')
1004 warn('help() not available - check site.py')
984
1005
1006 # make global variables for user access to the histories
1007 ns['_ih'] = self.input_hist
1008 ns['_oh'] = self.output_hist
1009 ns['_dh'] = self.dir_hist
1010
1011 ns['_sh'] = shadowns
1012
1013 # user aliases to input and output histories. These shouldn't show up
1014 # in %who, as they can have very large reprs.
1015 ns['In'] = self.input_hist
1016 ns['Out'] = self.output_hist
1017
1018 # Store myself as the public api!!!
1019 ns['get_ipython'] = self.get_ipython
1020
1021 # Sync what we've added so far to user_ns_hidden so these aren't seen
1022 # by %who
1023 self.user_ns_hidden.update(ns)
1024
1025 # Anything put into ns now would show up in %who. Think twice before
1026 # putting anything here, as we really want %who to show the user their
1027 # stuff, not our variables.
1028
1029 # Finally, update the real user's namespace
1030 self.user_ns.update(ns)
1031
1032
985 def reset(self):
1033 def reset(self):
986 """Clear all internal namespaces.
1034 """Clear all internal namespaces.
987
1035
988 Note that this is much more aggressive than %reset, since it clears
1036 Note that this is much more aggressive than %reset, since it clears
989 fully all namespaces, as well as all input/output lists.
1037 fully all namespaces, as well as all input/output lists.
990 """
1038 """
991 for ns in self.ns_refs_table:
1039 for ns in self.ns_refs_table:
992 ns.clear()
1040 ns.clear()
993
1041
994 self.alias_manager.clear_aliases()
1042 self.alias_manager.clear_aliases()
995
1043
996 # Clear input and output histories
1044 # Clear input and output histories
997 self.input_hist[:] = []
1045 self.input_hist[:] = []
998 self.input_hist_raw[:] = []
1046 self.input_hist_raw[:] = []
999 self.output_hist.clear()
1047 self.output_hist.clear()
1000
1048
1001 # Restore the user namespaces to minimal usability
1049 # Restore the user namespaces to minimal usability
1002 self.init_user_ns()
1050 self.init_user_ns()
1003
1051
1004 # Restore the default and user aliases
1052 # Restore the default and user aliases
1005 self.alias_manager.init_aliases()
1053 self.alias_manager.init_aliases()
1006
1054
1007 def push(self, variables, interactive=True):
1055 def push(self, variables, interactive=True):
1008 """Inject a group of variables into the IPython user namespace.
1056 """Inject a group of variables into the IPython user namespace.
1009
1057
1010 Parameters
1058 Parameters
1011 ----------
1059 ----------
1012 variables : dict, str or list/tuple of str
1060 variables : dict, str or list/tuple of str
1013 The variables to inject into the user's namespace. If a dict,
1061 The variables to inject into the user's namespace. If a dict,
1014 a simple update is done. If a str, the string is assumed to
1062 a simple update is done. If a str, the string is assumed to
1015 have variable names separated by spaces. A list/tuple of str
1063 have variable names separated by spaces. A list/tuple of str
1016 can also be used to give the variable names. If just the variable
1064 can also be used to give the variable names. If just the variable
1017 names are give (list/tuple/str) then the variable values looked
1065 names are give (list/tuple/str) then the variable values looked
1018 up in the callers frame.
1066 up in the callers frame.
1019 interactive : bool
1067 interactive : bool
1020 If True (default), the variables will be listed with the ``who``
1068 If True (default), the variables will be listed with the ``who``
1021 magic.
1069 magic.
1022 """
1070 """
1023 vdict = None
1071 vdict = None
1024
1072
1025 # We need a dict of name/value pairs to do namespace updates.
1073 # We need a dict of name/value pairs to do namespace updates.
1026 if isinstance(variables, dict):
1074 if isinstance(variables, dict):
1027 vdict = variables
1075 vdict = variables
1028 elif isinstance(variables, (basestring, list, tuple)):
1076 elif isinstance(variables, (basestring, list, tuple)):
1029 if isinstance(variables, basestring):
1077 if isinstance(variables, basestring):
1030 vlist = variables.split()
1078 vlist = variables.split()
1031 else:
1079 else:
1032 vlist = variables
1080 vlist = variables
1033 vdict = {}
1081 vdict = {}
1034 cf = sys._getframe(1)
1082 cf = sys._getframe(1)
1035 for name in vlist:
1083 for name in vlist:
1036 try:
1084 try:
1037 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1085 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1038 except:
1086 except:
1039 print ('Could not get variable %s from %s' %
1087 print ('Could not get variable %s from %s' %
1040 (name,cf.f_code.co_name))
1088 (name,cf.f_code.co_name))
1041 else:
1089 else:
1042 raise ValueError('variables must be a dict/str/list/tuple')
1090 raise ValueError('variables must be a dict/str/list/tuple')
1043
1091
1044 # Propagate variables to user namespace
1092 # Propagate variables to user namespace
1045 self.user_ns.update(vdict)
1093 self.user_ns.update(vdict)
1046
1094
1047 # And configure interactive visibility
1095 # And configure interactive visibility
1048 config_ns = self.user_config_ns
1096 config_ns = self.user_ns_hidden
1049 if interactive:
1097 if interactive:
1050 for name, val in vdict.iteritems():
1098 for name, val in vdict.iteritems():
1051 config_ns.pop(name, None)
1099 config_ns.pop(name, None)
1052 else:
1100 else:
1053 for name,val in vdict.iteritems():
1101 for name,val in vdict.iteritems():
1054 config_ns[name] = val
1102 config_ns[name] = val
1055
1103
1056 #-------------------------------------------------------------------------
1104 #-------------------------------------------------------------------------
1057 # Things related to history management
1105 # Things related to history management
1058 #-------------------------------------------------------------------------
1106 #-------------------------------------------------------------------------
1059
1107
1060 def init_history(self):
1108 def init_history(self):
1061 # List of input with multi-line handling.
1109 # List of input with multi-line handling.
1062 self.input_hist = InputList()
1110 self.input_hist = InputList()
1063 # This one will hold the 'raw' input history, without any
1111 # This one will hold the 'raw' input history, without any
1064 # pre-processing. This will allow users to retrieve the input just as
1112 # pre-processing. This will allow users to retrieve the input just as
1065 # it was exactly typed in by the user, with %hist -r.
1113 # it was exactly typed in by the user, with %hist -r.
1066 self.input_hist_raw = InputList()
1114 self.input_hist_raw = InputList()
1067
1115
1068 # list of visited directories
1116 # list of visited directories
1069 try:
1117 try:
1070 self.dir_hist = [os.getcwd()]
1118 self.dir_hist = [os.getcwd()]
1071 except OSError:
1119 except OSError:
1072 self.dir_hist = []
1120 self.dir_hist = []
1073
1121
1074 # dict of output history
1122 # dict of output history
1075 self.output_hist = {}
1123 self.output_hist = {}
1076
1124
1077 # Now the history file
1125 # Now the history file
1078 if self.profile:
1126 if self.profile:
1079 histfname = 'history-%s' % self.profile
1127 histfname = 'history-%s' % self.profile
1080 else:
1128 else:
1081 histfname = 'history'
1129 histfname = 'history'
1082 self.histfile = os.path.join(self.ipython_dir, histfname)
1130 self.histfile = os.path.join(self.ipython_dir, histfname)
1083
1131
1084 # Fill the history zero entry, user counter starts at 1
1132 # Fill the history zero entry, user counter starts at 1
1085 self.input_hist.append('\n')
1133 self.input_hist.append('\n')
1086 self.input_hist_raw.append('\n')
1134 self.input_hist_raw.append('\n')
1087
1135
1088 def init_shadow_hist(self):
1136 def init_shadow_hist(self):
1089 try:
1137 try:
1090 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1138 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1091 except exceptions.UnicodeDecodeError:
1139 except exceptions.UnicodeDecodeError:
1092 print "Your ipython_dir can't be decoded to unicode!"
1140 print "Your ipython_dir can't be decoded to unicode!"
1093 print "Please set HOME environment variable to something that"
1141 print "Please set HOME environment variable to something that"
1094 print r"only has ASCII characters, e.g. c:\home"
1142 print r"only has ASCII characters, e.g. c:\home"
1095 print "Now it is", self.ipython_dir
1143 print "Now it is", self.ipython_dir
1096 sys.exit()
1144 sys.exit()
1097 self.shadowhist = ipcorehist.ShadowHist(self.db)
1145 self.shadowhist = ipcorehist.ShadowHist(self.db)
1098
1146
1099 def savehist(self):
1147 def savehist(self):
1100 """Save input history to a file (via readline library)."""
1148 """Save input history to a file (via readline library)."""
1101
1149
1102 if not self.has_readline:
1103 return
1104
1105 try:
1150 try:
1106 self.readline.write_history_file(self.histfile)
1151 self.readline.write_history_file(self.histfile)
1107 except:
1152 except:
1108 print 'Unable to save IPython command history to file: ' + \
1153 print 'Unable to save IPython command history to file: ' + \
1109 `self.histfile`
1154 `self.histfile`
1110
1155
1111 def reloadhist(self):
1156 def reloadhist(self):
1112 """Reload the input history from disk file."""
1157 """Reload the input history from disk file."""
1113
1158
1114 if self.has_readline:
1159 try:
1115 try:
1160 self.readline.clear_history()
1116 self.readline.clear_history()
1161 self.readline.read_history_file(self.shell.histfile)
1117 self.readline.read_history_file(self.shell.histfile)
1162 except AttributeError:
1118 except AttributeError:
1163 pass
1119 pass
1120
1164
1121 def history_saving_wrapper(self, func):
1165 def history_saving_wrapper(self, func):
1122 """ Wrap func for readline history saving
1166 """ Wrap func for readline history saving
1123
1167
1124 Convert func into callable that saves & restores
1168 Convert func into callable that saves & restores
1125 history around the call """
1169 history around the call """
1126
1170
1127 if not self.has_readline:
1171 if self.has_readline:
1172 from IPython.utils import rlineimpl as readline
1173 else:
1128 return func
1174 return func
1129
1175
1130 def wrapper():
1176 def wrapper():
1131 self.savehist()
1177 self.savehist()
1132 try:
1178 try:
1133 func()
1179 func()
1134 finally:
1180 finally:
1135 readline.read_history_file(self.histfile)
1181 readline.read_history_file(self.histfile)
1136 return wrapper
1182 return wrapper
1137
1183
1138 #-------------------------------------------------------------------------
1184 #-------------------------------------------------------------------------
1139 # Things related to exception handling and tracebacks (not debugging)
1185 # Things related to exception handling and tracebacks (not debugging)
1140 #-------------------------------------------------------------------------
1186 #-------------------------------------------------------------------------
1141
1187
1142 def init_traceback_handlers(self, custom_exceptions):
1188 def init_traceback_handlers(self, custom_exceptions):
1143 # Syntax error handler.
1189 # Syntax error handler.
1144 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1190 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1145
1191
1146 # The interactive one is initialized with an offset, meaning we always
1192 # The interactive one is initialized with an offset, meaning we always
1147 # want to remove the topmost item in the traceback, which is our own
1193 # want to remove the topmost item in the traceback, which is our own
1148 # internal code. Valid modes: ['Plain','Context','Verbose']
1194 # internal code. Valid modes: ['Plain','Context','Verbose']
1149 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1195 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1150 color_scheme='NoColor',
1196 color_scheme='NoColor',
1151 tb_offset = 1)
1197 tb_offset = 1)
1152
1198
1153 # IPython itself shouldn't crash. This will produce a detailed
1199 # The instance will store a pointer to the system-wide exception hook,
1154 # post-mortem if it does. But we only install the crash handler for
1200 # so that runtime code (such as magics) can access it. This is because
1155 # non-threaded shells, the threaded ones use a normal verbose reporter
1201 # during the read-eval loop, it may get temporarily overwritten.
1156 # and lose the crash handler. This is because exceptions in the main
1202 self.sys_excepthook = sys.excepthook
1157 # thread (such as in GUI code) propagate directly to sys.excepthook,
1158 # and there's no point in printing crash dumps for every user exception.
1159 if self.isthreaded:
1160 ipCrashHandler = ultratb.FormattedTB()
1161 else:
1162 from IPython.core import crashhandler
1163 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1164 self.set_crash_handler(ipCrashHandler)
1165
1203
1166 # and add any custom exception handlers the user may have specified
1204 # and add any custom exception handlers the user may have specified
1167 self.set_custom_exc(*custom_exceptions)
1205 self.set_custom_exc(*custom_exceptions)
1168
1206
1169 def set_crash_handler(self, crashHandler):
1207 # Set the exception mode
1170 """Set the IPython crash handler.
1208 self.InteractiveTB.set_mode(mode=self.xmode)
1171
1172 This must be a callable with a signature suitable for use as
1173 sys.excepthook."""
1174
1175 # Install the given crash handler as the Python exception hook
1176 sys.excepthook = crashHandler
1177
1178 # The instance will store a pointer to this, so that runtime code
1179 # (such as magics) can access it. This is because during the
1180 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1181 # frameworks).
1182 self.sys_excepthook = sys.excepthook
1183
1209
1184 def set_custom_exc(self,exc_tuple,handler):
1210 def set_custom_exc(self,exc_tuple,handler):
1185 """set_custom_exc(exc_tuple,handler)
1211 """set_custom_exc(exc_tuple,handler)
1186
1212
1187 Set a custom exception handler, which will be called if any of the
1213 Set a custom exception handler, which will be called if any of the
1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1214 exceptions in exc_tuple occur in the mainloop (specifically, in the
1189 runcode() method.
1215 runcode() method.
1190
1216
1191 Inputs:
1217 Inputs:
1192
1218
1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1219 - exc_tuple: a *tuple* of valid exceptions to call the defined
1194 handler for. It is very important that you use a tuple, and NOT A
1220 handler for. It is very important that you use a tuple, and NOT A
1195 LIST here, because of the way Python's except statement works. If
1221 LIST here, because of the way Python's except statement works. If
1196 you only want to trap a single exception, use a singleton tuple:
1222 you only want to trap a single exception, use a singleton tuple:
1197
1223
1198 exc_tuple == (MyCustomException,)
1224 exc_tuple == (MyCustomException,)
1199
1225
1200 - handler: this must be defined as a function with the following
1226 - handler: this must be defined as a function with the following
1201 basic interface: def my_handler(self,etype,value,tb).
1227 basic interface: def my_handler(self,etype,value,tb).
1202
1228
1203 This will be made into an instance method (via new.instancemethod)
1229 This will be made into an instance method (via new.instancemethod)
1204 of IPython itself, and it will be called if any of the exceptions
1230 of IPython itself, and it will be called if any of the exceptions
1205 listed in the exc_tuple are caught. If the handler is None, an
1231 listed in the exc_tuple are caught. If the handler is None, an
1206 internal basic one is used, which just prints basic info.
1232 internal basic one is used, which just prints basic info.
1207
1233
1208 WARNING: by putting in your own exception handler into IPython's main
1234 WARNING: by putting in your own exception handler into IPython's main
1209 execution loop, you run a very good chance of nasty crashes. This
1235 execution loop, you run a very good chance of nasty crashes. This
1210 facility should only be used if you really know what you are doing."""
1236 facility should only be used if you really know what you are doing."""
1211
1237
1212 assert type(exc_tuple)==type(()) , \
1238 assert type(exc_tuple)==type(()) , \
1213 "The custom exceptions must be given AS A TUPLE."
1239 "The custom exceptions must be given AS A TUPLE."
1214
1240
1215 def dummy_handler(self,etype,value,tb):
1241 def dummy_handler(self,etype,value,tb):
1216 print '*** Simple custom exception handler ***'
1242 print '*** Simple custom exception handler ***'
1217 print 'Exception type :',etype
1243 print 'Exception type :',etype
1218 print 'Exception value:',value
1244 print 'Exception value:',value
1219 print 'Traceback :',tb
1245 print 'Traceback :',tb
1220 print 'Source code :','\n'.join(self.buffer)
1246 print 'Source code :','\n'.join(self.buffer)
1221
1247
1222 if handler is None: handler = dummy_handler
1248 if handler is None: handler = dummy_handler
1223
1249
1224 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1250 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1225 self.custom_exceptions = exc_tuple
1251 self.custom_exceptions = exc_tuple
1226
1252
1227 def excepthook(self, etype, value, tb):
1253 def excepthook(self, etype, value, tb):
1228 """One more defense for GUI apps that call sys.excepthook.
1254 """One more defense for GUI apps that call sys.excepthook.
1229
1255
1230 GUI frameworks like wxPython trap exceptions and call
1256 GUI frameworks like wxPython trap exceptions and call
1231 sys.excepthook themselves. I guess this is a feature that
1257 sys.excepthook themselves. I guess this is a feature that
1232 enables them to keep running after exceptions that would
1258 enables them to keep running after exceptions that would
1233 otherwise kill their mainloop. This is a bother for IPython
1259 otherwise kill their mainloop. This is a bother for IPython
1234 which excepts to catch all of the program exceptions with a try:
1260 which excepts to catch all of the program exceptions with a try:
1235 except: statement.
1261 except: statement.
1236
1262
1237 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1263 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1238 any app directly invokes sys.excepthook, it will look to the user like
1264 any app directly invokes sys.excepthook, it will look to the user like
1239 IPython crashed. In order to work around this, we can disable the
1265 IPython crashed. In order to work around this, we can disable the
1240 CrashHandler and replace it with this excepthook instead, which prints a
1266 CrashHandler and replace it with this excepthook instead, which prints a
1241 regular traceback using our InteractiveTB. In this fashion, apps which
1267 regular traceback using our InteractiveTB. In this fashion, apps which
1242 call sys.excepthook will generate a regular-looking exception from
1268 call sys.excepthook will generate a regular-looking exception from
1243 IPython, and the CrashHandler will only be triggered by real IPython
1269 IPython, and the CrashHandler will only be triggered by real IPython
1244 crashes.
1270 crashes.
1245
1271
1246 This hook should be used sparingly, only in places which are not likely
1272 This hook should be used sparingly, only in places which are not likely
1247 to be true IPython errors.
1273 to be true IPython errors.
1248 """
1274 """
1249 self.showtraceback((etype,value,tb),tb_offset=0)
1275 self.showtraceback((etype,value,tb),tb_offset=0)
1250
1276
1251 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1277 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1278 exception_only=False):
1252 """Display the exception that just occurred.
1279 """Display the exception that just occurred.
1253
1280
1254 If nothing is known about the exception, this is the method which
1281 If nothing is known about the exception, this is the method which
1255 should be used throughout the code for presenting user tracebacks,
1282 should be used throughout the code for presenting user tracebacks,
1256 rather than directly invoking the InteractiveTB object.
1283 rather than directly invoking the InteractiveTB object.
1257
1284
1258 A specific showsyntaxerror() also exists, but this method can take
1285 A specific showsyntaxerror() also exists, but this method can take
1259 care of calling it if needed, so unless you are explicitly catching a
1286 care of calling it if needed, so unless you are explicitly catching a
1260 SyntaxError exception, don't try to analyze the stack manually and
1287 SyntaxError exception, don't try to analyze the stack manually and
1261 simply call this method."""
1288 simply call this method."""
1262
1263
1264 # Though this won't be called by syntax errors in the input line,
1265 # there may be SyntaxError cases whith imported code.
1266
1289
1267 try:
1290 try:
1268 if exc_tuple is None:
1291 if exc_tuple is None:
1269 etype, value, tb = sys.exc_info()
1292 etype, value, tb = sys.exc_info()
1270 else:
1293 else:
1271 etype, value, tb = exc_tuple
1294 etype, value, tb = exc_tuple
1295
1296 if etype is None:
1297 if hasattr(sys, 'last_type'):
1298 etype, value, tb = sys.last_type, sys.last_value, \
1299 sys.last_traceback
1300 else:
1301 self.write('No traceback available to show.\n')
1302 return
1272
1303
1273 if etype is SyntaxError:
1304 if etype is SyntaxError:
1305 # Though this won't be called by syntax errors in the input
1306 # line, there may be SyntaxError cases whith imported code.
1274 self.showsyntaxerror(filename)
1307 self.showsyntaxerror(filename)
1275 elif etype is UsageError:
1308 elif etype is UsageError:
1276 print "UsageError:", value
1309 print "UsageError:", value
1277 else:
1310 else:
1278 # WARNING: these variables are somewhat deprecated and not
1311 # WARNING: these variables are somewhat deprecated and not
1279 # necessarily safe to use in a threaded environment, but tools
1312 # necessarily safe to use in a threaded environment, but tools
1280 # like pdb depend on their existence, so let's set them. If we
1313 # like pdb depend on their existence, so let's set them. If we
1281 # find problems in the field, we'll need to revisit their use.
1314 # find problems in the field, we'll need to revisit their use.
1282 sys.last_type = etype
1315 sys.last_type = etype
1283 sys.last_value = value
1316 sys.last_value = value
1284 sys.last_traceback = tb
1317 sys.last_traceback = tb
1285
1318
1286 if etype in self.custom_exceptions:
1319 if etype in self.custom_exceptions:
1287 self.CustomTB(etype,value,tb)
1320 self.CustomTB(etype,value,tb)
1288 else:
1321 else:
1289 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1322 if exception_only:
1290 if self.InteractiveTB.call_pdb and self.has_readline:
1323 m = ('An exception has occurred, use %tb to see the '
1291 # pdb mucks up readline, fix it back
1324 'full traceback.')
1292 self.set_completer()
1325 print m
1326 self.InteractiveTB.show_exception_only(etype, value)
1327 else:
1328 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1329 if self.InteractiveTB.call_pdb:
1330 # pdb mucks up readline, fix it back
1331 self.set_completer()
1332
1293 except KeyboardInterrupt:
1333 except KeyboardInterrupt:
1294 self.write("\nKeyboardInterrupt\n")
1334 self.write("\nKeyboardInterrupt\n")
1335
1295
1336
1296 def showsyntaxerror(self, filename=None):
1337 def showsyntaxerror(self, filename=None):
1297 """Display the syntax error that just occurred.
1338 """Display the syntax error that just occurred.
1298
1339
1299 This doesn't display a stack trace because there isn't one.
1340 This doesn't display a stack trace because there isn't one.
1300
1341
1301 If a filename is given, it is stuffed in the exception instead
1342 If a filename is given, it is stuffed in the exception instead
1302 of what was there before (because Python's parser always uses
1343 of what was there before (because Python's parser always uses
1303 "<string>" when reading from a string).
1344 "<string>" when reading from a string).
1304 """
1345 """
1305 etype, value, last_traceback = sys.exc_info()
1346 etype, value, last_traceback = sys.exc_info()
1306
1347
1307 # See note about these variables in showtraceback() below
1348 # See note about these variables in showtraceback() above
1308 sys.last_type = etype
1349 sys.last_type = etype
1309 sys.last_value = value
1350 sys.last_value = value
1310 sys.last_traceback = last_traceback
1351 sys.last_traceback = last_traceback
1311
1352
1312 if filename and etype is SyntaxError:
1353 if filename and etype is SyntaxError:
1313 # Work hard to stuff the correct filename in the exception
1354 # Work hard to stuff the correct filename in the exception
1314 try:
1355 try:
1315 msg, (dummy_filename, lineno, offset, line) = value
1356 msg, (dummy_filename, lineno, offset, line) = value
1316 except:
1357 except:
1317 # Not the format we expect; leave it alone
1358 # Not the format we expect; leave it alone
1318 pass
1359 pass
1319 else:
1360 else:
1320 # Stuff in the right filename
1361 # Stuff in the right filename
1321 try:
1362 try:
1322 # Assume SyntaxError is a class exception
1363 # Assume SyntaxError is a class exception
1323 value = SyntaxError(msg, (filename, lineno, offset, line))
1364 value = SyntaxError(msg, (filename, lineno, offset, line))
1324 except:
1365 except:
1325 # If that failed, assume SyntaxError is a string
1366 # If that failed, assume SyntaxError is a string
1326 value = msg, (filename, lineno, offset, line)
1367 value = msg, (filename, lineno, offset, line)
1327 self.SyntaxTB(etype,value,[])
1368 self.SyntaxTB(etype,value,[])
1328
1369
1329 def edit_syntax_error(self):
1370 def edit_syntax_error(self):
1330 """The bottom half of the syntax error handler called in the main loop.
1371 """The bottom half of the syntax error handler called in the main loop.
1331
1372
1332 Loop until syntax error is fixed or user cancels.
1373 Loop until syntax error is fixed or user cancels.
1333 """
1374 """
1334
1375
1335 while self.SyntaxTB.last_syntax_error:
1376 while self.SyntaxTB.last_syntax_error:
1336 # copy and clear last_syntax_error
1377 # copy and clear last_syntax_error
1337 err = self.SyntaxTB.clear_err_state()
1378 err = self.SyntaxTB.clear_err_state()
1338 if not self._should_recompile(err):
1379 if not self._should_recompile(err):
1339 return
1380 return
1340 try:
1381 try:
1341 # may set last_syntax_error again if a SyntaxError is raised
1382 # may set last_syntax_error again if a SyntaxError is raised
1342 self.safe_execfile(err.filename,self.user_ns)
1383 self.safe_execfile(err.filename,self.user_ns)
1343 except:
1384 except:
1344 self.showtraceback()
1385 self.showtraceback()
1345 else:
1386 else:
1346 try:
1387 try:
1347 f = file(err.filename)
1388 f = file(err.filename)
1348 try:
1389 try:
1349 # This should be inside a display_trap block and I
1390 # This should be inside a display_trap block and I
1350 # think it is.
1391 # think it is.
1351 sys.displayhook(f.read())
1392 sys.displayhook(f.read())
1352 finally:
1393 finally:
1353 f.close()
1394 f.close()
1354 except:
1395 except:
1355 self.showtraceback()
1396 self.showtraceback()
1356
1397
1357 def _should_recompile(self,e):
1398 def _should_recompile(self,e):
1358 """Utility routine for edit_syntax_error"""
1399 """Utility routine for edit_syntax_error"""
1359
1400
1360 if e.filename in ('<ipython console>','<input>','<string>',
1401 if e.filename in ('<ipython console>','<input>','<string>',
1361 '<console>','<BackgroundJob compilation>',
1402 '<console>','<BackgroundJob compilation>',
1362 None):
1403 None):
1363
1404
1364 return False
1405 return False
1365 try:
1406 try:
1366 if (self.autoedit_syntax and
1407 if (self.autoedit_syntax and
1367 not self.ask_yes_no('Return to editor to correct syntax error? '
1408 not self.ask_yes_no('Return to editor to correct syntax error? '
1368 '[Y/n] ','y')):
1409 '[Y/n] ','y')):
1369 return False
1410 return False
1370 except EOFError:
1411 except EOFError:
1371 return False
1412 return False
1372
1413
1373 def int0(x):
1414 def int0(x):
1374 try:
1415 try:
1375 return int(x)
1416 return int(x)
1376 except TypeError:
1417 except TypeError:
1377 return 0
1418 return 0
1378 # always pass integer line and offset values to editor hook
1419 # always pass integer line and offset values to editor hook
1379 try:
1420 try:
1380 self.hooks.fix_error_editor(e.filename,
1421 self.hooks.fix_error_editor(e.filename,
1381 int0(e.lineno),int0(e.offset),e.msg)
1422 int0(e.lineno),int0(e.offset),e.msg)
1382 except TryNext:
1423 except TryNext:
1383 warn('Could not open editor')
1424 warn('Could not open editor')
1384 return False
1425 return False
1385 return True
1426 return True
1386
1427
1387 #-------------------------------------------------------------------------
1428 #-------------------------------------------------------------------------
1388 # Things related to tab completion
1429 # Things related to tab completion
1389 #-------------------------------------------------------------------------
1430 #-------------------------------------------------------------------------
1390
1431
1391 def complete(self, text):
1432 def complete(self, text):
1392 """Return a sorted list of all possible completions on text.
1433 """Return a sorted list of all possible completions on text.
1393
1434
1394 Inputs:
1435 Inputs:
1395
1436
1396 - text: a string of text to be completed on.
1437 - text: a string of text to be completed on.
1397
1438
1398 This is a wrapper around the completion mechanism, similar to what
1439 This is a wrapper around the completion mechanism, similar to what
1399 readline does at the command line when the TAB key is hit. By
1440 readline does at the command line when the TAB key is hit. By
1400 exposing it as a method, it can be used by other non-readline
1441 exposing it as a method, it can be used by other non-readline
1401 environments (such as GUIs) for text completion.
1442 environments (such as GUIs) for text completion.
1402
1443
1403 Simple usage example:
1444 Simple usage example:
1404
1445
1405 In [7]: x = 'hello'
1446 In [7]: x = 'hello'
1406
1447
1407 In [8]: x
1448 In [8]: x
1408 Out[8]: 'hello'
1449 Out[8]: 'hello'
1409
1450
1410 In [9]: print x
1451 In [9]: print x
1411 hello
1452 hello
1412
1453
1413 In [10]: _ip.complete('x.l')
1454 In [10]: _ip.complete('x.l')
1414 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1455 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1415 """
1456 """
1416
1457
1417 # Inject names into __builtin__ so we can complete on the added names.
1458 # Inject names into __builtin__ so we can complete on the added names.
1418 with self.builtin_trap:
1459 with self.builtin_trap:
1419 complete = self.Completer.complete
1460 complete = self.Completer.complete
1420 state = 0
1461 state = 0
1421 # use a dict so we get unique keys, since ipyhton's multiple
1462 # use a dict so we get unique keys, since ipyhton's multiple
1422 # completers can return duplicates. When we make 2.4 a requirement,
1463 # completers can return duplicates. When we make 2.4 a requirement,
1423 # start using sets instead, which are faster.
1464 # start using sets instead, which are faster.
1424 comps = {}
1465 comps = {}
1425 while True:
1466 while True:
1426 newcomp = complete(text,state,line_buffer=text)
1467 newcomp = complete(text,state,line_buffer=text)
1427 if newcomp is None:
1468 if newcomp is None:
1428 break
1469 break
1429 comps[newcomp] = 1
1470 comps[newcomp] = 1
1430 state += 1
1471 state += 1
1431 outcomps = comps.keys()
1472 outcomps = comps.keys()
1432 outcomps.sort()
1473 outcomps.sort()
1433 #print "T:",text,"OC:",outcomps # dbg
1474 #print "T:",text,"OC:",outcomps # dbg
1434 #print "vars:",self.user_ns.keys()
1475 #print "vars:",self.user_ns.keys()
1435 return outcomps
1476 return outcomps
1436
1477
1437 def set_custom_completer(self,completer,pos=0):
1478 def set_custom_completer(self,completer,pos=0):
1438 """Adds a new custom completer function.
1479 """Adds a new custom completer function.
1439
1480
1440 The position argument (defaults to 0) is the index in the completers
1481 The position argument (defaults to 0) is the index in the completers
1441 list where you want the completer to be inserted."""
1482 list where you want the completer to be inserted."""
1442
1483
1443 newcomp = new.instancemethod(completer,self.Completer,
1484 newcomp = new.instancemethod(completer,self.Completer,
1444 self.Completer.__class__)
1485 self.Completer.__class__)
1445 self.Completer.matchers.insert(pos,newcomp)
1486 self.Completer.matchers.insert(pos,newcomp)
1446
1487
1447 def set_completer(self):
1488 def set_completer(self):
1448 """Reset readline's completer to be our own."""
1489 """Reset readline's completer to be our own."""
1449 self.readline.set_completer(self.Completer.complete)
1490 self.readline.set_completer(self.Completer.complete)
1450
1491
1451 def set_completer_frame(self, frame=None):
1492 def set_completer_frame(self, frame=None):
1452 """Set the frame of the completer."""
1493 """Set the frame of the completer."""
1453 if frame:
1494 if frame:
1454 self.Completer.namespace = frame.f_locals
1495 self.Completer.namespace = frame.f_locals
1455 self.Completer.global_namespace = frame.f_globals
1496 self.Completer.global_namespace = frame.f_globals
1456 else:
1497 else:
1457 self.Completer.namespace = self.user_ns
1498 self.Completer.namespace = self.user_ns
1458 self.Completer.global_namespace = self.user_global_ns
1499 self.Completer.global_namespace = self.user_global_ns
1459
1500
1460 #-------------------------------------------------------------------------
1501 #-------------------------------------------------------------------------
1461 # Things related to readline
1502 # Things related to readline
1462 #-------------------------------------------------------------------------
1503 #-------------------------------------------------------------------------
1463
1504
1464 def init_readline(self):
1505 def init_readline(self):
1465 """Command history completion/saving/reloading."""
1506 """Command history completion/saving/reloading."""
1466
1507
1508 if self.readline_use:
1509 import IPython.utils.rlineimpl as readline
1510
1467 self.rl_next_input = None
1511 self.rl_next_input = None
1468 self.rl_do_indent = False
1512 self.rl_do_indent = False
1469
1513
1470 if not self.readline_use:
1514 if not self.readline_use or not readline.have_readline:
1471 return
1515 self.has_readline = False
1472
1473 import IPython.utils.rlineimpl as readline
1474
1475 if not readline.have_readline:
1476 self.has_readline = 0
1477 self.readline = None
1516 self.readline = None
1478 # no point in bugging windows users with this every time:
1517 # Set a number of methods that depend on readline to be no-op
1479 warn('Readline services not available on this platform.')
1518 self.savehist = no_op
1519 self.reloadhist = no_op
1520 self.set_completer = no_op
1521 self.set_custom_completer = no_op
1522 self.set_completer_frame = no_op
1523 warn('Readline services not available or not loaded.')
1480 else:
1524 else:
1525 self.has_readline = True
1526 self.readline = readline
1481 sys.modules['readline'] = readline
1527 sys.modules['readline'] = readline
1482 import atexit
1528 import atexit
1483 from IPython.core.completer import IPCompleter
1529 from IPython.core.completer import IPCompleter
1484 self.Completer = IPCompleter(self,
1530 self.Completer = IPCompleter(self,
1485 self.user_ns,
1531 self.user_ns,
1486 self.user_global_ns,
1532 self.user_global_ns,
1487 self.readline_omit__names,
1533 self.readline_omit__names,
1488 self.alias_manager.alias_table)
1534 self.alias_manager.alias_table)
1489 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1535 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1490 self.strdispatchers['complete_command'] = sdisp
1536 self.strdispatchers['complete_command'] = sdisp
1491 self.Completer.custom_completers = sdisp
1537 self.Completer.custom_completers = sdisp
1492 # Platform-specific configuration
1538 # Platform-specific configuration
1493 if os.name == 'nt':
1539 if os.name == 'nt':
1494 self.readline_startup_hook = readline.set_pre_input_hook
1540 self.readline_startup_hook = readline.set_pre_input_hook
1495 else:
1541 else:
1496 self.readline_startup_hook = readline.set_startup_hook
1542 self.readline_startup_hook = readline.set_startup_hook
1497
1543
1498 # Load user's initrc file (readline config)
1544 # Load user's initrc file (readline config)
1499 # Or if libedit is used, load editrc.
1545 # Or if libedit is used, load editrc.
1500 inputrc_name = os.environ.get('INPUTRC')
1546 inputrc_name = os.environ.get('INPUTRC')
1501 if inputrc_name is None:
1547 if inputrc_name is None:
1502 home_dir = get_home_dir()
1548 home_dir = get_home_dir()
1503 if home_dir is not None:
1549 if home_dir is not None:
1504 inputrc_name = '.inputrc'
1550 inputrc_name = '.inputrc'
1505 if readline.uses_libedit:
1551 if readline.uses_libedit:
1506 inputrc_name = '.editrc'
1552 inputrc_name = '.editrc'
1507 inputrc_name = os.path.join(home_dir, inputrc_name)
1553 inputrc_name = os.path.join(home_dir, inputrc_name)
1508 if os.path.isfile(inputrc_name):
1554 if os.path.isfile(inputrc_name):
1509 try:
1555 try:
1510 readline.read_init_file(inputrc_name)
1556 readline.read_init_file(inputrc_name)
1511 except:
1557 except:
1512 warn('Problems reading readline initialization file <%s>'
1558 warn('Problems reading readline initialization file <%s>'
1513 % inputrc_name)
1559 % inputrc_name)
1514
1560
1515 self.has_readline = 1
1516 self.readline = readline
1517 # save this in sys so embedded copies can restore it properly
1561 # save this in sys so embedded copies can restore it properly
1518 sys.ipcompleter = self.Completer.complete
1562 sys.ipcompleter = self.Completer.complete
1519 self.set_completer()
1563 self.set_completer()
1520
1564
1521 # Configure readline according to user's prefs
1565 # Configure readline according to user's prefs
1522 # This is only done if GNU readline is being used. If libedit
1566 # This is only done if GNU readline is being used. If libedit
1523 # is being used (as on Leopard) the readline config is
1567 # is being used (as on Leopard) the readline config is
1524 # not run as the syntax for libedit is different.
1568 # not run as the syntax for libedit is different.
1525 if not readline.uses_libedit:
1569 if not readline.uses_libedit:
1526 for rlcommand in self.readline_parse_and_bind:
1570 for rlcommand in self.readline_parse_and_bind:
1527 #print "loading rl:",rlcommand # dbg
1571 #print "loading rl:",rlcommand # dbg
1528 readline.parse_and_bind(rlcommand)
1572 readline.parse_and_bind(rlcommand)
1529
1573
1530 # Remove some chars from the delimiters list. If we encounter
1574 # Remove some chars from the delimiters list. If we encounter
1531 # unicode chars, discard them.
1575 # unicode chars, discard them.
1532 delims = readline.get_completer_delims().encode("ascii", "ignore")
1576 delims = readline.get_completer_delims().encode("ascii", "ignore")
1533 delims = delims.translate(string._idmap,
1577 delims = delims.translate(string._idmap,
1534 self.readline_remove_delims)
1578 self.readline_remove_delims)
1535 readline.set_completer_delims(delims)
1579 readline.set_completer_delims(delims)
1536 # otherwise we end up with a monster history after a while:
1580 # otherwise we end up with a monster history after a while:
1537 readline.set_history_length(1000)
1581 readline.set_history_length(1000)
1538 try:
1582 try:
1539 #print '*** Reading readline history' # dbg
1583 #print '*** Reading readline history' # dbg
1540 readline.read_history_file(self.histfile)
1584 readline.read_history_file(self.histfile)
1541 except IOError:
1585 except IOError:
1542 pass # It doesn't exist yet.
1586 pass # It doesn't exist yet.
1543
1587
1544 atexit.register(self.atexit_operations)
1588 atexit.register(self.atexit_operations)
1545 del atexit
1589 del atexit
1546
1590
1547 # Configure auto-indent for all platforms
1591 # Configure auto-indent for all platforms
1548 self.set_autoindent(self.autoindent)
1592 self.set_autoindent(self.autoindent)
1549
1593
1550 def set_next_input(self, s):
1594 def set_next_input(self, s):
1551 """ Sets the 'default' input string for the next command line.
1595 """ Sets the 'default' input string for the next command line.
1552
1596
1553 Requires readline.
1597 Requires readline.
1554
1598
1555 Example:
1599 Example:
1556
1600
1557 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1601 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1558 [D:\ipython]|2> Hello Word_ # cursor is here
1602 [D:\ipython]|2> Hello Word_ # cursor is here
1559 """
1603 """
1560
1604
1561 self.rl_next_input = s
1605 self.rl_next_input = s
1562
1606
1563 def pre_readline(self):
1607 def pre_readline(self):
1564 """readline hook to be used at the start of each line.
1608 """readline hook to be used at the start of each line.
1565
1609
1566 Currently it handles auto-indent only."""
1610 Currently it handles auto-indent only."""
1567
1611
1568 #debugx('self.indent_current_nsp','pre_readline:')
1612 #debugx('self.indent_current_nsp','pre_readline:')
1569
1613
1570 if self.rl_do_indent:
1614 if self.rl_do_indent:
1571 self.readline.insert_text(self._indent_current_str())
1615 self.readline.insert_text(self._indent_current_str())
1572 if self.rl_next_input is not None:
1616 if self.rl_next_input is not None:
1573 self.readline.insert_text(self.rl_next_input)
1617 self.readline.insert_text(self.rl_next_input)
1574 self.rl_next_input = None
1618 self.rl_next_input = None
1575
1619
1576 def _indent_current_str(self):
1620 def _indent_current_str(self):
1577 """return the current level of indentation as a string"""
1621 """return the current level of indentation as a string"""
1578 return self.indent_current_nsp * ' '
1622 return self.indent_current_nsp * ' '
1579
1623
1580 #-------------------------------------------------------------------------
1624 #-------------------------------------------------------------------------
1581 # Things related to magics
1625 # Things related to magics
1582 #-------------------------------------------------------------------------
1626 #-------------------------------------------------------------------------
1583
1627
1584 def init_magics(self):
1628 def init_magics(self):
1585 # Set user colors (don't do it in the constructor above so that it
1629 # Set user colors (don't do it in the constructor above so that it
1586 # doesn't crash if colors option is invalid)
1630 # doesn't crash if colors option is invalid)
1587 self.magic_colors(self.colors)
1631 self.magic_colors(self.colors)
1632 # History was moved to a separate module
1633 from . import history
1634 history.init_ipython(self)
1588
1635
1589 def magic(self,arg_s):
1636 def magic(self,arg_s):
1590 """Call a magic function by name.
1637 """Call a magic function by name.
1591
1638
1592 Input: a string containing the name of the magic function to call and any
1639 Input: a string containing the name of the magic function to call and any
1593 additional arguments to be passed to the magic.
1640 additional arguments to be passed to the magic.
1594
1641
1595 magic('name -opt foo bar') is equivalent to typing at the ipython
1642 magic('name -opt foo bar') is equivalent to typing at the ipython
1596 prompt:
1643 prompt:
1597
1644
1598 In[1]: %name -opt foo bar
1645 In[1]: %name -opt foo bar
1599
1646
1600 To call a magic without arguments, simply use magic('name').
1647 To call a magic without arguments, simply use magic('name').
1601
1648
1602 This provides a proper Python function to call IPython's magics in any
1649 This provides a proper Python function to call IPython's magics in any
1603 valid Python code you can type at the interpreter, including loops and
1650 valid Python code you can type at the interpreter, including loops and
1604 compound statements.
1651 compound statements.
1605 """
1652 """
1606
1607 args = arg_s.split(' ',1)
1653 args = arg_s.split(' ',1)
1608 magic_name = args[0]
1654 magic_name = args[0]
1609 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1655 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1610
1656
1611 try:
1657 try:
1612 magic_args = args[1]
1658 magic_args = args[1]
1613 except IndexError:
1659 except IndexError:
1614 magic_args = ''
1660 magic_args = ''
1615 fn = getattr(self,'magic_'+magic_name,None)
1661 fn = getattr(self,'magic_'+magic_name,None)
1616 if fn is None:
1662 if fn is None:
1617 error("Magic function `%s` not found." % magic_name)
1663 error("Magic function `%s` not found." % magic_name)
1618 else:
1664 else:
1619 magic_args = self.var_expand(magic_args,1)
1665 magic_args = self.var_expand(magic_args,1)
1620 with nested(self.builtin_trap,):
1666 with nested(self.builtin_trap,):
1621 result = fn(magic_args)
1667 result = fn(magic_args)
1622 return result
1668 return result
1623
1669
1624 def define_magic(self, magicname, func):
1670 def define_magic(self, magicname, func):
1625 """Expose own function as magic function for ipython
1671 """Expose own function as magic function for ipython
1626
1672
1627 def foo_impl(self,parameter_s=''):
1673 def foo_impl(self,parameter_s=''):
1628 'My very own magic!. (Use docstrings, IPython reads them).'
1674 'My very own magic!. (Use docstrings, IPython reads them).'
1629 print 'Magic function. Passed parameter is between < >:'
1675 print 'Magic function. Passed parameter is between < >:'
1630 print '<%s>' % parameter_s
1676 print '<%s>' % parameter_s
1631 print 'The self object is:',self
1677 print 'The self object is:',self
1632
1678
1633 self.define_magic('foo',foo_impl)
1679 self.define_magic('foo',foo_impl)
1634 """
1680 """
1635
1681
1636 import new
1682 import new
1637 im = new.instancemethod(func,self, self.__class__)
1683 im = new.instancemethod(func,self, self.__class__)
1638 old = getattr(self, "magic_" + magicname, None)
1684 old = getattr(self, "magic_" + magicname, None)
1639 setattr(self, "magic_" + magicname, im)
1685 setattr(self, "magic_" + magicname, im)
1640 return old
1686 return old
1641
1687
1642 #-------------------------------------------------------------------------
1688 #-------------------------------------------------------------------------
1643 # Things related to macros
1689 # Things related to macros
1644 #-------------------------------------------------------------------------
1690 #-------------------------------------------------------------------------
1645
1691
1646 def define_macro(self, name, themacro):
1692 def define_macro(self, name, themacro):
1647 """Define a new macro
1693 """Define a new macro
1648
1694
1649 Parameters
1695 Parameters
1650 ----------
1696 ----------
1651 name : str
1697 name : str
1652 The name of the macro.
1698 The name of the macro.
1653 themacro : str or Macro
1699 themacro : str or Macro
1654 The action to do upon invoking the macro. If a string, a new
1700 The action to do upon invoking the macro. If a string, a new
1655 Macro object is created by passing the string to it.
1701 Macro object is created by passing the string to it.
1656 """
1702 """
1657
1703
1658 from IPython.core import macro
1704 from IPython.core import macro
1659
1705
1660 if isinstance(themacro, basestring):
1706 if isinstance(themacro, basestring):
1661 themacro = macro.Macro(themacro)
1707 themacro = macro.Macro(themacro)
1662 if not isinstance(themacro, macro.Macro):
1708 if not isinstance(themacro, macro.Macro):
1663 raise ValueError('A macro must be a string or a Macro instance.')
1709 raise ValueError('A macro must be a string or a Macro instance.')
1664 self.user_ns[name] = themacro
1710 self.user_ns[name] = themacro
1665
1711
1666 #-------------------------------------------------------------------------
1712 #-------------------------------------------------------------------------
1667 # Things related to the running of system commands
1713 # Things related to the running of system commands
1668 #-------------------------------------------------------------------------
1714 #-------------------------------------------------------------------------
1669
1715
1670 def system(self, cmd):
1716 def system(self, cmd):
1671 """Make a system call, using IPython."""
1717 """Make a system call, using IPython."""
1672 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1718 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1673
1719
1674 #-------------------------------------------------------------------------
1720 #-------------------------------------------------------------------------
1675 # Things related to aliases
1721 # Things related to aliases
1676 #-------------------------------------------------------------------------
1722 #-------------------------------------------------------------------------
1677
1723
1678 def init_alias(self):
1724 def init_alias(self):
1679 self.alias_manager = AliasManager(self, config=self.config)
1725 self.alias_manager = AliasManager(self, config=self.config)
1680 self.ns_table['alias'] = self.alias_manager.alias_table,
1726 self.ns_table['alias'] = self.alias_manager.alias_table,
1681
1727
1682 #-------------------------------------------------------------------------
1728 #-------------------------------------------------------------------------
1683 # Things related to the running of code
1729 # Things related to the running of code
1684 #-------------------------------------------------------------------------
1730 #-------------------------------------------------------------------------
1685
1731
1686 def ex(self, cmd):
1732 def ex(self, cmd):
1687 """Execute a normal python statement in user namespace."""
1733 """Execute a normal python statement in user namespace."""
1688 with nested(self.builtin_trap,):
1734 with nested(self.builtin_trap,):
1689 exec cmd in self.user_global_ns, self.user_ns
1735 exec cmd in self.user_global_ns, self.user_ns
1690
1736
1691 def ev(self, expr):
1737 def ev(self, expr):
1692 """Evaluate python expression expr in user namespace.
1738 """Evaluate python expression expr in user namespace.
1693
1739
1694 Returns the result of evaluation
1740 Returns the result of evaluation
1695 """
1741 """
1696 with nested(self.builtin_trap,):
1742 with nested(self.builtin_trap,):
1697 return eval(expr, self.user_global_ns, self.user_ns)
1743 return eval(expr, self.user_global_ns, self.user_ns)
1698
1744
1699 def mainloop(self, display_banner=None):
1745 def mainloop(self, display_banner=None):
1700 """Start the mainloop.
1746 """Start the mainloop.
1701
1747
1702 If an optional banner argument is given, it will override the
1748 If an optional banner argument is given, it will override the
1703 internally created default banner.
1749 internally created default banner.
1704 """
1750 """
1705
1751
1706 with nested(self.builtin_trap, self.display_trap):
1752 with nested(self.builtin_trap, self.display_trap):
1707
1753
1708 # if you run stuff with -c <cmd>, raw hist is not updated
1754 # if you run stuff with -c <cmd>, raw hist is not updated
1709 # ensure that it's in sync
1755 # ensure that it's in sync
1710 if len(self.input_hist) != len (self.input_hist_raw):
1756 if len(self.input_hist) != len (self.input_hist_raw):
1711 self.input_hist_raw = InputList(self.input_hist)
1757 self.input_hist_raw = InputList(self.input_hist)
1712
1758
1713 while 1:
1759 while 1:
1714 try:
1760 try:
1715 self.interact(display_banner=display_banner)
1761 self.interact(display_banner=display_banner)
1716 #self.interact_with_readline()
1762 #self.interact_with_readline()
1717 # XXX for testing of a readline-decoupled repl loop, call
1763 # XXX for testing of a readline-decoupled repl loop, call
1718 # interact_with_readline above
1764 # interact_with_readline above
1719 break
1765 break
1720 except KeyboardInterrupt:
1766 except KeyboardInterrupt:
1721 # this should not be necessary, but KeyboardInterrupt
1767 # this should not be necessary, but KeyboardInterrupt
1722 # handling seems rather unpredictable...
1768 # handling seems rather unpredictable...
1723 self.write("\nKeyboardInterrupt in interact()\n")
1769 self.write("\nKeyboardInterrupt in interact()\n")
1724
1770
1725 def interact_prompt(self):
1771 def interact_prompt(self):
1726 """ Print the prompt (in read-eval-print loop)
1772 """ Print the prompt (in read-eval-print loop)
1727
1773
1728 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1774 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1729 used in standard IPython flow.
1775 used in standard IPython flow.
1730 """
1776 """
1731 if self.more:
1777 if self.more:
1732 try:
1778 try:
1733 prompt = self.hooks.generate_prompt(True)
1779 prompt = self.hooks.generate_prompt(True)
1734 except:
1780 except:
1735 self.showtraceback()
1781 self.showtraceback()
1736 if self.autoindent:
1782 if self.autoindent:
1737 self.rl_do_indent = True
1783 self.rl_do_indent = True
1738
1784
1739 else:
1785 else:
1740 try:
1786 try:
1741 prompt = self.hooks.generate_prompt(False)
1787 prompt = self.hooks.generate_prompt(False)
1742 except:
1788 except:
1743 self.showtraceback()
1789 self.showtraceback()
1744 self.write(prompt)
1790 self.write(prompt)
1745
1791
1746 def interact_handle_input(self,line):
1792 def interact_handle_input(self,line):
1747 """ Handle the input line (in read-eval-print loop)
1793 """ Handle the input line (in read-eval-print loop)
1748
1794
1749 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1795 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1750 used in standard IPython flow.
1796 used in standard IPython flow.
1751 """
1797 """
1752 if line.lstrip() == line:
1798 if line.lstrip() == line:
1753 self.shadowhist.add(line.strip())
1799 self.shadowhist.add(line.strip())
1754 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1800 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1755
1801
1756 if line.strip():
1802 if line.strip():
1757 if self.more:
1803 if self.more:
1758 self.input_hist_raw[-1] += '%s\n' % line
1804 self.input_hist_raw[-1] += '%s\n' % line
1759 else:
1805 else:
1760 self.input_hist_raw.append('%s\n' % line)
1806 self.input_hist_raw.append('%s\n' % line)
1761
1807
1762
1808
1763 self.more = self.push_line(lineout)
1809 self.more = self.push_line(lineout)
1764 if (self.SyntaxTB.last_syntax_error and
1810 if (self.SyntaxTB.last_syntax_error and
1765 self.autoedit_syntax):
1811 self.autoedit_syntax):
1766 self.edit_syntax_error()
1812 self.edit_syntax_error()
1767
1813
1768 def interact_with_readline(self):
1814 def interact_with_readline(self):
1769 """ Demo of using interact_handle_input, interact_prompt
1815 """ Demo of using interact_handle_input, interact_prompt
1770
1816
1771 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1817 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1772 it should work like this.
1818 it should work like this.
1773 """
1819 """
1774 self.readline_startup_hook(self.pre_readline)
1820 self.readline_startup_hook(self.pre_readline)
1775 while not self.exit_now:
1821 while not self.exit_now:
1776 self.interact_prompt()
1822 self.interact_prompt()
1777 if self.more:
1823 if self.more:
1778 self.rl_do_indent = True
1824 self.rl_do_indent = True
1779 else:
1825 else:
1780 self.rl_do_indent = False
1826 self.rl_do_indent = False
1781 line = raw_input_original().decode(self.stdin_encoding)
1827 line = raw_input_original().decode(self.stdin_encoding)
1782 self.interact_handle_input(line)
1828 self.interact_handle_input(line)
1783
1829
1784 def interact(self, display_banner=None):
1830 def interact(self, display_banner=None):
1785 """Closely emulate the interactive Python console."""
1831 """Closely emulate the interactive Python console."""
1786
1832
1787 # batch run -> do not interact
1833 # batch run -> do not interact
1788 if self.exit_now:
1834 if self.exit_now:
1789 return
1835 return
1790
1836
1791 if display_banner is None:
1837 if display_banner is None:
1792 display_banner = self.display_banner
1838 display_banner = self.display_banner
1793 if display_banner:
1839 if display_banner:
1794 self.show_banner()
1840 self.show_banner()
1795
1841
1796 more = 0
1842 more = 0
1797
1843
1798 # Mark activity in the builtins
1844 # Mark activity in the builtins
1799 __builtin__.__dict__['__IPYTHON__active'] += 1
1845 __builtin__.__dict__['__IPYTHON__active'] += 1
1800
1846
1801 if self.has_readline:
1847 if self.has_readline:
1802 self.readline_startup_hook(self.pre_readline)
1848 self.readline_startup_hook(self.pre_readline)
1803 # exit_now is set by a call to %Exit or %Quit, through the
1849 # exit_now is set by a call to %Exit or %Quit, through the
1804 # ask_exit callback.
1850 # ask_exit callback.
1805
1851
1806 while not self.exit_now:
1852 while not self.exit_now:
1807 self.hooks.pre_prompt_hook()
1853 self.hooks.pre_prompt_hook()
1808 if more:
1854 if more:
1809 try:
1855 try:
1810 prompt = self.hooks.generate_prompt(True)
1856 prompt = self.hooks.generate_prompt(True)
1811 except:
1857 except:
1812 self.showtraceback()
1858 self.showtraceback()
1813 if self.autoindent:
1859 if self.autoindent:
1814 self.rl_do_indent = True
1860 self.rl_do_indent = True
1815
1861
1816 else:
1862 else:
1817 try:
1863 try:
1818 prompt = self.hooks.generate_prompt(False)
1864 prompt = self.hooks.generate_prompt(False)
1819 except:
1865 except:
1820 self.showtraceback()
1866 self.showtraceback()
1821 try:
1867 try:
1822 line = self.raw_input(prompt, more)
1868 line = self.raw_input(prompt, more)
1823 if self.exit_now:
1869 if self.exit_now:
1824 # quick exit on sys.std[in|out] close
1870 # quick exit on sys.std[in|out] close
1825 break
1871 break
1826 if self.autoindent:
1872 if self.autoindent:
1827 self.rl_do_indent = False
1873 self.rl_do_indent = False
1828
1874
1829 except KeyboardInterrupt:
1875 except KeyboardInterrupt:
1830 #double-guard against keyboardinterrupts during kbdint handling
1876 #double-guard against keyboardinterrupts during kbdint handling
1831 try:
1877 try:
1832 self.write('\nKeyboardInterrupt\n')
1878 self.write('\nKeyboardInterrupt\n')
1833 self.resetbuffer()
1879 self.resetbuffer()
1834 # keep cache in sync with the prompt counter:
1880 # keep cache in sync with the prompt counter:
1835 self.outputcache.prompt_count -= 1
1881 self.outputcache.prompt_count -= 1
1836
1882
1837 if self.autoindent:
1883 if self.autoindent:
1838 self.indent_current_nsp = 0
1884 self.indent_current_nsp = 0
1839 more = 0
1885 more = 0
1840 except KeyboardInterrupt:
1886 except KeyboardInterrupt:
1841 pass
1887 pass
1842 except EOFError:
1888 except EOFError:
1843 if self.autoindent:
1889 if self.autoindent:
1844 self.rl_do_indent = False
1890 self.rl_do_indent = False
1845 self.readline_startup_hook(None)
1891 if self.has_readline:
1892 self.readline_startup_hook(None)
1846 self.write('\n')
1893 self.write('\n')
1847 self.exit()
1894 self.exit()
1848 except bdb.BdbQuit:
1895 except bdb.BdbQuit:
1849 warn('The Python debugger has exited with a BdbQuit exception.\n'
1896 warn('The Python debugger has exited with a BdbQuit exception.\n'
1850 'Because of how pdb handles the stack, it is impossible\n'
1897 'Because of how pdb handles the stack, it is impossible\n'
1851 'for IPython to properly format this particular exception.\n'
1898 'for IPython to properly format this particular exception.\n'
1852 'IPython will resume normal operation.')
1899 'IPython will resume normal operation.')
1853 except:
1900 except:
1854 # exceptions here are VERY RARE, but they can be triggered
1901 # exceptions here are VERY RARE, but they can be triggered
1855 # asynchronously by signal handlers, for example.
1902 # asynchronously by signal handlers, for example.
1856 self.showtraceback()
1903 self.showtraceback()
1857 else:
1904 else:
1858 more = self.push_line(line)
1905 more = self.push_line(line)
1859 if (self.SyntaxTB.last_syntax_error and
1906 if (self.SyntaxTB.last_syntax_error and
1860 self.autoedit_syntax):
1907 self.autoedit_syntax):
1861 self.edit_syntax_error()
1908 self.edit_syntax_error()
1862
1909
1863 # We are off again...
1910 # We are off again...
1864 __builtin__.__dict__['__IPYTHON__active'] -= 1
1911 __builtin__.__dict__['__IPYTHON__active'] -= 1
1865
1912
1913 # Turn off the exit flag, so the mainloop can be restarted if desired
1914 self.exit_now = False
1915
1866 def safe_execfile(self, fname, *where, **kw):
1916 def safe_execfile(self, fname, *where, **kw):
1867 """A safe version of the builtin execfile().
1917 """A safe version of the builtin execfile().
1868
1918
1869 This version will never throw an exception, but instead print
1919 This version will never throw an exception, but instead print
1870 helpful error messages to the screen. This only works on pure
1920 helpful error messages to the screen. This only works on pure
1871 Python files with the .py extension.
1921 Python files with the .py extension.
1872
1922
1873 Parameters
1923 Parameters
1874 ----------
1924 ----------
1875 fname : string
1925 fname : string
1876 The name of the file to be executed.
1926 The name of the file to be executed.
1877 where : tuple
1927 where : tuple
1878 One or two namespaces, passed to execfile() as (globals,locals).
1928 One or two namespaces, passed to execfile() as (globals,locals).
1879 If only one is given, it is passed as both.
1929 If only one is given, it is passed as both.
1880 exit_ignore : bool (False)
1930 exit_ignore : bool (False)
1881 If True, then don't print errors for non-zero exit statuses.
1931 If True, then silence SystemExit for non-zero status (it is always
1932 silenced for zero status, as it is so common).
1882 """
1933 """
1883 kw.setdefault('exit_ignore', False)
1934 kw.setdefault('exit_ignore', False)
1884
1935
1885 fname = os.path.abspath(os.path.expanduser(fname))
1936 fname = os.path.abspath(os.path.expanduser(fname))
1886
1937
1887 # Make sure we have a .py file
1938 # Make sure we have a .py file
1888 if not fname.endswith('.py'):
1939 if not fname.endswith('.py'):
1889 warn('File must end with .py to be run using execfile: <%s>' % fname)
1940 warn('File must end with .py to be run using execfile: <%s>' % fname)
1890
1941
1891 # Make sure we can open the file
1942 # Make sure we can open the file
1892 try:
1943 try:
1893 with open(fname) as thefile:
1944 with open(fname) as thefile:
1894 pass
1945 pass
1895 except:
1946 except:
1896 warn('Could not open file <%s> for safe execution.' % fname)
1947 warn('Could not open file <%s> for safe execution.' % fname)
1897 return
1948 return
1898
1949
1899 # Find things also in current directory. This is needed to mimic the
1950 # Find things also in current directory. This is needed to mimic the
1900 # behavior of running a script from the system command line, where
1951 # behavior of running a script from the system command line, where
1901 # Python inserts the script's directory into sys.path
1952 # Python inserts the script's directory into sys.path
1902 dname = os.path.dirname(fname)
1953 dname = os.path.dirname(fname)
1903
1954
1904 with prepended_to_syspath(dname):
1955 with prepended_to_syspath(dname):
1905 try:
1956 try:
1906 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1957 execfile(fname,*where)
1907 # Work around a bug in Python for Windows. The bug was
1908 # fixed in in Python 2.5 r54159 and 54158, but that's still
1909 # SVN Python as of March/07. For details, see:
1910 # http://projects.scipy.org/ipython/ipython/ticket/123
1911 try:
1912 globs,locs = where[0:2]
1913 except:
1914 try:
1915 globs = locs = where[0]
1916 except:
1917 globs = locs = globals()
1918 exec file(fname) in globs,locs
1919 else:
1920 execfile(fname,*where)
1921 except SyntaxError:
1922 self.showsyntaxerror()
1923 warn('Failure executing file: <%s>' % fname)
1924 except SystemExit, status:
1958 except SystemExit, status:
1925 # Code that correctly sets the exit status flag to success (0)
1959 # If the call was made with 0 or None exit status (sys.exit(0)
1926 # shouldn't be bothered with a traceback. Note that a plain
1960 # or sys.exit() ), don't bother showing a traceback, as both of
1927 # sys.exit() does NOT set the message to 0 (it's empty) so that
1961 # these are considered normal by the OS:
1928 # will still get a traceback. Note that the structure of the
1962 # > python -c'import sys;sys.exit(0)'; echo $?
1929 # SystemExit exception changed between Python 2.4 and 2.5, so
1963 # 0
1930 # the checks must be done in a version-dependent way.
1964 # > python -c'import sys;sys.exit()'; echo $?
1931 show = False
1965 # 0
1932 if status.args[0]==0 and not kw['exit_ignore']:
1966 # For other exit status, we show the exception unless
1933 show = True
1967 # explicitly silenced, but only in short form.
1934 if show:
1968 if status.code not in (0, None) and not kw['exit_ignore']:
1935 self.showtraceback()
1969 self.showtraceback(exception_only=True)
1936 warn('Failure executing file: <%s>' % fname)
1937 except:
1970 except:
1938 self.showtraceback()
1971 self.showtraceback()
1939 warn('Failure executing file: <%s>' % fname)
1940
1972
1941 def safe_execfile_ipy(self, fname):
1973 def safe_execfile_ipy(self, fname):
1942 """Like safe_execfile, but for .ipy files with IPython syntax.
1974 """Like safe_execfile, but for .ipy files with IPython syntax.
1943
1975
1944 Parameters
1976 Parameters
1945 ----------
1977 ----------
1946 fname : str
1978 fname : str
1947 The name of the file to execute. The filename must have a
1979 The name of the file to execute. The filename must have a
1948 .ipy extension.
1980 .ipy extension.
1949 """
1981 """
1950 fname = os.path.abspath(os.path.expanduser(fname))
1982 fname = os.path.abspath(os.path.expanduser(fname))
1951
1983
1952 # Make sure we have a .py file
1984 # Make sure we have a .py file
1953 if not fname.endswith('.ipy'):
1985 if not fname.endswith('.ipy'):
1954 warn('File must end with .py to be run using execfile: <%s>' % fname)
1986 warn('File must end with .py to be run using execfile: <%s>' % fname)
1955
1987
1956 # Make sure we can open the file
1988 # Make sure we can open the file
1957 try:
1989 try:
1958 with open(fname) as thefile:
1990 with open(fname) as thefile:
1959 pass
1991 pass
1960 except:
1992 except:
1961 warn('Could not open file <%s> for safe execution.' % fname)
1993 warn('Could not open file <%s> for safe execution.' % fname)
1962 return
1994 return
1963
1995
1964 # Find things also in current directory. This is needed to mimic the
1996 # Find things also in current directory. This is needed to mimic the
1965 # behavior of running a script from the system command line, where
1997 # behavior of running a script from the system command line, where
1966 # Python inserts the script's directory into sys.path
1998 # Python inserts the script's directory into sys.path
1967 dname = os.path.dirname(fname)
1999 dname = os.path.dirname(fname)
1968
2000
1969 with prepended_to_syspath(dname):
2001 with prepended_to_syspath(dname):
1970 try:
2002 try:
1971 with open(fname) as thefile:
2003 with open(fname) as thefile:
1972 script = thefile.read()
2004 script = thefile.read()
1973 # self.runlines currently captures all exceptions
2005 # self.runlines currently captures all exceptions
1974 # raise in user code. It would be nice if there were
2006 # raise in user code. It would be nice if there were
1975 # versions of runlines, execfile that did raise, so
2007 # versions of runlines, execfile that did raise, so
1976 # we could catch the errors.
2008 # we could catch the errors.
1977 self.runlines(script, clean=True)
2009 self.runlines(script, clean=True)
1978 except:
2010 except:
1979 self.showtraceback()
2011 self.showtraceback()
1980 warn('Unknown failure executing file: <%s>' % fname)
2012 warn('Unknown failure executing file: <%s>' % fname)
1981
2013
1982 def _is_secondary_block_start(self, s):
2014 def _is_secondary_block_start(self, s):
1983 if not s.endswith(':'):
2015 if not s.endswith(':'):
1984 return False
2016 return False
1985 if (s.startswith('elif') or
2017 if (s.startswith('elif') or
1986 s.startswith('else') or
2018 s.startswith('else') or
1987 s.startswith('except') or
2019 s.startswith('except') or
1988 s.startswith('finally')):
2020 s.startswith('finally')):
1989 return True
2021 return True
1990
2022
1991 def cleanup_ipy_script(self, script):
2023 def cleanup_ipy_script(self, script):
1992 """Make a script safe for self.runlines()
2024 """Make a script safe for self.runlines()
1993
2025
1994 Currently, IPython is lines based, with blocks being detected by
2026 Currently, IPython is lines based, with blocks being detected by
1995 empty lines. This is a problem for block based scripts that may
2027 empty lines. This is a problem for block based scripts that may
1996 not have empty lines after blocks. This script adds those empty
2028 not have empty lines after blocks. This script adds those empty
1997 lines to make scripts safe for running in the current line based
2029 lines to make scripts safe for running in the current line based
1998 IPython.
2030 IPython.
1999 """
2031 """
2000 res = []
2032 res = []
2001 lines = script.splitlines()
2033 lines = script.splitlines()
2002 level = 0
2034 level = 0
2003
2035
2004 for l in lines:
2036 for l in lines:
2005 lstripped = l.lstrip()
2037 lstripped = l.lstrip()
2006 stripped = l.strip()
2038 stripped = l.strip()
2007 if not stripped:
2039 if not stripped:
2008 continue
2040 continue
2009 newlevel = len(l) - len(lstripped)
2041 newlevel = len(l) - len(lstripped)
2010 if level > 0 and newlevel == 0 and \
2042 if level > 0 and newlevel == 0 and \
2011 not self._is_secondary_block_start(stripped):
2043 not self._is_secondary_block_start(stripped):
2012 # add empty line
2044 # add empty line
2013 res.append('')
2045 res.append('')
2014 res.append(l)
2046 res.append(l)
2015 level = newlevel
2047 level = newlevel
2016
2048
2017 return '\n'.join(res) + '\n'
2049 return '\n'.join(res) + '\n'
2018
2050
2019 def runlines(self, lines, clean=False):
2051 def runlines(self, lines, clean=False):
2020 """Run a string of one or more lines of source.
2052 """Run a string of one or more lines of source.
2021
2053
2022 This method is capable of running a string containing multiple source
2054 This method is capable of running a string containing multiple source
2023 lines, as if they had been entered at the IPython prompt. Since it
2055 lines, as if they had been entered at the IPython prompt. Since it
2024 exposes IPython's processing machinery, the given strings can contain
2056 exposes IPython's processing machinery, the given strings can contain
2025 magic calls (%magic), special shell access (!cmd), etc.
2057 magic calls (%magic), special shell access (!cmd), etc.
2026 """
2058 """
2027
2059
2028 if isinstance(lines, (list, tuple)):
2060 if isinstance(lines, (list, tuple)):
2029 lines = '\n'.join(lines)
2061 lines = '\n'.join(lines)
2030
2062
2031 if clean:
2063 if clean:
2032 lines = self.cleanup_ipy_script(lines)
2064 lines = self.cleanup_ipy_script(lines)
2033
2065
2034 # We must start with a clean buffer, in case this is run from an
2066 # We must start with a clean buffer, in case this is run from an
2035 # interactive IPython session (via a magic, for example).
2067 # interactive IPython session (via a magic, for example).
2036 self.resetbuffer()
2068 self.resetbuffer()
2037 lines = lines.splitlines()
2069 lines = lines.splitlines()
2038 more = 0
2070 more = 0
2039
2071
2040 with nested(self.builtin_trap, self.display_trap):
2072 with nested(self.builtin_trap, self.display_trap):
2041 for line in lines:
2073 for line in lines:
2042 # skip blank lines so we don't mess up the prompt counter, but do
2074 # skip blank lines so we don't mess up the prompt counter, but do
2043 # NOT skip even a blank line if we are in a code block (more is
2075 # NOT skip even a blank line if we are in a code block (more is
2044 # true)
2076 # true)
2045
2077
2046 if line or more:
2078 if line or more:
2047 # push to raw history, so hist line numbers stay in sync
2079 # push to raw history, so hist line numbers stay in sync
2048 self.input_hist_raw.append("# " + line + "\n")
2080 self.input_hist_raw.append("# " + line + "\n")
2049 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2081 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2050 more = self.push_line(prefiltered)
2082 more = self.push_line(prefiltered)
2051 # IPython's runsource returns None if there was an error
2083 # IPython's runsource returns None if there was an error
2052 # compiling the code. This allows us to stop processing right
2084 # compiling the code. This allows us to stop processing right
2053 # away, so the user gets the error message at the right place.
2085 # away, so the user gets the error message at the right place.
2054 if more is None:
2086 if more is None:
2055 break
2087 break
2056 else:
2088 else:
2057 self.input_hist_raw.append("\n")
2089 self.input_hist_raw.append("\n")
2058 # final newline in case the input didn't have it, so that the code
2090 # final newline in case the input didn't have it, so that the code
2059 # actually does get executed
2091 # actually does get executed
2060 if more:
2092 if more:
2061 self.push_line('\n')
2093 self.push_line('\n')
2062
2094
2063 def runsource(self, source, filename='<input>', symbol='single'):
2095 def runsource(self, source, filename='<input>', symbol='single'):
2064 """Compile and run some source in the interpreter.
2096 """Compile and run some source in the interpreter.
2065
2097
2066 Arguments are as for compile_command().
2098 Arguments are as for compile_command().
2067
2099
2068 One several things can happen:
2100 One several things can happen:
2069
2101
2070 1) The input is incorrect; compile_command() raised an
2102 1) The input is incorrect; compile_command() raised an
2071 exception (SyntaxError or OverflowError). A syntax traceback
2103 exception (SyntaxError or OverflowError). A syntax traceback
2072 will be printed by calling the showsyntaxerror() method.
2104 will be printed by calling the showsyntaxerror() method.
2073
2105
2074 2) The input is incomplete, and more input is required;
2106 2) The input is incomplete, and more input is required;
2075 compile_command() returned None. Nothing happens.
2107 compile_command() returned None. Nothing happens.
2076
2108
2077 3) The input is complete; compile_command() returned a code
2109 3) The input is complete; compile_command() returned a code
2078 object. The code is executed by calling self.runcode() (which
2110 object. The code is executed by calling self.runcode() (which
2079 also handles run-time exceptions, except for SystemExit).
2111 also handles run-time exceptions, except for SystemExit).
2080
2112
2081 The return value is:
2113 The return value is:
2082
2114
2083 - True in case 2
2115 - True in case 2
2084
2116
2085 - False in the other cases, unless an exception is raised, where
2117 - False in the other cases, unless an exception is raised, where
2086 None is returned instead. This can be used by external callers to
2118 None is returned instead. This can be used by external callers to
2087 know whether to continue feeding input or not.
2119 know whether to continue feeding input or not.
2088
2120
2089 The return value can be used to decide whether to use sys.ps1 or
2121 The return value can be used to decide whether to use sys.ps1 or
2090 sys.ps2 to prompt the next line."""
2122 sys.ps2 to prompt the next line."""
2091
2123
2092 # if the source code has leading blanks, add 'if 1:\n' to it
2124 # if the source code has leading blanks, add 'if 1:\n' to it
2093 # this allows execution of indented pasted code. It is tempting
2125 # this allows execution of indented pasted code. It is tempting
2094 # to add '\n' at the end of source to run commands like ' a=1'
2126 # to add '\n' at the end of source to run commands like ' a=1'
2095 # directly, but this fails for more complicated scenarios
2127 # directly, but this fails for more complicated scenarios
2096 source=source.encode(self.stdin_encoding)
2128 source=source.encode(self.stdin_encoding)
2097 if source[:1] in [' ', '\t']:
2129 if source[:1] in [' ', '\t']:
2098 source = 'if 1:\n%s' % source
2130 source = 'if 1:\n%s' % source
2099
2131
2100 try:
2132 try:
2101 code = self.compile(source,filename,symbol)
2133 code = self.compile(source,filename,symbol)
2102 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2134 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2103 # Case 1
2135 # Case 1
2104 self.showsyntaxerror(filename)
2136 self.showsyntaxerror(filename)
2105 return None
2137 return None
2106
2138
2107 if code is None:
2139 if code is None:
2108 # Case 2
2140 # Case 2
2109 return True
2141 return True
2110
2142
2111 # Case 3
2143 # Case 3
2112 # We store the code object so that threaded shells and
2144 # We store the code object so that threaded shells and
2113 # custom exception handlers can access all this info if needed.
2145 # custom exception handlers can access all this info if needed.
2114 # The source corresponding to this can be obtained from the
2146 # The source corresponding to this can be obtained from the
2115 # buffer attribute as '\n'.join(self.buffer).
2147 # buffer attribute as '\n'.join(self.buffer).
2116 self.code_to_run = code
2148 self.code_to_run = code
2117 # now actually execute the code object
2149 # now actually execute the code object
2118 if self.runcode(code) == 0:
2150 if self.runcode(code) == 0:
2119 return False
2151 return False
2120 else:
2152 else:
2121 return None
2153 return None
2122
2154
2123 def runcode(self,code_obj):
2155 def runcode(self,code_obj):
2124 """Execute a code object.
2156 """Execute a code object.
2125
2157
2126 When an exception occurs, self.showtraceback() is called to display a
2158 When an exception occurs, self.showtraceback() is called to display a
2127 traceback.
2159 traceback.
2128
2160
2129 Return value: a flag indicating whether the code to be run completed
2161 Return value: a flag indicating whether the code to be run completed
2130 successfully:
2162 successfully:
2131
2163
2132 - 0: successful execution.
2164 - 0: successful execution.
2133 - 1: an error occurred.
2165 - 1: an error occurred.
2134 """
2166 """
2135
2167
2136 # Set our own excepthook in case the user code tries to call it
2168 # Set our own excepthook in case the user code tries to call it
2137 # directly, so that the IPython crash handler doesn't get triggered
2169 # directly, so that the IPython crash handler doesn't get triggered
2138 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2170 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2139
2171
2140 # we save the original sys.excepthook in the instance, in case config
2172 # we save the original sys.excepthook in the instance, in case config
2141 # code (such as magics) needs access to it.
2173 # code (such as magics) needs access to it.
2142 self.sys_excepthook = old_excepthook
2174 self.sys_excepthook = old_excepthook
2143 outflag = 1 # happens in more places, so it's easier as default
2175 outflag = 1 # happens in more places, so it's easier as default
2144 try:
2176 try:
2145 try:
2177 try:
2146 self.hooks.pre_runcode_hook()
2178 self.hooks.pre_runcode_hook()
2147 exec code_obj in self.user_global_ns, self.user_ns
2179 exec code_obj in self.user_global_ns, self.user_ns
2148 finally:
2180 finally:
2149 # Reset our crash handler in place
2181 # Reset our crash handler in place
2150 sys.excepthook = old_excepthook
2182 sys.excepthook = old_excepthook
2151 except SystemExit:
2183 except SystemExit:
2152 self.resetbuffer()
2184 self.resetbuffer()
2153 self.showtraceback()
2185 self.showtraceback(exception_only=True)
2154 warn("Type %exit or %quit to exit IPython "
2186 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2155 "(%Exit or %Quit do so unconditionally).",level=1)
2156 except self.custom_exceptions:
2187 except self.custom_exceptions:
2157 etype,value,tb = sys.exc_info()
2188 etype,value,tb = sys.exc_info()
2158 self.CustomTB(etype,value,tb)
2189 self.CustomTB(etype,value,tb)
2159 except:
2190 except:
2160 self.showtraceback()
2191 self.showtraceback()
2161 else:
2192 else:
2162 outflag = 0
2193 outflag = 0
2163 if softspace(sys.stdout, 0):
2194 if softspace(sys.stdout, 0):
2164 print
2195 print
2165 # Flush out code object which has been run (and source)
2196 # Flush out code object which has been run (and source)
2166 self.code_to_run = None
2197 self.code_to_run = None
2167 return outflag
2198 return outflag
2168
2199
2169 def push_line(self, line):
2200 def push_line(self, line):
2170 """Push a line to the interpreter.
2201 """Push a line to the interpreter.
2171
2202
2172 The line should not have a trailing newline; it may have
2203 The line should not have a trailing newline; it may have
2173 internal newlines. The line is appended to a buffer and the
2204 internal newlines. The line is appended to a buffer and the
2174 interpreter's runsource() method is called with the
2205 interpreter's runsource() method is called with the
2175 concatenated contents of the buffer as source. If this
2206 concatenated contents of the buffer as source. If this
2176 indicates that the command was executed or invalid, the buffer
2207 indicates that the command was executed or invalid, the buffer
2177 is reset; otherwise, the command is incomplete, and the buffer
2208 is reset; otherwise, the command is incomplete, and the buffer
2178 is left as it was after the line was appended. The return
2209 is left as it was after the line was appended. The return
2179 value is 1 if more input is required, 0 if the line was dealt
2210 value is 1 if more input is required, 0 if the line was dealt
2180 with in some way (this is the same as runsource()).
2211 with in some way (this is the same as runsource()).
2181 """
2212 """
2182
2213
2183 # autoindent management should be done here, and not in the
2214 # autoindent management should be done here, and not in the
2184 # interactive loop, since that one is only seen by keyboard input. We
2215 # interactive loop, since that one is only seen by keyboard input. We
2185 # need this done correctly even for code run via runlines (which uses
2216 # need this done correctly even for code run via runlines (which uses
2186 # push).
2217 # push).
2187
2218
2188 #print 'push line: <%s>' % line # dbg
2219 #print 'push line: <%s>' % line # dbg
2189 for subline in line.splitlines():
2220 for subline in line.splitlines():
2190 self._autoindent_update(subline)
2221 self._autoindent_update(subline)
2191 self.buffer.append(line)
2222 self.buffer.append(line)
2192 more = self.runsource('\n'.join(self.buffer), self.filename)
2223 more = self.runsource('\n'.join(self.buffer), self.filename)
2193 if not more:
2224 if not more:
2194 self.resetbuffer()
2225 self.resetbuffer()
2195 return more
2226 return more
2196
2227
2197 def _autoindent_update(self,line):
2228 def _autoindent_update(self,line):
2198 """Keep track of the indent level."""
2229 """Keep track of the indent level."""
2199
2230
2200 #debugx('line')
2231 #debugx('line')
2201 #debugx('self.indent_current_nsp')
2232 #debugx('self.indent_current_nsp')
2202 if self.autoindent:
2233 if self.autoindent:
2203 if line:
2234 if line:
2204 inisp = num_ini_spaces(line)
2235 inisp = num_ini_spaces(line)
2205 if inisp < self.indent_current_nsp:
2236 if inisp < self.indent_current_nsp:
2206 self.indent_current_nsp = inisp
2237 self.indent_current_nsp = inisp
2207
2238
2208 if line[-1] == ':':
2239 if line[-1] == ':':
2209 self.indent_current_nsp += 4
2240 self.indent_current_nsp += 4
2210 elif dedent_re.match(line):
2241 elif dedent_re.match(line):
2211 self.indent_current_nsp -= 4
2242 self.indent_current_nsp -= 4
2212 else:
2243 else:
2213 self.indent_current_nsp = 0
2244 self.indent_current_nsp = 0
2214
2245
2215 def resetbuffer(self):
2246 def resetbuffer(self):
2216 """Reset the input buffer."""
2247 """Reset the input buffer."""
2217 self.buffer[:] = []
2248 self.buffer[:] = []
2218
2249
2219 def raw_input(self,prompt='',continue_prompt=False):
2250 def raw_input(self,prompt='',continue_prompt=False):
2220 """Write a prompt and read a line.
2251 """Write a prompt and read a line.
2221
2252
2222 The returned line does not include the trailing newline.
2253 The returned line does not include the trailing newline.
2223 When the user enters the EOF key sequence, EOFError is raised.
2254 When the user enters the EOF key sequence, EOFError is raised.
2224
2255
2225 Optional inputs:
2256 Optional inputs:
2226
2257
2227 - prompt(''): a string to be printed to prompt the user.
2258 - prompt(''): a string to be printed to prompt the user.
2228
2259
2229 - continue_prompt(False): whether this line is the first one or a
2260 - continue_prompt(False): whether this line is the first one or a
2230 continuation in a sequence of inputs.
2261 continuation in a sequence of inputs.
2231 """
2262 """
2232 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2263 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2233
2264
2234 # Code run by the user may have modified the readline completer state.
2265 # Code run by the user may have modified the readline completer state.
2235 # We must ensure that our completer is back in place.
2266 # We must ensure that our completer is back in place.
2236
2267
2237 if self.has_readline:
2268 if self.has_readline:
2238 self.set_completer()
2269 self.set_completer()
2239
2270
2240 try:
2271 try:
2241 line = raw_input_original(prompt).decode(self.stdin_encoding)
2272 line = raw_input_original(prompt).decode(self.stdin_encoding)
2242 except ValueError:
2273 except ValueError:
2243 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2274 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2244 " or sys.stdout.close()!\nExiting IPython!")
2275 " or sys.stdout.close()!\nExiting IPython!")
2245 self.ask_exit()
2276 self.ask_exit()
2246 return ""
2277 return ""
2247
2278
2248 # Try to be reasonably smart about not re-indenting pasted input more
2279 # Try to be reasonably smart about not re-indenting pasted input more
2249 # than necessary. We do this by trimming out the auto-indent initial
2280 # than necessary. We do this by trimming out the auto-indent initial
2250 # spaces, if the user's actual input started itself with whitespace.
2281 # spaces, if the user's actual input started itself with whitespace.
2251 #debugx('self.buffer[-1]')
2282 #debugx('self.buffer[-1]')
2252
2283
2253 if self.autoindent:
2284 if self.autoindent:
2254 if num_ini_spaces(line) > self.indent_current_nsp:
2285 if num_ini_spaces(line) > self.indent_current_nsp:
2255 line = line[self.indent_current_nsp:]
2286 line = line[self.indent_current_nsp:]
2256 self.indent_current_nsp = 0
2287 self.indent_current_nsp = 0
2257
2288
2258 # store the unfiltered input before the user has any chance to modify
2289 # store the unfiltered input before the user has any chance to modify
2259 # it.
2290 # it.
2260 if line.strip():
2291 if line.strip():
2261 if continue_prompt:
2292 if continue_prompt:
2262 self.input_hist_raw[-1] += '%s\n' % line
2293 self.input_hist_raw[-1] += '%s\n' % line
2263 if self.has_readline and self.readline_use:
2294 if self.has_readline and self.readline_use:
2264 try:
2295 try:
2265 histlen = self.readline.get_current_history_length()
2296 histlen = self.readline.get_current_history_length()
2266 if histlen > 1:
2297 if histlen > 1:
2267 newhist = self.input_hist_raw[-1].rstrip()
2298 newhist = self.input_hist_raw[-1].rstrip()
2268 self.readline.remove_history_item(histlen-1)
2299 self.readline.remove_history_item(histlen-1)
2269 self.readline.replace_history_item(histlen-2,
2300 self.readline.replace_history_item(histlen-2,
2270 newhist.encode(self.stdin_encoding))
2301 newhist.encode(self.stdin_encoding))
2271 except AttributeError:
2302 except AttributeError:
2272 pass # re{move,place}_history_item are new in 2.4.
2303 pass # re{move,place}_history_item are new in 2.4.
2273 else:
2304 else:
2274 self.input_hist_raw.append('%s\n' % line)
2305 self.input_hist_raw.append('%s\n' % line)
2275 # only entries starting at first column go to shadow history
2306 # only entries starting at first column go to shadow history
2276 if line.lstrip() == line:
2307 if line.lstrip() == line:
2277 self.shadowhist.add(line.strip())
2308 self.shadowhist.add(line.strip())
2278 elif not continue_prompt:
2309 elif not continue_prompt:
2279 self.input_hist_raw.append('\n')
2310 self.input_hist_raw.append('\n')
2280 try:
2311 try:
2281 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2312 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2282 except:
2313 except:
2283 # blanket except, in case a user-defined prefilter crashes, so it
2314 # blanket except, in case a user-defined prefilter crashes, so it
2284 # can't take all of ipython with it.
2315 # can't take all of ipython with it.
2285 self.showtraceback()
2316 self.showtraceback()
2286 return ''
2317 return ''
2287 else:
2318 else:
2288 return lineout
2319 return lineout
2289
2320
2290 #-------------------------------------------------------------------------
2321 #-------------------------------------------------------------------------
2291 # Working with components
2322 # Working with components
2292 #-------------------------------------------------------------------------
2323 #-------------------------------------------------------------------------
2293
2324
2294 def get_component(self, name=None, klass=None):
2325 def get_component(self, name=None, klass=None):
2295 """Fetch a component by name and klass in my tree."""
2326 """Fetch a component by name and klass in my tree."""
2296 c = Component.get_instances(root=self, name=name, klass=klass)
2327 c = Component.get_instances(root=self, name=name, klass=klass)
2297 if len(c) == 0:
2328 if len(c) == 0:
2298 return None
2329 return None
2299 if len(c) == 1:
2330 if len(c) == 1:
2300 return c[0]
2331 return c[0]
2301 else:
2332 else:
2302 return c
2333 return c
2303
2334
2304 #-------------------------------------------------------------------------
2335 #-------------------------------------------------------------------------
2305 # IPython extensions
2336 # IPython extensions
2306 #-------------------------------------------------------------------------
2337 #-------------------------------------------------------------------------
2307
2338
2308 def load_extension(self, module_str):
2339 def load_extension(self, module_str):
2309 """Load an IPython extension by its module name.
2340 """Load an IPython extension by its module name.
2310
2341
2311 An IPython extension is an importable Python module that has
2342 An IPython extension is an importable Python module that has
2312 a function with the signature::
2343 a function with the signature::
2313
2344
2314 def load_ipython_extension(ipython):
2345 def load_ipython_extension(ipython):
2315 # Do things with ipython
2346 # Do things with ipython
2316
2347
2317 This function is called after your extension is imported and the
2348 This function is called after your extension is imported and the
2318 currently active :class:`InteractiveShell` instance is passed as
2349 currently active :class:`InteractiveShell` instance is passed as
2319 the only argument. You can do anything you want with IPython at
2350 the only argument. You can do anything you want with IPython at
2320 that point, including defining new magic and aliases, adding new
2351 that point, including defining new magic and aliases, adding new
2321 components, etc.
2352 components, etc.
2322
2353
2323 The :func:`load_ipython_extension` will be called again is you
2354 The :func:`load_ipython_extension` will be called again is you
2324 load or reload the extension again. It is up to the extension
2355 load or reload the extension again. It is up to the extension
2325 author to add code to manage that.
2356 author to add code to manage that.
2326
2357
2327 You can put your extension modules anywhere you want, as long as
2358 You can put your extension modules anywhere you want, as long as
2328 they can be imported by Python's standard import mechanism. However,
2359 they can be imported by Python's standard import mechanism. However,
2329 to make it easy to write extensions, you can also put your extensions
2360 to make it easy to write extensions, you can also put your extensions
2330 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2361 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2331 is added to ``sys.path`` automatically.
2362 is added to ``sys.path`` automatically.
2363
2364 If :func:`load_ipython_extension` returns anything, this function
2365 will return that object.
2332 """
2366 """
2333 from IPython.utils.syspathcontext import prepended_to_syspath
2367 from IPython.utils.syspathcontext import prepended_to_syspath
2334
2368
2335 if module_str not in sys.modules:
2369 if module_str not in sys.modules:
2336 with prepended_to_syspath(self.ipython_extension_dir):
2370 with prepended_to_syspath(self.ipython_extension_dir):
2337 __import__(module_str)
2371 __import__(module_str)
2338 mod = sys.modules[module_str]
2372 mod = sys.modules[module_str]
2339 self._call_load_ipython_extension(mod)
2373 return self._call_load_ipython_extension(mod)
2340
2374
2341 def unload_extension(self, module_str):
2375 def unload_extension(self, module_str):
2342 """Unload an IPython extension by its module name.
2376 """Unload an IPython extension by its module name.
2343
2377
2344 This function looks up the extension's name in ``sys.modules`` and
2378 This function looks up the extension's name in ``sys.modules`` and
2345 simply calls ``mod.unload_ipython_extension(self)``.
2379 simply calls ``mod.unload_ipython_extension(self)``.
2346 """
2380 """
2347 if module_str in sys.modules:
2381 if module_str in sys.modules:
2348 mod = sys.modules[module_str]
2382 mod = sys.modules[module_str]
2349 self._call_unload_ipython_extension(mod)
2383 self._call_unload_ipython_extension(mod)
2350
2384
2351 def reload_extension(self, module_str):
2385 def reload_extension(self, module_str):
2352 """Reload an IPython extension by calling reload.
2386 """Reload an IPython extension by calling reload.
2353
2387
2354 If the module has not been loaded before,
2388 If the module has not been loaded before,
2355 :meth:`InteractiveShell.load_extension` is called. Otherwise
2389 :meth:`InteractiveShell.load_extension` is called. Otherwise
2356 :func:`reload` is called and then the :func:`load_ipython_extension`
2390 :func:`reload` is called and then the :func:`load_ipython_extension`
2357 function of the module, if it exists is called.
2391 function of the module, if it exists is called.
2358 """
2392 """
2359 from IPython.utils.syspathcontext import prepended_to_syspath
2393 from IPython.utils.syspathcontext import prepended_to_syspath
2360
2394
2361 with prepended_to_syspath(self.ipython_extension_dir):
2395 with prepended_to_syspath(self.ipython_extension_dir):
2362 if module_str in sys.modules:
2396 if module_str in sys.modules:
2363 mod = sys.modules[module_str]
2397 mod = sys.modules[module_str]
2364 reload(mod)
2398 reload(mod)
2365 self._call_load_ipython_extension(mod)
2399 self._call_load_ipython_extension(mod)
2366 else:
2400 else:
2367 self.load_extension(module_str)
2401 self.load_extension(module_str)
2368
2402
2369 def _call_load_ipython_extension(self, mod):
2403 def _call_load_ipython_extension(self, mod):
2370 if hasattr(mod, 'load_ipython_extension'):
2404 if hasattr(mod, 'load_ipython_extension'):
2371 mod.load_ipython_extension(self)
2405 return mod.load_ipython_extension(self)
2372
2406
2373 def _call_unload_ipython_extension(self, mod):
2407 def _call_unload_ipython_extension(self, mod):
2374 if hasattr(mod, 'unload_ipython_extension'):
2408 if hasattr(mod, 'unload_ipython_extension'):
2375 mod.unload_ipython_extension(self)
2409 return mod.unload_ipython_extension(self)
2376
2410
2377 #-------------------------------------------------------------------------
2411 #-------------------------------------------------------------------------
2378 # Things related to the prefilter
2412 # Things related to the prefilter
2379 #-------------------------------------------------------------------------
2413 #-------------------------------------------------------------------------
2380
2414
2381 def init_prefilter(self):
2415 def init_prefilter(self):
2382 self.prefilter_manager = PrefilterManager(self, config=self.config)
2416 self.prefilter_manager = PrefilterManager(self, config=self.config)
2417 # Ultimately this will be refactored in the new interpreter code, but
2418 # for now, we should expose the main prefilter method (there's legacy
2419 # code out there that may rely on this).
2420 self.prefilter = self.prefilter_manager.prefilter_lines
2383
2421
2384 #-------------------------------------------------------------------------
2422 #-------------------------------------------------------------------------
2385 # Utilities
2423 # Utilities
2386 #-------------------------------------------------------------------------
2424 #-------------------------------------------------------------------------
2387
2425
2388 def getoutput(self, cmd):
2426 def getoutput(self, cmd):
2389 return getoutput(self.var_expand(cmd,depth=2),
2427 return getoutput(self.var_expand(cmd,depth=2),
2390 header=self.system_header,
2428 header=self.system_header,
2391 verbose=self.system_verbose)
2429 verbose=self.system_verbose)
2392
2430
2393 def getoutputerror(self, cmd):
2431 def getoutputerror(self, cmd):
2394 return getoutputerror(self.var_expand(cmd,depth=2),
2432 return getoutputerror(self.var_expand(cmd,depth=2),
2395 header=self.system_header,
2433 header=self.system_header,
2396 verbose=self.system_verbose)
2434 verbose=self.system_verbose)
2397
2435
2398 def var_expand(self,cmd,depth=0):
2436 def var_expand(self,cmd,depth=0):
2399 """Expand python variables in a string.
2437 """Expand python variables in a string.
2400
2438
2401 The depth argument indicates how many frames above the caller should
2439 The depth argument indicates how many frames above the caller should
2402 be walked to look for the local namespace where to expand variables.
2440 be walked to look for the local namespace where to expand variables.
2403
2441
2404 The global namespace for expansion is always the user's interactive
2442 The global namespace for expansion is always the user's interactive
2405 namespace.
2443 namespace.
2406 """
2444 """
2407
2445
2408 return str(ItplNS(cmd,
2446 return str(ItplNS(cmd,
2409 self.user_ns, # globals
2447 self.user_ns, # globals
2410 # Skip our own frame in searching for locals:
2448 # Skip our own frame in searching for locals:
2411 sys._getframe(depth+1).f_locals # locals
2449 sys._getframe(depth+1).f_locals # locals
2412 ))
2450 ))
2413
2451
2414 def mktempfile(self,data=None):
2452 def mktempfile(self,data=None):
2415 """Make a new tempfile and return its filename.
2453 """Make a new tempfile and return its filename.
2416
2454
2417 This makes a call to tempfile.mktemp, but it registers the created
2455 This makes a call to tempfile.mktemp, but it registers the created
2418 filename internally so ipython cleans it up at exit time.
2456 filename internally so ipython cleans it up at exit time.
2419
2457
2420 Optional inputs:
2458 Optional inputs:
2421
2459
2422 - data(None): if data is given, it gets written out to the temp file
2460 - data(None): if data is given, it gets written out to the temp file
2423 immediately, and the file is closed again."""
2461 immediately, and the file is closed again."""
2424
2462
2425 filename = tempfile.mktemp('.py','ipython_edit_')
2463 filename = tempfile.mktemp('.py','ipython_edit_')
2426 self.tempfiles.append(filename)
2464 self.tempfiles.append(filename)
2427
2465
2428 if data:
2466 if data:
2429 tmp_file = open(filename,'w')
2467 tmp_file = open(filename,'w')
2430 tmp_file.write(data)
2468 tmp_file.write(data)
2431 tmp_file.close()
2469 tmp_file.close()
2432 return filename
2470 return filename
2433
2471
2434 def write(self,data):
2472 def write(self,data):
2435 """Write a string to the default output"""
2473 """Write a string to the default output"""
2436 Term.cout.write(data)
2474 Term.cout.write(data)
2437
2475
2438 def write_err(self,data):
2476 def write_err(self,data):
2439 """Write a string to the default error output"""
2477 """Write a string to the default error output"""
2440 Term.cerr.write(data)
2478 Term.cerr.write(data)
2441
2479
2442 def ask_yes_no(self,prompt,default=True):
2480 def ask_yes_no(self,prompt,default=True):
2443 if self.quiet:
2481 if self.quiet:
2444 return True
2482 return True
2445 return ask_yes_no(prompt,default)
2483 return ask_yes_no(prompt,default)
2446
2484
2447 #-------------------------------------------------------------------------
2485 #-------------------------------------------------------------------------
2486 # Things related to GUI support and pylab
2487 #-------------------------------------------------------------------------
2488
2489 def enable_pylab(self, gui=None):
2490 """Activate pylab support at runtime.
2491
2492 This turns on support for matplotlib, preloads into the interactive
2493 namespace all of numpy and pylab, and configures IPython to correcdtly
2494 interact with the GUI event loop. The GUI backend to be used can be
2495 optionally selected with the optional :param:`gui` argument.
2496
2497 Parameters
2498 ----------
2499 gui : optional, string
2500
2501 If given, dictates the choice of matplotlib GUI backend to use
2502 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2503 'gtk'), otherwise we use the default chosen by matplotlib (as
2504 dictated by the matplotlib build-time options plus the user's
2505 matplotlibrc configuration file).
2506 """
2507 # We want to prevent the loading of pylab to pollute the user's
2508 # namespace as shown by the %who* magics, so we execute the activation
2509 # code in an empty namespace, and we update *both* user_ns and
2510 # user_ns_hidden with this information.
2511 ns = {}
2512 gui = pylab_activate(ns, gui)
2513 self.user_ns.update(ns)
2514 self.user_ns_hidden.update(ns)
2515 # Now we must activate the gui pylab wants to use, and fix %run to take
2516 # plot updates into account
2517 enable_gui(gui)
2518 self.magic_run = self._pylab_magic_run
2519
2520 #-------------------------------------------------------------------------
2448 # Things related to IPython exiting
2521 # Things related to IPython exiting
2449 #-------------------------------------------------------------------------
2522 #-------------------------------------------------------------------------
2450
2523
2451 def ask_exit(self):
2524 def ask_exit(self):
2452 """ Call for exiting. Can be overiden and used as a callback. """
2525 """ Ask the shell to exit. Can be overiden and used as a callback. """
2453 self.exit_now = True
2526 self.exit_now = True
2454
2527
2455 def exit(self):
2528 def exit(self):
2456 """Handle interactive exit.
2529 """Handle interactive exit.
2457
2530
2458 This method calls the ask_exit callback."""
2531 This method calls the ask_exit callback."""
2459 if self.confirm_exit:
2532 if self.confirm_exit:
2460 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2533 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2461 self.ask_exit()
2534 self.ask_exit()
2462 else:
2535 else:
2463 self.ask_exit()
2536 self.ask_exit()
2464
2537
2465 def atexit_operations(self):
2538 def atexit_operations(self):
2466 """This will be executed at the time of exit.
2539 """This will be executed at the time of exit.
2467
2540
2468 Saving of persistent data should be performed here.
2541 Saving of persistent data should be performed here.
2469 """
2542 """
2470 self.savehist()
2543 self.savehist()
2471
2544
2472 # Cleanup all tempfiles left around
2545 # Cleanup all tempfiles left around
2473 for tfile in self.tempfiles:
2546 for tfile in self.tempfiles:
2474 try:
2547 try:
2475 os.unlink(tfile)
2548 os.unlink(tfile)
2476 except OSError:
2549 except OSError:
2477 pass
2550 pass
2478
2551
2479 # Clear all user namespaces to release all references cleanly.
2552 # Clear all user namespaces to release all references cleanly.
2480 self.reset()
2553 self.reset()
2481
2554
2482 # Run user hooks
2555 # Run user hooks
2483 self.hooks.shutdown_hook()
2556 self.hooks.shutdown_hook()
2484
2557
2485 def cleanup(self):
2558 def cleanup(self):
2486 self.restore_sys_module_state()
2559 self.restore_sys_module_state()
2487
2560
2488
2561
@@ -1,41 +1,41 b''
1 """Support for interactive macros in IPython"""
1 """Support for interactive macros in IPython"""
2
2
3 #*****************************************************************************
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
8 #*****************************************************************************
9
9
10 from IPython.utils.genutils import Term
10 from IPython.utils.io import Term
11 from IPython.core.autocall import IPyAutocall
11 from IPython.core.autocall import IPyAutocall
12
12
13 class Macro(IPyAutocall):
13 class Macro(IPyAutocall):
14 """Simple class to store the value of macros as strings.
14 """Simple class to store the value of macros as strings.
15
15
16 Macro is just a callable that executes a string of IPython
16 Macro is just a callable that executes a string of IPython
17 input when called.
17 input when called.
18
18
19 Args to macro are available in _margv list if you need them.
19 Args to macro are available in _margv list if you need them.
20 """
20 """
21
21
22 def __init__(self,data):
22 def __init__(self,data):
23
23
24 # store the macro value, as a single string which can be evaluated by
24 # store the macro value, as a single string which can be evaluated by
25 # runlines()
25 # runlines()
26 self.value = ''.join(data).rstrip()+'\n'
26 self.value = ''.join(data).rstrip()+'\n'
27
27
28 def __str__(self):
28 def __str__(self):
29 return self.value
29 return self.value
30
30
31 def __repr__(self):
31 def __repr__(self):
32 return 'IPython.macro.Macro(%s)' % repr(self.value)
32 return 'IPython.macro.Macro(%s)' % repr(self.value)
33
33
34 def __call__(self,*args):
34 def __call__(self,*args):
35 Term.cout.flush()
35 Term.cout.flush()
36 self._ip.user_ns['_margv'] = args
36 self._ip.user_ns['_margv'] = args
37 self._ip.runlines(self.value)
37 self._ip.runlines(self.value)
38
38
39 def __getstate__(self):
39 def __getstate__(self):
40 """ needed for safe pickling via %store """
40 """ needed for safe pickling via %store """
41 return {'value': self.value}
41 return {'value': self.value}
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,608 +1,609 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
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 __all__ = ['Inspector','InspectColors']
17 __all__ = ['Inspector','InspectColors']
18
18
19 # stdlib modules
19 # stdlib modules
20 import __builtin__
20 import __builtin__
21 import StringIO
21 import StringIO
22 import inspect
22 import inspect
23 import linecache
23 import linecache
24 import os
24 import os
25 import string
25 import string
26 import sys
26 import sys
27 import types
27 import types
28
28
29 # IPython's own
29 # IPython's own
30 from IPython.utils import PyColorize
31 from IPython.utils.genutils import indent, Term
32 from IPython.core.page import page
30 from IPython.core.page import page
33 from IPython.external.Itpl import itpl
31 from IPython.external.Itpl import itpl
32 from IPython.utils import PyColorize
33 from IPython.utils.io import Term
34 from IPython.utils.text import indent
34 from IPython.utils.wildcard import list_namespace
35 from IPython.utils.wildcard import list_namespace
35 from IPython.utils.coloransi import *
36 from IPython.utils.coloransi import *
36
37
37 #****************************************************************************
38 #****************************************************************************
38 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
39 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
39 # simply monkeypatch inspect with code copied from python 2.4.
40 # simply monkeypatch inspect with code copied from python 2.4.
40 if sys.version_info[:2] == (2,3):
41 if sys.version_info[:2] == (2,3):
41 from inspect import ismodule, getabsfile, modulesbyfile
42 from inspect import ismodule, getabsfile, modulesbyfile
42 def getmodule(object):
43 def getmodule(object):
43 """Return the module an object was defined in, or None if not found."""
44 """Return the module an object was defined in, or None if not found."""
44 if ismodule(object):
45 if ismodule(object):
45 return object
46 return object
46 if hasattr(object, '__module__'):
47 if hasattr(object, '__module__'):
47 return sys.modules.get(object.__module__)
48 return sys.modules.get(object.__module__)
48 try:
49 try:
49 file = getabsfile(object)
50 file = getabsfile(object)
50 except TypeError:
51 except TypeError:
51 return None
52 return None
52 if file in modulesbyfile:
53 if file in modulesbyfile:
53 return sys.modules.get(modulesbyfile[file])
54 return sys.modules.get(modulesbyfile[file])
54 for module in sys.modules.values():
55 for module in sys.modules.values():
55 if hasattr(module, '__file__'):
56 if hasattr(module, '__file__'):
56 modulesbyfile[
57 modulesbyfile[
57 os.path.realpath(
58 os.path.realpath(
58 getabsfile(module))] = module.__name__
59 getabsfile(module))] = module.__name__
59 if file in modulesbyfile:
60 if file in modulesbyfile:
60 return sys.modules.get(modulesbyfile[file])
61 return sys.modules.get(modulesbyfile[file])
61 main = sys.modules['__main__']
62 main = sys.modules['__main__']
62 if not hasattr(object, '__name__'):
63 if not hasattr(object, '__name__'):
63 return None
64 return None
64 if hasattr(main, object.__name__):
65 if hasattr(main, object.__name__):
65 mainobject = getattr(main, object.__name__)
66 mainobject = getattr(main, object.__name__)
66 if mainobject is object:
67 if mainobject is object:
67 return main
68 return main
68 builtin = sys.modules['__builtin__']
69 builtin = sys.modules['__builtin__']
69 if hasattr(builtin, object.__name__):
70 if hasattr(builtin, object.__name__):
70 builtinobject = getattr(builtin, object.__name__)
71 builtinobject = getattr(builtin, object.__name__)
71 if builtinobject is object:
72 if builtinobject is object:
72 return builtin
73 return builtin
73
74
74 inspect.getmodule = getmodule
75 inspect.getmodule = getmodule
75
76
76 #****************************************************************************
77 #****************************************************************************
77 # Builtin color schemes
78 # Builtin color schemes
78
79
79 Colors = TermColors # just a shorthand
80 Colors = TermColors # just a shorthand
80
81
81 # Build a few color schemes
82 # Build a few color schemes
82 NoColor = ColorScheme(
83 NoColor = ColorScheme(
83 'NoColor',{
84 'NoColor',{
84 'header' : Colors.NoColor,
85 'header' : Colors.NoColor,
85 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
86 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
86 } )
87 } )
87
88
88 LinuxColors = ColorScheme(
89 LinuxColors = ColorScheme(
89 'Linux',{
90 'Linux',{
90 'header' : Colors.LightRed,
91 'header' : Colors.LightRed,
91 'normal' : Colors.Normal # color off (usu. Colors.Normal)
92 'normal' : Colors.Normal # color off (usu. Colors.Normal)
92 } )
93 } )
93
94
94 LightBGColors = ColorScheme(
95 LightBGColors = ColorScheme(
95 'LightBG',{
96 'LightBG',{
96 'header' : Colors.Red,
97 'header' : Colors.Red,
97 'normal' : Colors.Normal # color off (usu. Colors.Normal)
98 'normal' : Colors.Normal # color off (usu. Colors.Normal)
98 } )
99 } )
99
100
100 # Build table of color schemes (needed by the parser)
101 # Build table of color schemes (needed by the parser)
101 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
102 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
102 'Linux')
103 'Linux')
103
104
104 #****************************************************************************
105 #****************************************************************************
105 # Auxiliary functions
106 # Auxiliary functions
106 def getdoc(obj):
107 def getdoc(obj):
107 """Stable wrapper around inspect.getdoc.
108 """Stable wrapper around inspect.getdoc.
108
109
109 This can't crash because of attribute problems.
110 This can't crash because of attribute problems.
110
111
111 It also attempts to call a getdoc() method on the given object. This
112 It also attempts to call a getdoc() method on the given object. This
112 allows objects which provide their docstrings via non-standard mechanisms
113 allows objects which provide their docstrings via non-standard mechanisms
113 (like Pyro proxies) to still be inspected by ipython's ? system."""
114 (like Pyro proxies) to still be inspected by ipython's ? system."""
114
115
115 ds = None # default return value
116 ds = None # default return value
116 try:
117 try:
117 ds = inspect.getdoc(obj)
118 ds = inspect.getdoc(obj)
118 except:
119 except:
119 # Harden against an inspect failure, which can occur with
120 # Harden against an inspect failure, which can occur with
120 # SWIG-wrapped extensions.
121 # SWIG-wrapped extensions.
121 pass
122 pass
122 # Allow objects to offer customized documentation via a getdoc method:
123 # Allow objects to offer customized documentation via a getdoc method:
123 try:
124 try:
124 ds2 = obj.getdoc()
125 ds2 = obj.getdoc()
125 except:
126 except:
126 pass
127 pass
127 else:
128 else:
128 # if we get extra info, we add it to the normal docstring.
129 # if we get extra info, we add it to the normal docstring.
129 if ds is None:
130 if ds is None:
130 ds = ds2
131 ds = ds2
131 else:
132 else:
132 ds = '%s\n%s' % (ds,ds2)
133 ds = '%s\n%s' % (ds,ds2)
133 return ds
134 return ds
134
135
135
136
136 def getsource(obj,is_binary=False):
137 def getsource(obj,is_binary=False):
137 """Wrapper around inspect.getsource.
138 """Wrapper around inspect.getsource.
138
139
139 This can be modified by other projects to provide customized source
140 This can be modified by other projects to provide customized source
140 extraction.
141 extraction.
141
142
142 Inputs:
143 Inputs:
143
144
144 - obj: an object whose source code we will attempt to extract.
145 - obj: an object whose source code we will attempt to extract.
145
146
146 Optional inputs:
147 Optional inputs:
147
148
148 - is_binary: whether the object is known to come from a binary source.
149 - is_binary: whether the object is known to come from a binary source.
149 This implementation will skip returning any output for binary objects, but
150 This implementation will skip returning any output for binary objects, but
150 custom extractors may know how to meaningfully process them."""
151 custom extractors may know how to meaningfully process them."""
151
152
152 if is_binary:
153 if is_binary:
153 return None
154 return None
154 else:
155 else:
155 try:
156 try:
156 src = inspect.getsource(obj)
157 src = inspect.getsource(obj)
157 except TypeError:
158 except TypeError:
158 if hasattr(obj,'__class__'):
159 if hasattr(obj,'__class__'):
159 src = inspect.getsource(obj.__class__)
160 src = inspect.getsource(obj.__class__)
160 return src
161 return src
161
162
162 def getargspec(obj):
163 def getargspec(obj):
163 """Get the names and default values of a function's arguments.
164 """Get the names and default values of a function's arguments.
164
165
165 A tuple of four things is returned: (args, varargs, varkw, defaults).
166 A tuple of four things is returned: (args, varargs, varkw, defaults).
166 'args' is a list of the argument names (it may contain nested lists).
167 'args' is a list of the argument names (it may contain nested lists).
167 'varargs' and 'varkw' are the names of the * and ** arguments or None.
168 'varargs' and 'varkw' are the names of the * and ** arguments or None.
168 'defaults' is an n-tuple of the default values of the last n arguments.
169 'defaults' is an n-tuple of the default values of the last n arguments.
169
170
170 Modified version of inspect.getargspec from the Python Standard
171 Modified version of inspect.getargspec from the Python Standard
171 Library."""
172 Library."""
172
173
173 if inspect.isfunction(obj):
174 if inspect.isfunction(obj):
174 func_obj = obj
175 func_obj = obj
175 elif inspect.ismethod(obj):
176 elif inspect.ismethod(obj):
176 func_obj = obj.im_func
177 func_obj = obj.im_func
177 else:
178 else:
178 raise TypeError, 'arg is not a Python function'
179 raise TypeError, 'arg is not a Python function'
179 args, varargs, varkw = inspect.getargs(func_obj.func_code)
180 args, varargs, varkw = inspect.getargs(func_obj.func_code)
180 return args, varargs, varkw, func_obj.func_defaults
181 return args, varargs, varkw, func_obj.func_defaults
181
182
182 #****************************************************************************
183 #****************************************************************************
183 # Class definitions
184 # Class definitions
184
185
185 class myStringIO(StringIO.StringIO):
186 class myStringIO(StringIO.StringIO):
186 """Adds a writeln method to normal StringIO."""
187 """Adds a writeln method to normal StringIO."""
187 def writeln(self,*arg,**kw):
188 def writeln(self,*arg,**kw):
188 """Does a write() and then a write('\n')"""
189 """Does a write() and then a write('\n')"""
189 self.write(*arg,**kw)
190 self.write(*arg,**kw)
190 self.write('\n')
191 self.write('\n')
191
192
192
193
193 class Inspector:
194 class Inspector:
194 def __init__(self,color_table,code_color_table,scheme,
195 def __init__(self,color_table,code_color_table,scheme,
195 str_detail_level=0):
196 str_detail_level=0):
196 self.color_table = color_table
197 self.color_table = color_table
197 self.parser = PyColorize.Parser(code_color_table,out='str')
198 self.parser = PyColorize.Parser(code_color_table,out='str')
198 self.format = self.parser.format
199 self.format = self.parser.format
199 self.str_detail_level = str_detail_level
200 self.str_detail_level = str_detail_level
200 self.set_active_scheme(scheme)
201 self.set_active_scheme(scheme)
201
202
202 def __getdef(self,obj,oname=''):
203 def __getdef(self,obj,oname=''):
203 """Return the definition header for any callable object.
204 """Return the definition header for any callable object.
204
205
205 If any exception is generated, None is returned instead and the
206 If any exception is generated, None is returned instead and the
206 exception is suppressed."""
207 exception is suppressed."""
207
208
208 try:
209 try:
209 return oname + inspect.formatargspec(*getargspec(obj))
210 return oname + inspect.formatargspec(*getargspec(obj))
210 except:
211 except:
211 return None
212 return None
212
213
213 def __head(self,h):
214 def __head(self,h):
214 """Return a header string with proper colors."""
215 """Return a header string with proper colors."""
215 return '%s%s%s' % (self.color_table.active_colors.header,h,
216 return '%s%s%s' % (self.color_table.active_colors.header,h,
216 self.color_table.active_colors.normal)
217 self.color_table.active_colors.normal)
217
218
218 def set_active_scheme(self,scheme):
219 def set_active_scheme(self,scheme):
219 self.color_table.set_active_scheme(scheme)
220 self.color_table.set_active_scheme(scheme)
220 self.parser.color_table.set_active_scheme(scheme)
221 self.parser.color_table.set_active_scheme(scheme)
221
222
222 def noinfo(self,msg,oname):
223 def noinfo(self,msg,oname):
223 """Generic message when no information is found."""
224 """Generic message when no information is found."""
224 print 'No %s found' % msg,
225 print 'No %s found' % msg,
225 if oname:
226 if oname:
226 print 'for %s' % oname
227 print 'for %s' % oname
227 else:
228 else:
228 print
229 print
229
230
230 def pdef(self,obj,oname=''):
231 def pdef(self,obj,oname=''):
231 """Print the definition header for any callable object.
232 """Print the definition header for any callable object.
232
233
233 If the object is a class, print the constructor information."""
234 If the object is a class, print the constructor information."""
234
235
235 if not callable(obj):
236 if not callable(obj):
236 print 'Object is not callable.'
237 print 'Object is not callable.'
237 return
238 return
238
239
239 header = ''
240 header = ''
240
241
241 if inspect.isclass(obj):
242 if inspect.isclass(obj):
242 header = self.__head('Class constructor information:\n')
243 header = self.__head('Class constructor information:\n')
243 obj = obj.__init__
244 obj = obj.__init__
244 elif type(obj) is types.InstanceType:
245 elif type(obj) is types.InstanceType:
245 obj = obj.__call__
246 obj = obj.__call__
246
247
247 output = self.__getdef(obj,oname)
248 output = self.__getdef(obj,oname)
248 if output is None:
249 if output is None:
249 self.noinfo('definition header',oname)
250 self.noinfo('definition header',oname)
250 else:
251 else:
251 print >>Term.cout, header,self.format(output),
252 print >>Term.cout, header,self.format(output),
252
253
253 def pdoc(self,obj,oname='',formatter = None):
254 def pdoc(self,obj,oname='',formatter = None):
254 """Print the docstring for any object.
255 """Print the docstring for any object.
255
256
256 Optional:
257 Optional:
257 -formatter: a function to run the docstring through for specially
258 -formatter: a function to run the docstring through for specially
258 formatted docstrings."""
259 formatted docstrings."""
259
260
260 head = self.__head # so that itpl can find it even if private
261 head = self.__head # so that itpl can find it even if private
261 ds = getdoc(obj)
262 ds = getdoc(obj)
262 if formatter:
263 if formatter:
263 ds = formatter(ds)
264 ds = formatter(ds)
264 if inspect.isclass(obj):
265 if inspect.isclass(obj):
265 init_ds = getdoc(obj.__init__)
266 init_ds = getdoc(obj.__init__)
266 output = itpl('$head("Class Docstring:")\n'
267 output = itpl('$head("Class Docstring:")\n'
267 '$indent(ds)\n'
268 '$indent(ds)\n'
268 '$head("Constructor Docstring"):\n'
269 '$head("Constructor Docstring"):\n'
269 '$indent(init_ds)')
270 '$indent(init_ds)')
270 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
271 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
271 and hasattr(obj,'__call__'):
272 and hasattr(obj,'__call__'):
272 call_ds = getdoc(obj.__call__)
273 call_ds = getdoc(obj.__call__)
273 if call_ds:
274 if call_ds:
274 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
275 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
275 '$head("Calling Docstring:")\n$indent(call_ds)')
276 '$head("Calling Docstring:")\n$indent(call_ds)')
276 else:
277 else:
277 output = ds
278 output = ds
278 else:
279 else:
279 output = ds
280 output = ds
280 if output is None:
281 if output is None:
281 self.noinfo('documentation',oname)
282 self.noinfo('documentation',oname)
282 return
283 return
283 page(output)
284 page(output)
284
285
285 def psource(self,obj,oname=''):
286 def psource(self,obj,oname=''):
286 """Print the source code for an object."""
287 """Print the source code for an object."""
287
288
288 # Flush the source cache because inspect can return out-of-date source
289 # Flush the source cache because inspect can return out-of-date source
289 linecache.checkcache()
290 linecache.checkcache()
290 try:
291 try:
291 src = getsource(obj)
292 src = getsource(obj)
292 except:
293 except:
293 self.noinfo('source',oname)
294 self.noinfo('source',oname)
294 else:
295 else:
295 page(self.format(src))
296 page(self.format(src))
296
297
297 def pfile(self,obj,oname=''):
298 def pfile(self,obj,oname=''):
298 """Show the whole file where an object was defined."""
299 """Show the whole file where an object was defined."""
299
300
300 try:
301 try:
301 try:
302 try:
302 lineno = inspect.getsourcelines(obj)[1]
303 lineno = inspect.getsourcelines(obj)[1]
303 except TypeError:
304 except TypeError:
304 # For instances, try the class object like getsource() does
305 # For instances, try the class object like getsource() does
305 if hasattr(obj,'__class__'):
306 if hasattr(obj,'__class__'):
306 lineno = inspect.getsourcelines(obj.__class__)[1]
307 lineno = inspect.getsourcelines(obj.__class__)[1]
307 # Adjust the inspected object so getabsfile() below works
308 # Adjust the inspected object so getabsfile() below works
308 obj = obj.__class__
309 obj = obj.__class__
309 except:
310 except:
310 self.noinfo('file',oname)
311 self.noinfo('file',oname)
311 return
312 return
312
313
313 # We only reach this point if object was successfully queried
314 # We only reach this point if object was successfully queried
314
315
315 # run contents of file through pager starting at line
316 # run contents of file through pager starting at line
316 # where the object is defined
317 # where the object is defined
317 ofile = inspect.getabsfile(obj)
318 ofile = inspect.getabsfile(obj)
318
319
319 if (ofile.endswith('.so') or ofile.endswith('.dll')):
320 if (ofile.endswith('.so') or ofile.endswith('.dll')):
320 print 'File %r is binary, not printing.' % ofile
321 print 'File %r is binary, not printing.' % ofile
321 elif not os.path.isfile(ofile):
322 elif not os.path.isfile(ofile):
322 print 'File %r does not exist, not printing.' % ofile
323 print 'File %r does not exist, not printing.' % ofile
323 else:
324 else:
324 # Print only text files, not extension binaries. Note that
325 # Print only text files, not extension binaries. Note that
325 # getsourcelines returns lineno with 1-offset and page() uses
326 # getsourcelines returns lineno with 1-offset and page() uses
326 # 0-offset, so we must adjust.
327 # 0-offset, so we must adjust.
327 page(self.format(open(ofile).read()),lineno-1)
328 page(self.format(open(ofile).read()),lineno-1)
328
329
329 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
330 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
330 """Show detailed information about an object.
331 """Show detailed information about an object.
331
332
332 Optional arguments:
333 Optional arguments:
333
334
334 - oname: name of the variable pointing to the object.
335 - oname: name of the variable pointing to the object.
335
336
336 - formatter: special formatter for docstrings (see pdoc)
337 - formatter: special formatter for docstrings (see pdoc)
337
338
338 - info: a structure with some information fields which may have been
339 - info: a structure with some information fields which may have been
339 precomputed already.
340 precomputed already.
340
341
341 - detail_level: if set to 1, more information is given.
342 - detail_level: if set to 1, more information is given.
342 """
343 """
343
344
344 obj_type = type(obj)
345 obj_type = type(obj)
345
346
346 header = self.__head
347 header = self.__head
347 if info is None:
348 if info is None:
348 ismagic = 0
349 ismagic = 0
349 isalias = 0
350 isalias = 0
350 ospace = ''
351 ospace = ''
351 else:
352 else:
352 ismagic = info.ismagic
353 ismagic = info.ismagic
353 isalias = info.isalias
354 isalias = info.isalias
354 ospace = info.namespace
355 ospace = info.namespace
355 # Get docstring, special-casing aliases:
356 # Get docstring, special-casing aliases:
356 if isalias:
357 if isalias:
357 if not callable(obj):
358 if not callable(obj):
358 try:
359 try:
359 ds = "Alias to the system command:\n %s" % obj[1]
360 ds = "Alias to the system command:\n %s" % obj[1]
360 except:
361 except:
361 ds = "Alias: " + str(obj)
362 ds = "Alias: " + str(obj)
362 else:
363 else:
363 ds = "Alias to " + str(obj)
364 ds = "Alias to " + str(obj)
364 if obj.__doc__:
365 if obj.__doc__:
365 ds += "\nDocstring:\n" + obj.__doc__
366 ds += "\nDocstring:\n" + obj.__doc__
366 else:
367 else:
367 ds = getdoc(obj)
368 ds = getdoc(obj)
368 if ds is None:
369 if ds is None:
369 ds = '<no docstring>'
370 ds = '<no docstring>'
370 if formatter is not None:
371 if formatter is not None:
371 ds = formatter(ds)
372 ds = formatter(ds)
372
373
373 # store output in a list which gets joined with \n at the end.
374 # store output in a list which gets joined with \n at the end.
374 out = myStringIO()
375 out = myStringIO()
375
376
376 string_max = 200 # max size of strings to show (snipped if longer)
377 string_max = 200 # max size of strings to show (snipped if longer)
377 shalf = int((string_max -5)/2)
378 shalf = int((string_max -5)/2)
378
379
379 if ismagic:
380 if ismagic:
380 obj_type_name = 'Magic function'
381 obj_type_name = 'Magic function'
381 elif isalias:
382 elif isalias:
382 obj_type_name = 'System alias'
383 obj_type_name = 'System alias'
383 else:
384 else:
384 obj_type_name = obj_type.__name__
385 obj_type_name = obj_type.__name__
385 out.writeln(header('Type:\t\t')+obj_type_name)
386 out.writeln(header('Type:\t\t')+obj_type_name)
386
387
387 try:
388 try:
388 bclass = obj.__class__
389 bclass = obj.__class__
389 out.writeln(header('Base Class:\t')+str(bclass))
390 out.writeln(header('Base Class:\t')+str(bclass))
390 except: pass
391 except: pass
391
392
392 # String form, but snip if too long in ? form (full in ??)
393 # String form, but snip if too long in ? form (full in ??)
393 if detail_level >= self.str_detail_level:
394 if detail_level >= self.str_detail_level:
394 try:
395 try:
395 ostr = str(obj)
396 ostr = str(obj)
396 str_head = 'String Form:'
397 str_head = 'String Form:'
397 if not detail_level and len(ostr)>string_max:
398 if not detail_level and len(ostr)>string_max:
398 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
399 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
399 ostr = ("\n" + " " * len(str_head.expandtabs())).\
400 ostr = ("\n" + " " * len(str_head.expandtabs())).\
400 join(map(string.strip,ostr.split("\n")))
401 join(map(string.strip,ostr.split("\n")))
401 if ostr.find('\n') > -1:
402 if ostr.find('\n') > -1:
402 # Print multi-line strings starting at the next line.
403 # Print multi-line strings starting at the next line.
403 str_sep = '\n'
404 str_sep = '\n'
404 else:
405 else:
405 str_sep = '\t'
406 str_sep = '\t'
406 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
407 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
407 except:
408 except:
408 pass
409 pass
409
410
410 if ospace:
411 if ospace:
411 out.writeln(header('Namespace:\t')+ospace)
412 out.writeln(header('Namespace:\t')+ospace)
412
413
413 # Length (for strings and lists)
414 # Length (for strings and lists)
414 try:
415 try:
415 length = str(len(obj))
416 length = str(len(obj))
416 out.writeln(header('Length:\t\t')+length)
417 out.writeln(header('Length:\t\t')+length)
417 except: pass
418 except: pass
418
419
419 # Filename where object was defined
420 # Filename where object was defined
420 binary_file = False
421 binary_file = False
421 try:
422 try:
422 try:
423 try:
423 fname = inspect.getabsfile(obj)
424 fname = inspect.getabsfile(obj)
424 except TypeError:
425 except TypeError:
425 # For an instance, the file that matters is where its class was
426 # For an instance, the file that matters is where its class was
426 # declared.
427 # declared.
427 if hasattr(obj,'__class__'):
428 if hasattr(obj,'__class__'):
428 fname = inspect.getabsfile(obj.__class__)
429 fname = inspect.getabsfile(obj.__class__)
429 if fname.endswith('<string>'):
430 if fname.endswith('<string>'):
430 fname = 'Dynamically generated function. No source code available.'
431 fname = 'Dynamically generated function. No source code available.'
431 if (fname.endswith('.so') or fname.endswith('.dll')):
432 if (fname.endswith('.so') or fname.endswith('.dll')):
432 binary_file = True
433 binary_file = True
433 out.writeln(header('File:\t\t')+fname)
434 out.writeln(header('File:\t\t')+fname)
434 except:
435 except:
435 # if anything goes wrong, we don't want to show source, so it's as
436 # if anything goes wrong, we don't want to show source, so it's as
436 # if the file was binary
437 # if the file was binary
437 binary_file = True
438 binary_file = True
438
439
439 # reconstruct the function definition and print it:
440 # reconstruct the function definition and print it:
440 defln = self.__getdef(obj,oname)
441 defln = self.__getdef(obj,oname)
441 if defln:
442 if defln:
442 out.write(header('Definition:\t')+self.format(defln))
443 out.write(header('Definition:\t')+self.format(defln))
443
444
444 # Docstrings only in detail 0 mode, since source contains them (we
445 # Docstrings only in detail 0 mode, since source contains them (we
445 # avoid repetitions). If source fails, we add them back, see below.
446 # avoid repetitions). If source fails, we add them back, see below.
446 if ds and detail_level == 0:
447 if ds and detail_level == 0:
447 out.writeln(header('Docstring:\n') + indent(ds))
448 out.writeln(header('Docstring:\n') + indent(ds))
448
449
449 # Original source code for any callable
450 # Original source code for any callable
450 if detail_level:
451 if detail_level:
451 # Flush the source cache because inspect can return out-of-date
452 # Flush the source cache because inspect can return out-of-date
452 # source
453 # source
453 linecache.checkcache()
454 linecache.checkcache()
454 source_success = False
455 source_success = False
455 try:
456 try:
456 try:
457 try:
457 src = getsource(obj,binary_file)
458 src = getsource(obj,binary_file)
458 except TypeError:
459 except TypeError:
459 if hasattr(obj,'__class__'):
460 if hasattr(obj,'__class__'):
460 src = getsource(obj.__class__,binary_file)
461 src = getsource(obj.__class__,binary_file)
461 if src is not None:
462 if src is not None:
462 source = self.format(src)
463 source = self.format(src)
463 out.write(header('Source:\n')+source.rstrip())
464 out.write(header('Source:\n')+source.rstrip())
464 source_success = True
465 source_success = True
465 except Exception, msg:
466 except Exception, msg:
466 pass
467 pass
467
468
468 if ds and not source_success:
469 if ds and not source_success:
469 out.writeln(header('Docstring [source file open failed]:\n')
470 out.writeln(header('Docstring [source file open failed]:\n')
470 + indent(ds))
471 + indent(ds))
471
472
472 # Constructor docstring for classes
473 # Constructor docstring for classes
473 if inspect.isclass(obj):
474 if inspect.isclass(obj):
474 # reconstruct the function definition and print it:
475 # reconstruct the function definition and print it:
475 try:
476 try:
476 obj_init = obj.__init__
477 obj_init = obj.__init__
477 except AttributeError:
478 except AttributeError:
478 init_def = init_ds = None
479 init_def = init_ds = None
479 else:
480 else:
480 init_def = self.__getdef(obj_init,oname)
481 init_def = self.__getdef(obj_init,oname)
481 init_ds = getdoc(obj_init)
482 init_ds = getdoc(obj_init)
482 # Skip Python's auto-generated docstrings
483 # Skip Python's auto-generated docstrings
483 if init_ds and \
484 if init_ds and \
484 init_ds.startswith('x.__init__(...) initializes'):
485 init_ds.startswith('x.__init__(...) initializes'):
485 init_ds = None
486 init_ds = None
486
487
487 if init_def or init_ds:
488 if init_def or init_ds:
488 out.writeln(header('\nConstructor information:'))
489 out.writeln(header('\nConstructor information:'))
489 if init_def:
490 if init_def:
490 out.write(header('Definition:\t')+ self.format(init_def))
491 out.write(header('Definition:\t')+ self.format(init_def))
491 if init_ds:
492 if init_ds:
492 out.writeln(header('Docstring:\n') + indent(init_ds))
493 out.writeln(header('Docstring:\n') + indent(init_ds))
493 # and class docstring for instances:
494 # and class docstring for instances:
494 elif obj_type is types.InstanceType or \
495 elif obj_type is types.InstanceType or \
495 isinstance(obj,object):
496 isinstance(obj,object):
496
497
497 # First, check whether the instance docstring is identical to the
498 # First, check whether the instance docstring is identical to the
498 # class one, and print it separately if they don't coincide. In
499 # class one, and print it separately if they don't coincide. In
499 # most cases they will, but it's nice to print all the info for
500 # most cases they will, but it's nice to print all the info for
500 # objects which use instance-customized docstrings.
501 # objects which use instance-customized docstrings.
501 if ds:
502 if ds:
502 try:
503 try:
503 cls = getattr(obj,'__class__')
504 cls = getattr(obj,'__class__')
504 except:
505 except:
505 class_ds = None
506 class_ds = None
506 else:
507 else:
507 class_ds = getdoc(cls)
508 class_ds = getdoc(cls)
508 # Skip Python's auto-generated docstrings
509 # Skip Python's auto-generated docstrings
509 if class_ds and \
510 if class_ds and \
510 (class_ds.startswith('function(code, globals[,') or \
511 (class_ds.startswith('function(code, globals[,') or \
511 class_ds.startswith('instancemethod(function, instance,') or \
512 class_ds.startswith('instancemethod(function, instance,') or \
512 class_ds.startswith('module(name[,') ):
513 class_ds.startswith('module(name[,') ):
513 class_ds = None
514 class_ds = None
514 if class_ds and ds != class_ds:
515 if class_ds and ds != class_ds:
515 out.writeln(header('Class Docstring:\n') +
516 out.writeln(header('Class Docstring:\n') +
516 indent(class_ds))
517 indent(class_ds))
517
518
518 # Next, try to show constructor docstrings
519 # Next, try to show constructor docstrings
519 try:
520 try:
520 init_ds = getdoc(obj.__init__)
521 init_ds = getdoc(obj.__init__)
521 # Skip Python's auto-generated docstrings
522 # Skip Python's auto-generated docstrings
522 if init_ds and \
523 if init_ds and \
523 init_ds.startswith('x.__init__(...) initializes'):
524 init_ds.startswith('x.__init__(...) initializes'):
524 init_ds = None
525 init_ds = None
525 except AttributeError:
526 except AttributeError:
526 init_ds = None
527 init_ds = None
527 if init_ds:
528 if init_ds:
528 out.writeln(header('Constructor Docstring:\n') +
529 out.writeln(header('Constructor Docstring:\n') +
529 indent(init_ds))
530 indent(init_ds))
530
531
531 # Call form docstring for callable instances
532 # Call form docstring for callable instances
532 if hasattr(obj,'__call__'):
533 if hasattr(obj,'__call__'):
533 #out.writeln(header('Callable:\t')+'Yes')
534 #out.writeln(header('Callable:\t')+'Yes')
534 call_def = self.__getdef(obj.__call__,oname)
535 call_def = self.__getdef(obj.__call__,oname)
535 #if call_def is None:
536 #if call_def is None:
536 # out.writeln(header('Call def:\t')+
537 # out.writeln(header('Call def:\t')+
537 # 'Calling definition not available.')
538 # 'Calling definition not available.')
538 if call_def is not None:
539 if call_def is not None:
539 out.writeln(header('Call def:\t')+self.format(call_def))
540 out.writeln(header('Call def:\t')+self.format(call_def))
540 call_ds = getdoc(obj.__call__)
541 call_ds = getdoc(obj.__call__)
541 # Skip Python's auto-generated docstrings
542 # Skip Python's auto-generated docstrings
542 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
543 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
543 call_ds = None
544 call_ds = None
544 if call_ds:
545 if call_ds:
545 out.writeln(header('Call docstring:\n') + indent(call_ds))
546 out.writeln(header('Call docstring:\n') + indent(call_ds))
546
547
547 # Finally send to printer/pager
548 # Finally send to printer/pager
548 output = out.getvalue()
549 output = out.getvalue()
549 if output:
550 if output:
550 page(output)
551 page(output)
551 # end pinfo
552 # end pinfo
552
553
553 def psearch(self,pattern,ns_table,ns_search=[],
554 def psearch(self,pattern,ns_table,ns_search=[],
554 ignore_case=False,show_all=False):
555 ignore_case=False,show_all=False):
555 """Search namespaces with wildcards for objects.
556 """Search namespaces with wildcards for objects.
556
557
557 Arguments:
558 Arguments:
558
559
559 - pattern: string containing shell-like wildcards to use in namespace
560 - pattern: string containing shell-like wildcards to use in namespace
560 searches and optionally a type specification to narrow the search to
561 searches and optionally a type specification to narrow the search to
561 objects of that type.
562 objects of that type.
562
563
563 - ns_table: dict of name->namespaces for search.
564 - ns_table: dict of name->namespaces for search.
564
565
565 Optional arguments:
566 Optional arguments:
566
567
567 - ns_search: list of namespace names to include in search.
568 - ns_search: list of namespace names to include in search.
568
569
569 - ignore_case(False): make the search case-insensitive.
570 - ignore_case(False): make the search case-insensitive.
570
571
571 - show_all(False): show all names, including those starting with
572 - show_all(False): show all names, including those starting with
572 underscores.
573 underscores.
573 """
574 """
574 #print 'ps pattern:<%r>' % pattern # dbg
575 #print 'ps pattern:<%r>' % pattern # dbg
575
576
576 # defaults
577 # defaults
577 type_pattern = 'all'
578 type_pattern = 'all'
578 filter = ''
579 filter = ''
579
580
580 cmds = pattern.split()
581 cmds = pattern.split()
581 len_cmds = len(cmds)
582 len_cmds = len(cmds)
582 if len_cmds == 1:
583 if len_cmds == 1:
583 # Only filter pattern given
584 # Only filter pattern given
584 filter = cmds[0]
585 filter = cmds[0]
585 elif len_cmds == 2:
586 elif len_cmds == 2:
586 # Both filter and type specified
587 # Both filter and type specified
587 filter,type_pattern = cmds
588 filter,type_pattern = cmds
588 else:
589 else:
589 raise ValueError('invalid argument string for psearch: <%s>' %
590 raise ValueError('invalid argument string for psearch: <%s>' %
590 pattern)
591 pattern)
591
592
592 # filter search namespaces
593 # filter search namespaces
593 for name in ns_search:
594 for name in ns_search:
594 if name not in ns_table:
595 if name not in ns_table:
595 raise ValueError('invalid namespace <%s>. Valid names: %s' %
596 raise ValueError('invalid namespace <%s>. Valid names: %s' %
596 (name,ns_table.keys()))
597 (name,ns_table.keys()))
597
598
598 #print 'type_pattern:',type_pattern # dbg
599 #print 'type_pattern:',type_pattern # dbg
599 search_result = []
600 search_result = []
600 for ns_name in ns_search:
601 for ns_name in ns_search:
601 ns = ns_table[ns_name]
602 ns = ns_table[ns_name]
602 tmp_res = list(list_namespace(ns,type_pattern,filter,
603 tmp_res = list(list_namespace(ns,type_pattern,filter,
603 ignore_case=ignore_case,
604 ignore_case=ignore_case,
604 show_all=show_all))
605 show_all=show_all))
605 search_result.extend(tmp_res)
606 search_result.extend(tmp_res)
606 search_result.sort()
607 search_result.sort()
607
608
608 page('\n'.join(search_result))
609 page('\n'.join(search_result))
@@ -1,308 +1,306 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Paging capabilities for IPython.core
4 Paging capabilities for IPython.core
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13
13
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 rid of that dependency, we could move it there.
15 rid of that dependency, we could move it there.
16 -----
16 -----
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 import os
30 import os
31 import re
31 import re
32 import sys
32 import sys
33 import tempfile
33
34
34 from IPython.core import ipapi
35 from IPython.core import ipapi
35 from IPython.core.error import TryNext
36 from IPython.core.error import TryNext
36 from IPython.utils.genutils import (
37 from IPython.utils.cursesimport import use_curses
37 chop, Term, USE_CURSES
38 from IPython.utils.data import chop
38 )
39 from IPython.utils.io import Term
39
40 from IPython.utils.process import xsys
40 if os.name == "nt":
41 from IPython.utils.terminal import get_terminal_size
41 from IPython.utils.winconsole import get_console_size
42
42
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Classes and functions
45 # Classes and functions
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 esc_re = re.compile(r"(\x1b[^m]+m)")
48 esc_re = re.compile(r"(\x1b[^m]+m)")
49
49
50 def page_dumb(strng,start=0,screen_lines=25):
50 def page_dumb(strng, start=0, screen_lines=25):
51 """Very dumb 'pager' in Python, for when nothing else works.
51 """Very dumb 'pager' in Python, for when nothing else works.
52
52
53 Only moves forward, same interface as page(), except for pager_cmd and
53 Only moves forward, same interface as page(), except for pager_cmd and
54 mode."""
54 mode."""
55
55
56 out_ln = strng.splitlines()[start:]
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
58 if len(screens) == 1:
59 print >>Term.cout, os.linesep.join(screens[0])
59 print >>Term.cout, os.linesep.join(screens[0])
60 else:
60 else:
61 last_escape = ""
61 last_escape = ""
62 for scr in screens[0:-1]:
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
63 hunk = os.linesep.join(scr)
64 print >>Term.cout, last_escape + hunk
64 print >>Term.cout, last_escape + hunk
65 if not page_more():
65 if not page_more():
66 return
66 return
67 esc_list = esc_re.findall(hunk)
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
69 last_escape = esc_list[-1]
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
71
71
72 #----------------------------------------------------------------------------
72
73 def page(strng,start=0,screen_lines=0,pager_cmd = None):
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
74 """Print a string, piping through a pager after a certain length.
74 """Print a string, piping through a pager after a certain length.
75
75
76 The screen_lines parameter specifies the number of *usable* lines of your
76 The screen_lines parameter specifies the number of *usable* lines of your
77 terminal screen (total lines minus lines you need to reserve to show other
77 terminal screen (total lines minus lines you need to reserve to show other
78 information).
78 information).
79
79
80 If you set screen_lines to a number <=0, page() will try to auto-determine
80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 your screen size and will only use up to (screen_size+screen_lines) for
81 your screen size and will only use up to (screen_size+screen_lines) for
82 printing, paging after that. That is, if you want auto-detection but need
82 printing, paging after that. That is, if you want auto-detection but need
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 auto-detection without any lines reserved simply use screen_lines = 0.
84 auto-detection without any lines reserved simply use screen_lines = 0.
85
85
86 If a string won't fit in the allowed lines, it is sent through the
86 If a string won't fit in the allowed lines, it is sent through the
87 specified pager command. If none given, look for PAGER in the environment,
87 specified pager command. If none given, look for PAGER in the environment,
88 and ultimately default to less.
88 and ultimately default to less.
89
89
90 If no system pager works, the string is sent through a 'dumb pager'
90 If no system pager works, the string is sent through a 'dumb pager'
91 written in python, very simplistic.
91 written in python, very simplistic.
92 """
92 """
93
93
94 # Some routines may auto-compute start offsets incorrectly and pass a
94 # Some routines may auto-compute start offsets incorrectly and pass a
95 # negative value. Offset to 0 for robustness.
95 # negative value. Offset to 0 for robustness.
96 start = max(0,start)
96 start = max(0, start)
97
97
98 # first, try the hook
98 # first, try the hook
99 ip = ipapi.get()
99 ip = ipapi.get()
100 if ip:
100 if ip:
101 try:
101 try:
102 ip.hooks.show_in_pager(strng)
102 ip.hooks.show_in_pager(strng)
103 return
103 return
104 except TryNext:
104 except TryNext:
105 pass
105 pass
106
106
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 TERM = os.environ.get('TERM','dumb')
108 TERM = os.environ.get('TERM','dumb')
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 print strng
110 print strng
111 return
111 return
112 # chop off the topmost part of the string we don't want to see
112 # chop off the topmost part of the string we don't want to see
113 str_lines = strng.split(os.linesep)[start:]
113 str_lines = strng.split(os.linesep)[start:]
114 str_toprint = os.linesep.join(str_lines)
114 str_toprint = os.linesep.join(str_lines)
115 num_newlines = len(str_lines)
115 num_newlines = len(str_lines)
116 len_str = len(str_toprint)
116 len_str = len(str_toprint)
117
117
118 # Dumb heuristics to guesstimate number of on-screen lines the string
118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 # takes. Very basic, but good enough for docstrings in reasonable
119 # takes. Very basic, but good enough for docstrings in reasonable
120 # terminals. If someone later feels like refining it, it's not hard.
120 # terminals. If someone later feels like refining it, it's not hard.
121 numlines = max(num_newlines,int(len_str/80)+1)
121 numlines = max(num_newlines,int(len_str/80)+1)
122
122
123 if os.name == "nt":
123 screen_lines_def = get_terminal_size()[1]
124 screen_lines_def = get_console_size(defaulty=25)[1]
125 else:
126 screen_lines_def = 25 # default value if we can't auto-determine
127
124
128 # auto-determine screen size
125 # auto-determine screen size
129 if screen_lines <= 0:
126 if screen_lines <= 0:
130 if TERM=='xterm' or TERM=='xterm-color':
127 if TERM=='xterm' or TERM=='xterm-color':
131 use_curses = USE_CURSES
128 local_use_curses = use_curses
132 else:
129 else:
133 # curses causes problems on many terminals other than xterm.
130 # curses causes problems on many terminals other than xterm.
134 use_curses = False
131 local_use_curses = False
135 if use_curses:
132 if local_use_curses:
136 import termios
133 import termios
137 import curses
134 import curses
138 # There is a bug in curses, where *sometimes* it fails to properly
135 # There is a bug in curses, where *sometimes* it fails to properly
139 # initialize, and then after the endwin() call is made, the
136 # initialize, and then after the endwin() call is made, the
140 # terminal is left in an unusable state. Rather than trying to
137 # terminal is left in an unusable state. Rather than trying to
141 # check everytime for this (by requesting and comparing termios
138 # check everytime for this (by requesting and comparing termios
142 # flags each time), we just save the initial terminal state and
139 # flags each time), we just save the initial terminal state and
143 # unconditionally reset it every time. It's cheaper than making
140 # unconditionally reset it every time. It's cheaper than making
144 # the checks.
141 # the checks.
145 term_flags = termios.tcgetattr(sys.stdout)
142 term_flags = termios.tcgetattr(sys.stdout)
146 scr = curses.initscr()
143 scr = curses.initscr()
147 screen_lines_real,screen_cols = scr.getmaxyx()
144 screen_lines_real,screen_cols = scr.getmaxyx()
148 curses.endwin()
145 curses.endwin()
149 # Restore terminal state in case endwin() didn't.
146 # Restore terminal state in case endwin() didn't.
150 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
147 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
151 # Now we have what we needed: the screen size in rows/columns
148 # Now we have what we needed: the screen size in rows/columns
152 screen_lines += screen_lines_real
149 screen_lines += screen_lines_real
153 #print '***Screen size:',screen_lines_real,'lines x',\
150 #print '***Screen size:',screen_lines_real,'lines x',\
154 #screen_cols,'columns.' # dbg
151 #screen_cols,'columns.' # dbg
155 else:
152 else:
156 screen_lines += screen_lines_def
153 screen_lines += screen_lines_def
157
154
158 #print 'numlines',numlines,'screenlines',screen_lines # dbg
155 #print 'numlines',numlines,'screenlines',screen_lines # dbg
159 if numlines <= screen_lines :
156 if numlines <= screen_lines :
160 #print '*** normal print' # dbg
157 #print '*** normal print' # dbg
161 print >>Term.cout, str_toprint
158 print >>Term.cout, str_toprint
162 else:
159 else:
163 # Try to open pager and default to internal one if that fails.
160 # Try to open pager and default to internal one if that fails.
164 # All failure modes are tagged as 'retval=1', to match the return
161 # All failure modes are tagged as 'retval=1', to match the return
165 # value of a failed system command. If any intermediate attempt
162 # value of a failed system command. If any intermediate attempt
166 # sets retval to 1, at the end we resort to our own page_dumb() pager.
163 # sets retval to 1, at the end we resort to our own page_dumb() pager.
167 pager_cmd = get_pager_cmd(pager_cmd)
164 pager_cmd = get_pager_cmd(pager_cmd)
168 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
165 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
169 if os.name == 'nt':
166 if os.name == 'nt':
170 if pager_cmd.startswith('type'):
167 if pager_cmd.startswith('type'):
171 # The default WinXP 'type' command is failing on complex strings.
168 # The default WinXP 'type' command is failing on complex strings.
172 retval = 1
169 retval = 1
173 else:
170 else:
174 tmpname = tempfile.mktemp('.txt')
171 tmpname = tempfile.mktemp('.txt')
175 tmpfile = file(tmpname,'wt')
172 tmpfile = file(tmpname,'wt')
176 tmpfile.write(strng)
173 tmpfile.write(strng)
177 tmpfile.close()
174 tmpfile.close()
178 cmd = "%s < %s" % (pager_cmd,tmpname)
175 cmd = "%s < %s" % (pager_cmd,tmpname)
179 if os.system(cmd):
176 if os.system(cmd):
180 retval = 1
177 retval = 1
181 else:
178 else:
182 retval = None
179 retval = None
183 os.remove(tmpname)
180 os.remove(tmpname)
184 else:
181 else:
185 try:
182 try:
186 retval = None
183 retval = None
187 # if I use popen4, things hang. No idea why.
184 # if I use popen4, things hang. No idea why.
188 #pager,shell_out = os.popen4(pager_cmd)
185 #pager,shell_out = os.popen4(pager_cmd)
189 pager = os.popen(pager_cmd,'w')
186 pager = os.popen(pager_cmd,'w')
190 pager.write(strng)
187 pager.write(strng)
191 pager.close()
188 pager.close()
192 retval = pager.close() # success returns None
189 retval = pager.close() # success returns None
193 except IOError,msg: # broken pipe when user quits
190 except IOError,msg: # broken pipe when user quits
194 if msg.args == (32,'Broken pipe'):
191 if msg.args == (32,'Broken pipe'):
195 retval = None
192 retval = None
196 else:
193 else:
197 retval = 1
194 retval = 1
198 except OSError:
195 except OSError:
199 # Other strange problems, sometimes seen in Win2k/cygwin
196 # Other strange problems, sometimes seen in Win2k/cygwin
200 retval = 1
197 retval = 1
201 if retval is not None:
198 if retval is not None:
202 page_dumb(strng,screen_lines=screen_lines)
199 page_dumb(strng,screen_lines=screen_lines)
203
200
204 #----------------------------------------------------------------------------
201
205 def page_file(fname,start = 0, pager_cmd = None):
202 def page_file(fname, start=0, pager_cmd=None):
206 """Page a file, using an optional pager command and starting line.
203 """Page a file, using an optional pager command and starting line.
207 """
204 """
208
205
209 pager_cmd = get_pager_cmd(pager_cmd)
206 pager_cmd = get_pager_cmd(pager_cmd)
210 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
207 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
211
208
212 try:
209 try:
213 if os.environ['TERM'] in ['emacs','dumb']:
210 if os.environ['TERM'] in ['emacs','dumb']:
214 raise EnvironmentError
211 raise EnvironmentError
215 xsys(pager_cmd + ' ' + fname)
212 xsys(pager_cmd + ' ' + fname)
216 except:
213 except:
217 try:
214 try:
218 if start > 0:
215 if start > 0:
219 start -= 1
216 start -= 1
220 page(open(fname).read(),start)
217 page(open(fname).read(),start)
221 except:
218 except:
222 print 'Unable to show file',`fname`
219 print 'Unable to show file',`fname`
223
220
224 #----------------------------------------------------------------------------
225 def get_pager_cmd(pager_cmd = None):
226 """Return a pager command.
227
221
228 Makes some attempts at finding an OS-correct one."""
222 def get_pager_cmd(pager_cmd=None):
223 """Return a pager command.
229
224
225 Makes some attempts at finding an OS-correct one.
226 """
230 if os.name == 'posix':
227 if os.name == 'posix':
231 default_pager_cmd = 'less -r' # -r for color control sequences
228 default_pager_cmd = 'less -r' # -r for color control sequences
232 elif os.name in ['nt','dos']:
229 elif os.name in ['nt','dos']:
233 default_pager_cmd = 'type'
230 default_pager_cmd = 'type'
234
231
235 if pager_cmd is None:
232 if pager_cmd is None:
236 try:
233 try:
237 pager_cmd = os.environ['PAGER']
234 pager_cmd = os.environ['PAGER']
238 except:
235 except:
239 pager_cmd = default_pager_cmd
236 pager_cmd = default_pager_cmd
240 return pager_cmd
237 return pager_cmd
241
238
242 #-----------------------------------------------------------------------------
239
243 def get_pager_start(pager,start):
240 def get_pager_start(pager, start):
244 """Return the string for paging files with an offset.
241 """Return the string for paging files with an offset.
245
242
246 This is the '+N' argument which less and more (under Unix) accept.
243 This is the '+N' argument which less and more (under Unix) accept.
247 """
244 """
248
245
249 if pager in ['less','more']:
246 if pager in ['less','more']:
250 if start:
247 if start:
251 start_string = '+' + str(start)
248 start_string = '+' + str(start)
252 else:
249 else:
253 start_string = ''
250 start_string = ''
254 else:
251 else:
255 start_string = ''
252 start_string = ''
256 return start_string
253 return start_string
257
254
258 #----------------------------------------------------------------------------
255
259 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
256 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
260 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
257 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
261 import msvcrt
258 import msvcrt
262 def page_more():
259 def page_more():
263 """ Smart pausing between pages
260 """ Smart pausing between pages
264
261
265 @return: True if need print more lines, False if quit
262 @return: True if need print more lines, False if quit
266 """
263 """
267 Term.cout.write('---Return to continue, q to quit--- ')
264 Term.cout.write('---Return to continue, q to quit--- ')
268 ans = msvcrt.getch()
265 ans = msvcrt.getch()
269 if ans in ("q", "Q"):
266 if ans in ("q", "Q"):
270 result = False
267 result = False
271 else:
268 else:
272 result = True
269 result = True
273 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
270 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
274 return result
271 return result
275 else:
272 else:
276 def page_more():
273 def page_more():
277 ans = raw_input('---Return to continue, q to quit--- ')
274 ans = raw_input('---Return to continue, q to quit--- ')
278 if ans.lower().startswith('q'):
275 if ans.lower().startswith('q'):
279 return False
276 return False
280 else:
277 else:
281 return True
278 return True
282
279
283 #----------------------------------------------------------------------------
280
284 def snip_print(str,width = 75,print_full = 0,header = ''):
281 def snip_print(str,width = 75,print_full = 0,header = ''):
285 """Print a string snipping the midsection to fit in width.
282 """Print a string snipping the midsection to fit in width.
286
283
287 print_full: mode control:
284 print_full: mode control:
288 - 0: only snip long strings
285 - 0: only snip long strings
289 - 1: send to page() directly.
286 - 1: send to page() directly.
290 - 2: snip long strings and ask for full length viewing with page()
287 - 2: snip long strings and ask for full length viewing with page()
291 Return 1 if snipping was necessary, 0 otherwise."""
288 Return 1 if snipping was necessary, 0 otherwise."""
292
289
293 if print_full == 1:
290 if print_full == 1:
294 page(header+str)
291 page(header+str)
295 return 0
292 return 0
296
293
297 print header,
294 print header,
298 if len(str) < width:
295 if len(str) < width:
299 print str
296 print str
300 snip = 0
297 snip = 0
301 else:
298 else:
302 whalf = int((width -5)/2)
299 whalf = int((width -5)/2)
303 print str[:whalf] + ' <...> ' + str[-whalf:]
300 print str[:whalf] + ' <...> ' + str[-whalf:]
304 snip = 1
301 snip = 1
305 if snip and print_full == 2:
302 if snip and print_full == 2:
306 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
303 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
307 page(str)
304 page(str)
308 return snip No newline at end of file
305 return snip
306
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/utils/tests/test_genutils.py to IPython/utils/tests/test_path.py
NO CONTENT: file renamed from IPython/utils/tests/test_genutils.py to IPython/utils/tests/test_path.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/utils/tests/test_platutils.py to IPython/utils/tests/test_process.py
NO CONTENT: file renamed from IPython/utils/tests/test_platutils.py to IPython/utils/tests/test_process.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now