##// END OF EJS Templates
Work to address the review comments on Fernando's branch....
Brian Granger -
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,67 +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 from __future__ import absolute_import
20
20
21 import os
21 import os
22 import sys
22 import sys
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Setup everything
25 # Setup everything
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 if sys.version[0:3] < '2.5':
28 if sys.version[0:3] < '2.5':
29 raise ImportError('Python Version 2.5 or above is required for IPython.')
29 raise ImportError('Python Version 2.5 or above is required for IPython.')
30
30
31
31
32 # 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.
33 # 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.
34 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35
36
36 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
37 # Setup the top level names
38 # Setup the top level names
38 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
39
40
40 # In some cases, these are causing circular imports.
41 from .config.loader import Config
41 from .config.loader import Config
42 from .core import release
42 from .core import release
43 from .core.application import Application
43 from .core.application import Application
44 from .core.ipapp import IPythonApp
44 from .core.ipapp import IPythonApp
45 from .core.embed import embed
45 from .core.embed import embed
46 from .core.error import TryNext
46 from .core.error import TryNext
47 from .core.iplib import InteractiveShell
47 from .core.iplib import InteractiveShell
48 from .testing import test
48 from .testing import test
49
49
50 from .lib import (
50 from .lib import (
51 enable_wx, disable_wx,
51 enable_wx, disable_wx,
52 enable_gtk, disable_gtk,
52 enable_gtk, disable_gtk,
53 enable_qt4, disable_qt4,
53 enable_qt4, disable_qt4,
54 enable_tk, disable_tk,
54 enable_tk, disable_tk,
55 set_inputhook, clear_inputhook,
55 set_inputhook, clear_inputhook,
56 current_gui, spin,
56 current_gui, spin,
57 appstart_qt4, appstart_wx,
57 appstart_qt4, appstart_wx,
58 appstart_gtk, appstart_tk
58 appstart_gtk, appstart_tk
59 )
59 )
60
60
61 # Release data
61 # Release data
62 __author__ = ''
62 __author__ = ''
63 for author, email in release.authors.values():
63 for author, email in release.authors.values():
64 __author__ += author + ' <' + email + '>\n'
64 __author__ += author + ' <' + email + '>\n'
65 __license__ = release.license
65 __license__ = release.license
66 __version__ = release.version
66 __version__ = release.version
67 __revision__ = release.revision
67 __revision__ = release.revision
@@ -1,377 +1,377 b''
1 # coding: utf-8
1 # coding: utf-8
2 """A simple configuration system.
2 """A simple configuration system.
3
3
4 Authors
4 Authors
5 -------
5 -------
6 * Brian Granger
6 * Brian Granger
7 * Fernando Perez
7 * Fernando Perez
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 import __builtin__
21 import __builtin__
22 import os
22 import os
23 import sys
23 import sys
24
24
25 from IPython.external import argparse
25 from IPython.external import argparse
26 from IPython.utils.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 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Argparse fix
41 # Argparse fix
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Unfortunately argparse by default prints help messages to stderr instead of
43 # Unfortunately argparse by default prints help messages to stderr instead of
44 # stdout. This makes it annoying to capture long help screens at the command
44 # stdout. This makes it annoying to capture long help screens at the command
45 # line, since one must know how to pipe stderr, which many users don't know how
45 # line, since one must know how to pipe stderr, which many users don't know how
46 # to do. So we override the print_help method with one that defaults to
46 # to do. So we override the print_help method with one that defaults to
47 # stdout and use our class instead.
47 # stdout and use our class instead.
48
48
49 class ArgumentParser(argparse.ArgumentParser):
49 class ArgumentParser(argparse.ArgumentParser):
50 """Simple argparse subclass that prints help to stdout by default."""
50 """Simple argparse subclass that prints help to stdout by default."""
51
51
52 def print_help(self, file=None):
52 def print_help(self, file=None):
53 if file is None:
53 if file is None:
54 file = sys.stdout
54 file = sys.stdout
55 return super(ArgumentParser, self).print_help(file)
55 return super(ArgumentParser, self).print_help(file)
56
56
57 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
57 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
58
58
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60 # Config class for holding config information
60 # Config class for holding config information
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62
62
63
63
64 class Config(dict):
64 class Config(dict):
65 """An attribute based dict that can do smart merges."""
65 """An attribute based dict that can do smart merges."""
66
66
67 def __init__(self, *args, **kwds):
67 def __init__(self, *args, **kwds):
68 dict.__init__(self, *args, **kwds)
68 dict.__init__(self, *args, **kwds)
69 # This sets self.__dict__ = self, but it has to be done this way
69 # This sets self.__dict__ = self, but it has to be done this way
70 # because we are also overriding __setattr__.
70 # because we are also overriding __setattr__.
71 dict.__setattr__(self, '__dict__', self)
71 dict.__setattr__(self, '__dict__', self)
72
72
73 def _merge(self, other):
73 def _merge(self, other):
74 to_update = {}
74 to_update = {}
75 for k, v in other.items():
75 for k, v in other.items():
76 if not self.has_key(k):
76 if not self.has_key(k):
77 to_update[k] = v
77 to_update[k] = v
78 else: # I have this key
78 else: # I have this key
79 if isinstance(v, Config):
79 if isinstance(v, Config):
80 # Recursively merge common sub Configs
80 # Recursively merge common sub Configs
81 self[k]._merge(v)
81 self[k]._merge(v)
82 else:
82 else:
83 # Plain updates for non-Configs
83 # Plain updates for non-Configs
84 to_update[k] = v
84 to_update[k] = v
85
85
86 self.update(to_update)
86 self.update(to_update)
87
87
88 def _is_section_key(self, key):
88 def _is_section_key(self, key):
89 if key[0].upper()==key[0] and not key.startswith('_'):
89 if key[0].upper()==key[0] and not key.startswith('_'):
90 return True
90 return True
91 else:
91 else:
92 return False
92 return False
93
93
94 def has_key(self, key):
94 def has_key(self, key):
95 if self._is_section_key(key):
95 if self._is_section_key(key):
96 return True
96 return True
97 else:
97 else:
98 return dict.has_key(self, key)
98 return dict.has_key(self, key)
99
99
100 def _has_section(self, key):
100 def _has_section(self, key):
101 if self._is_section_key(key):
101 if self._is_section_key(key):
102 if dict.has_key(self, key):
102 if dict.has_key(self, key):
103 return True
103 return True
104 return False
104 return False
105
105
106 def copy(self):
106 def copy(self):
107 return type(self)(dict.copy(self))
107 return type(self)(dict.copy(self))
108
108
109 def __copy__(self):
109 def __copy__(self):
110 return self.copy()
110 return self.copy()
111
111
112 def __deepcopy__(self, memo):
112 def __deepcopy__(self, memo):
113 import copy
113 import copy
114 return type(self)(copy.deepcopy(self.items()))
114 return type(self)(copy.deepcopy(self.items()))
115
115
116 def __getitem__(self, key):
116 def __getitem__(self, key):
117 # Because we use this for an exec namespace, we need to delegate
117 # Because we use this for an exec namespace, we need to delegate
118 # the lookup of names in __builtin__ to itself. This means
118 # the lookup of names in __builtin__ to itself. This means
119 # that you can't have section or attribute names that are
119 # that you can't have section or attribute names that are
120 # builtins.
120 # builtins.
121 try:
121 try:
122 return getattr(__builtin__, key)
122 return getattr(__builtin__, key)
123 except AttributeError:
123 except AttributeError:
124 pass
124 pass
125 if self._is_section_key(key):
125 if self._is_section_key(key):
126 try:
126 try:
127 return dict.__getitem__(self, key)
127 return dict.__getitem__(self, key)
128 except KeyError:
128 except KeyError:
129 c = Config()
129 c = Config()
130 dict.__setitem__(self, key, c)
130 dict.__setitem__(self, key, c)
131 return c
131 return c
132 else:
132 else:
133 return dict.__getitem__(self, key)
133 return dict.__getitem__(self, key)
134
134
135 def __setitem__(self, key, value):
135 def __setitem__(self, key, value):
136 # Don't allow names in __builtin__ to be modified.
136 # Don't allow names in __builtin__ to be modified.
137 if hasattr(__builtin__, key):
137 if hasattr(__builtin__, key):
138 raise ConfigError('Config variable names cannot have the same name '
138 raise ConfigError('Config variable names cannot have the same name '
139 'as a Python builtin: %s' % key)
139 'as a Python builtin: %s' % key)
140 if self._is_section_key(key):
140 if self._is_section_key(key):
141 if not isinstance(value, Config):
141 if not isinstance(value, Config):
142 raise ValueError('values whose keys begin with an uppercase '
142 raise ValueError('values whose keys begin with an uppercase '
143 'char must be Config instances: %r, %r' % (key, value))
143 'char must be Config instances: %r, %r' % (key, value))
144 else:
144 else:
145 dict.__setitem__(self, key, value)
145 dict.__setitem__(self, key, value)
146
146
147 def __getattr__(self, key):
147 def __getattr__(self, key):
148 try:
148 try:
149 return self.__getitem__(key)
149 return self.__getitem__(key)
150 except KeyError, e:
150 except KeyError, e:
151 raise AttributeError(e)
151 raise AttributeError(e)
152
152
153 def __setattr__(self, key, value):
153 def __setattr__(self, key, value):
154 try:
154 try:
155 self.__setitem__(key, value)
155 self.__setitem__(key, value)
156 except KeyError, e:
156 except KeyError, e:
157 raise AttributeError(e)
157 raise AttributeError(e)
158
158
159 def __delattr__(self, key):
159 def __delattr__(self, key):
160 try:
160 try:
161 dict.__delitem__(self, key)
161 dict.__delitem__(self, key)
162 except KeyError, e:
162 except KeyError, e:
163 raise AttributeError(e)
163 raise AttributeError(e)
164
164
165
165
166 #-----------------------------------------------------------------------------
166 #-----------------------------------------------------------------------------
167 # Config loading classes
167 # Config loading classes
168 #-----------------------------------------------------------------------------
168 #-----------------------------------------------------------------------------
169
169
170
170
171 class ConfigLoader(object):
171 class ConfigLoader(object):
172 """A object for loading configurations from just about anywhere.
172 """A object for loading configurations from just about anywhere.
173
173
174 The resulting configuration is packaged as a :class:`Struct`.
174 The resulting configuration is packaged as a :class:`Struct`.
175
175
176 Notes
176 Notes
177 -----
177 -----
178 A :class:`ConfigLoader` does one thing: load a config from a source
178 A :class:`ConfigLoader` does one thing: load a config from a source
179 (file, command line arguments) and returns the data as a :class:`Struct`.
179 (file, command line arguments) and returns the data as a :class:`Struct`.
180 There are lots of things that :class:`ConfigLoader` does not do. It does
180 There are lots of things that :class:`ConfigLoader` does not do. It does
181 not implement complex logic for finding config files. It does not handle
181 not implement complex logic for finding config files. It does not handle
182 default values or merge multiple configs. These things need to be
182 default values or merge multiple configs. These things need to be
183 handled elsewhere.
183 handled elsewhere.
184 """
184 """
185
185
186 def __init__(self):
186 def __init__(self):
187 """A base class for config loaders.
187 """A base class for config loaders.
188
188
189 Examples
189 Examples
190 --------
190 --------
191
191
192 >>> cl = ConfigLoader()
192 >>> cl = ConfigLoader()
193 >>> config = cl.load_config()
193 >>> config = cl.load_config()
194 >>> config
194 >>> config
195 {}
195 {}
196 """
196 """
197 self.clear()
197 self.clear()
198
198
199 def clear(self):
199 def clear(self):
200 self.config = Config()
200 self.config = Config()
201
201
202 def load_config(self):
202 def load_config(self):
203 """Load a config from somewhere, return a Struct.
203 """Load a config from somewhere, return a Struct.
204
204
205 Usually, this will cause self.config to be set and then returned.
205 Usually, this will cause self.config to be set and then returned.
206 """
206 """
207 return self.config
207 return self.config
208
208
209
209
210 class FileConfigLoader(ConfigLoader):
210 class FileConfigLoader(ConfigLoader):
211 """A base class for file based configurations.
211 """A base class for file based configurations.
212
212
213 As we add more file based config loaders, the common logic should go
213 As we add more file based config loaders, the common logic should go
214 here.
214 here.
215 """
215 """
216 pass
216 pass
217
217
218
218
219 class PyFileConfigLoader(FileConfigLoader):
219 class PyFileConfigLoader(FileConfigLoader):
220 """A config loader for pure python files.
220 """A config loader for pure python files.
221
221
222 This calls execfile on a plain python file and looks for attributes
222 This calls execfile on a plain python file and looks for attributes
223 that are all caps. These attribute are added to the config Struct.
223 that are all caps. These attribute are added to the config Struct.
224 """
224 """
225
225
226 def __init__(self, filename, path=None):
226 def __init__(self, filename, path=None):
227 """Build a config loader for a filename and path.
227 """Build a config loader for a filename and path.
228
228
229 Parameters
229 Parameters
230 ----------
230 ----------
231 filename : str
231 filename : str
232 The file name of the config file.
232 The file name of the config file.
233 path : str, list, tuple
233 path : str, list, tuple
234 The path to search for the config file on, or a sequence of
234 The path to search for the config file on, or a sequence of
235 paths to try in order.
235 paths to try in order.
236 """
236 """
237 super(PyFileConfigLoader, self).__init__()
237 super(PyFileConfigLoader, self).__init__()
238 self.filename = filename
238 self.filename = filename
239 self.path = path
239 self.path = path
240 self.full_filename = ''
240 self.full_filename = ''
241 self.data = None
241 self.data = None
242
242
243 def load_config(self):
243 def load_config(self):
244 """Load the config from a file and return it as a Struct."""
244 """Load the config from a file and return it as a Struct."""
245 self._find_file()
245 self._find_file()
246 self._read_file_as_dict()
246 self._read_file_as_dict()
247 self._convert_to_config()
247 self._convert_to_config()
248 return self.config
248 return self.config
249
249
250 def _find_file(self):
250 def _find_file(self):
251 """Try to find the file by searching the paths."""
251 """Try to find the file by searching the paths."""
252 self.full_filename = filefind(self.filename, self.path)
252 self.full_filename = filefind(self.filename, self.path)
253
253
254 def _read_file_as_dict(self):
254 def _read_file_as_dict(self):
255 """Load the config file into self.config, with recursive loading."""
255 """Load the config file into self.config, with recursive loading."""
256 # This closure is made available in the namespace that is used
256 # This closure is made available in the namespace that is used
257 # to exec the config file. This allows users to call
257 # to exec the config file. This allows users to call
258 # load_subconfig('myconfig.py') to load config files recursively.
258 # load_subconfig('myconfig.py') to load config files recursively.
259 # It needs to be a closure because it has references to self.path
259 # It needs to be a closure because it has references to self.path
260 # and self.config. The sub-config is loaded with the same path
260 # and self.config. The sub-config is loaded with the same path
261 # as the parent, but it uses an empty config which is then merged
261 # as the parent, but it uses an empty config which is then merged
262 # with the parents.
262 # with the parents.
263 def load_subconfig(fname):
263 def load_subconfig(fname):
264 loader = PyFileConfigLoader(fname, self.path)
264 loader = PyFileConfigLoader(fname, self.path)
265 try:
265 try:
266 sub_config = loader.load_config()
266 sub_config = loader.load_config()
267 except IOError:
267 except IOError:
268 # Pass silently if the sub config is not there. This happens
268 # Pass silently if the sub config is not there. This happens
269 # when a user us using a profile, but not the default config.
269 # when a user us using a profile, but not the default config.
270 pass
270 pass
271 else:
271 else:
272 self.config._merge(sub_config)
272 self.config._merge(sub_config)
273
273
274 # Again, this needs to be a closure and should be used in config
274 # Again, this needs to be a closure and should be used in config
275 # files to get the config being loaded.
275 # files to get the config being loaded.
276 def get_config():
276 def get_config():
277 return self.config
277 return self.config
278
278
279 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
279 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
280 execfile(self.full_filename, namespace)
280 execfile(self.full_filename, namespace)
281
281
282 def _convert_to_config(self):
282 def _convert_to_config(self):
283 if self.data is None:
283 if self.data is None:
284 ConfigLoaderError('self.data does not exist')
284 ConfigLoaderError('self.data does not exist')
285
285
286
286
287 class CommandLineConfigLoader(ConfigLoader):
287 class CommandLineConfigLoader(ConfigLoader):
288 """A config loader for command line arguments.
288 """A config loader for command line arguments.
289
289
290 As we add more command line based loaders, the common logic should go
290 As we add more command line based loaders, the common logic should go
291 here.
291 here.
292 """
292 """
293
293
294
294
295 class __NoConfigDefault(object): pass
295 class __NoConfigDefault(object): pass
296 NoConfigDefault = __NoConfigDefault()
296 NoConfigDefault = __NoConfigDefault()
297
297
298
298
299 class ArgParseConfigLoader(CommandLineConfigLoader):
299 class ArgParseConfigLoader(CommandLineConfigLoader):
300 #: Global default for arguments (see argparse docs for details)
300 #: Global default for arguments (see argparse docs for details)
301 argument_default = NoConfigDefault
301 argument_default = NoConfigDefault
302
302
303 def __init__(self, argv=None, arguments=(), *args, **kw):
303 def __init__(self, argv=None, arguments=(), *args, **kw):
304 """Create a config loader for use with argparse.
304 """Create a config loader for use with argparse.
305
305
306 With the exception of ``argv`` and ``arguments``, other args and kwargs
306 With the exception of ``argv`` and ``arguments``, other args and kwargs
307 arguments here are passed onto the constructor of
307 arguments here are passed onto the constructor of
308 :class:`argparse.ArgumentParser`.
308 :class:`argparse.ArgumentParser`.
309
309
310 Parameters
310 Parameters
311 ----------
311 ----------
312
312
313 argv : optional, list
313 argv : optional, list
314 If given, used to read command-line arguments from, otherwise
314 If given, used to read command-line arguments from, otherwise
315 sys.argv[1:] is used.
315 sys.argv[1:] is used.
316
316
317 arguments : optional, tuple
317 arguments : optional, tuple
318 Description of valid command-line arguments, to be called in sequence
318 Description of valid command-line arguments, to be called in sequence
319 with parser.add_argument() to configure the parser.
319 with parser.add_argument() to configure the parser.
320 """
320 """
321 super(CommandLineConfigLoader, self).__init__()
321 super(CommandLineConfigLoader, self).__init__()
322 if argv == None:
322 if argv == None:
323 argv = sys.argv[1:]
323 argv = sys.argv[1:]
324 self.argv = argv
324 self.argv = argv
325 self.arguments = arguments
325 self.arguments = arguments
326 self.args = args
326 self.args = args
327 kwargs = dict(argument_default=self.argument_default)
327 kwargs = dict(argument_default=self.argument_default)
328 kwargs.update(kw)
328 kwargs.update(kw)
329 self.kw = kwargs
329 self.kw = kwargs
330
330
331 def load_config(self, args=None):
331 def load_config(self, args=None):
332 """Parse command line arguments and return as a Struct.
332 """Parse command line arguments and return as a Struct.
333
333
334 Parameters
334 Parameters
335 ----------
335 ----------
336
336
337 args : optional, list
337 args : optional, list
338 If given, a list with the structure of sys.argv[1:] to parse arguments
338 If given, a list with the structure of sys.argv[1:] to parse arguments
339 from. If not given, the instance's self.argv attribute (given at
339 from. If not given, the instance's self.argv attribute (given at
340 construction time) is used."""
340 construction time) is used."""
341
341
342 if args is None:
342 if args is None:
343 args = self.argv
343 args = self.argv
344 self._create_parser()
344 self._create_parser()
345 self._parse_args(args)
345 self._parse_args(args)
346 self._convert_to_config()
346 self._convert_to_config()
347 return self.config
347 return self.config
348
348
349 def get_extra_args(self):
349 def get_extra_args(self):
350 if hasattr(self, 'extra_args'):
350 if hasattr(self, 'extra_args'):
351 return self.extra_args
351 return self.extra_args
352 else:
352 else:
353 return []
353 return []
354
354
355 def _create_parser(self):
355 def _create_parser(self):
356 self.parser = ArgumentParser(*self.args, **self.kw)
356 self.parser = ArgumentParser(*self.args, **self.kw)
357 self._add_arguments()
357 self._add_arguments()
358 self._add_other_arguments()
358 self._add_other_arguments()
359
359
360 def _add_arguments(self):
360 def _add_arguments(self):
361 for argument in self.arguments:
361 for argument in self.arguments:
362 self.parser.add_argument(*argument[0],**argument[1])
362 self.parser.add_argument(*argument[0],**argument[1])
363
363
364 def _add_other_arguments(self):
364 def _add_other_arguments(self):
365 """Meant for subclasses to add their own arguments."""
365 """Meant for subclasses to add their own arguments."""
366 pass
366 pass
367
367
368 def _parse_args(self, args):
368 def _parse_args(self, args):
369 """self.parser->self.parsed_data"""
369 """self.parser->self.parsed_data"""
370 self.parsed_data, self.extra_args = self.parser.parse_known_args(args)
370 self.parsed_data, self.extra_args = self.parser.parse_known_args(args)
371
371
372 def _convert_to_config(self):
372 def _convert_to_config(self):
373 """self.parsed_data->self.config"""
373 """self.parsed_data->self.config"""
374 for k, v in vars(self.parsed_data).items():
374 for k, v in vars(self.parsed_data).items():
375 if v is not NoConfigDefault:
375 if v is not NoConfigDefault:
376 exec_str = 'self.config.' + k + '= v'
376 exec_str = 'self.config.' + k + '= v'
377 exec exec_str in locals(), globals()
377 exec exec_str in locals(), globals()
@@ -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,489 +1,489 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An application for IPython.
3 An application for IPython.
4
4
5 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
6 handling configuration and creating componenets.
6 handling configuration and creating componenets.
7
7
8 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
9 object and then create the components, passing the config to them.
9 object and then create the components, passing the config to them.
10
10
11 Authors:
11 Authors:
12
12
13 * Brian Granger
13 * Brian Granger
14 * Fernando Perez
14 * Fernando Perez
15
15
16 Notes
16 Notes
17 -----
17 -----
18 """
18 """
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Copyright (C) 2008-2009 The IPython Development Team
21 # Copyright (C) 2008-2009 The IPython Development Team
22 #
22 #
23 # 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
24 # the file COPYING, distributed as part of this software.
24 # the file COPYING, distributed as part of this software.
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Imports
28 # Imports
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 import logging
31 import logging
32 import os
32 import os
33 import sys
33 import sys
34
34
35 from IPython.core import release, crashhandler
35 from IPython.core import release, crashhandler
36 from IPython.utils.genutils import get_ipython_dir, get_ipython_package_dir
36 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
37 from IPython.config.loader import (
37 from IPython.config.loader import (
38 PyFileConfigLoader,
38 PyFileConfigLoader,
39 ArgParseConfigLoader,
39 ArgParseConfigLoader,
40 Config,
40 Config,
41 )
41 )
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Classes and functions
44 # Classes and functions
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 class ApplicationError(Exception):
47 class ApplicationError(Exception):
48 pass
48 pass
49
49
50
50
51 app_cl_args = (
51 app_cl_args = (
52 (('--ipython-dir', ), dict(
52 (('--ipython-dir', ), dict(
53 dest='Global.ipython_dir',type=unicode,
53 dest='Global.ipython_dir',type=unicode,
54 help=
54 help=
55 """Set to override default location of the IPython directory
55 """Set to override default location of the IPython directory
56 IPYTHON_DIR, stored as Global.ipython_dir. This can also be specified
56 IPYTHON_DIR, stored as Global.ipython_dir. This can also be specified
57 through the environment variable IPYTHON_DIR.""",
57 through the environment variable IPYTHON_DIR.""",
58 metavar='Global.ipython_dir') ),
58 metavar='Global.ipython_dir') ),
59 (('-p', '--profile',), dict(
59 (('-p', '--profile',), dict(
60 dest='Global.profile',type=unicode,
60 dest='Global.profile',type=unicode,
61 help=
61 help=
62 """The string name of the ipython profile to be used. Assume that your
62 """The string name of the ipython profile to be used. Assume that your
63 config file is ipython_config-<name>.py (looks in current dir first,
63 config file is ipython_config-<name>.py (looks in current dir first,
64 then in IPYTHON_DIR). This is a quick way to keep and load multiple
64 then in IPYTHON_DIR). This is a quick way to keep and load multiple
65 config files for different tasks, especially if include your basic one
65 config files for different tasks, especially if include your basic one
66 in your more specialized ones. You can keep a basic
66 in your more specialized ones. You can keep a basic
67 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
67 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
68 include this one and load extra things for particular tasks.""",
68 include this one and load extra things for particular tasks.""",
69 metavar='Global.profile') ),
69 metavar='Global.profile') ),
70 (('--log-level',), dict(
70 (('--log-level',), dict(
71 dest="Global.log_level",type=int,
71 dest="Global.log_level",type=int,
72 help='Set the log level (0,10,20,30,40,50). Default is 30.',
72 help='Set the log level (0,10,20,30,40,50). Default is 30.',
73 metavar='Global.log_level')),
73 metavar='Global.log_level')),
74 (('--config-file',), dict(
74 (('--config-file',), dict(
75 dest='Global.config_file',type=unicode,
75 dest='Global.config_file',type=unicode,
76 help=
76 help=
77 """Set the config file name to override default. Normally IPython
77 """Set the config file name to override default. Normally IPython
78 loads ipython_config.py (from current directory) or
78 loads ipython_config.py (from current directory) or
79 IPYTHON_DIR/ipython_config.py. If the loading of your config file
79 IPYTHON_DIR/ipython_config.py. If the loading of your config file
80 fails, IPython starts with a bare bones configuration (no modules
80 fails, IPython starts with a bare bones configuration (no modules
81 loaded at all).""",
81 loaded at all).""",
82 metavar='Global.config_file')),
82 metavar='Global.config_file')),
83 )
83 )
84
84
85 class Application(object):
85 class Application(object):
86 """Load a config, construct components and set them running.
86 """Load a config, construct components and set them running.
87
87
88 The configuration of an application can be done via four different Config
88 The configuration of an application can be done via four different Config
89 objects, which are loaded and ultimately merged into a single one used from
89 objects, which are loaded and ultimately merged into a single one used from
90 that point on by the app. These are:
90 that point on by the app. These are:
91
91
92 1. default_config: internal defaults, implemented in code.
92 1. default_config: internal defaults, implemented in code.
93 2. file_config: read from the filesystem.
93 2. file_config: read from the filesystem.
94 3. command_line_config: read from the system's command line flags.
94 3. command_line_config: read from the system's command line flags.
95 4. constructor_config: passed parametrically to the constructor.
95 4. constructor_config: passed parametrically to the constructor.
96
96
97 During initialization, 3 is actually read before 2, since at the
97 During initialization, 3 is actually read before 2, since at the
98 command-line one may override the location of the file to be read. But the
98 command-line one may override the location of the file to be read. But the
99 above is the order in which the merge is made.
99 above is the order in which the merge is made.
100
100
101 There is a final config object can be created and passed to the
101 There is a final config object can be created and passed to the
102 constructor: override_config. If it exists, this completely overrides the
102 constructor: override_config. If it exists, this completely overrides the
103 configs 2-4 above (the default is still used to ensure that all needed
103 configs 2-4 above (the default is still used to ensure that all needed
104 fields at least are created). This makes it easier to create
104 fields at least are created). This makes it easier to create
105 parametrically (e.g. in testing or sphinx plugins) objects with a known
105 parametrically (e.g. in testing or sphinx plugins) objects with a known
106 configuration, that are unaffected by whatever arguments may be present in
106 configuration, that are unaffected by whatever arguments may be present in
107 sys.argv or files in the user's various directories.
107 sys.argv or files in the user's various directories.
108 """
108 """
109
109
110 name = u'ipython'
110 name = u'ipython'
111 description = 'IPython: an enhanced interactive Python shell.'
111 description = 'IPython: an enhanced interactive Python shell.'
112 #: usage message printed by argparse. If None, auto-generate
112 #: usage message printed by argparse. If None, auto-generate
113 usage = None
113 usage = None
114 config_file_name = u'ipython_config.py'
114 config_file_name = u'ipython_config.py'
115 #: Track the default and actual separately because some messages are
115 #: Track the default and actual separately because some messages are
116 #: only printed if we aren't using the default.
116 #: only printed if we aren't using the default.
117 default_config_file_name = config_file_name
117 default_config_file_name = config_file_name
118 default_log_level = logging.WARN
118 default_log_level = logging.WARN
119 #: Set by --profile option
119 #: Set by --profile option
120 profile_name = None
120 profile_name = None
121 #: User's ipython directory, typically ~/.ipython/
121 #: User's ipython directory, typically ~/.ipython/
122 ipython_dir = None
122 ipython_dir = None
123 #: internal defaults, implemented in code.
123 #: internal defaults, implemented in code.
124 default_config = None
124 default_config = None
125 #: read from the filesystem
125 #: read from the filesystem
126 file_config = None
126 file_config = None
127 #: read from the system's command line flags
127 #: read from the system's command line flags
128 command_line_config = None
128 command_line_config = None
129 #: passed parametrically to the constructor.
129 #: passed parametrically to the constructor.
130 constructor_config = None
130 constructor_config = None
131 #: final override, if given supercedes file/command/constructor configs
131 #: final override, if given supercedes file/command/constructor configs
132 override_config = None
132 override_config = None
133 #: A reference to the argv to be used (typically ends up being sys.argv[1:])
133 #: A reference to the argv to be used (typically ends up being sys.argv[1:])
134 argv = None
134 argv = None
135 #: Default command line arguments. Subclasses should create a new tuple
135 #: Default command line arguments. Subclasses should create a new tuple
136 #: that *includes* these.
136 #: that *includes* these.
137 cl_arguments = app_cl_args
137 cl_arguments = app_cl_args
138
138
139 #: extra arguments computed by the command-line loader
139 #: extra arguments computed by the command-line loader
140 extra_args = None
140 extra_args = None
141
141
142 # Private attributes
142 # Private attributes
143 _exiting = False
143 _exiting = False
144 _initialized = False
144 _initialized = False
145
145
146 # Class choices for things that will be instantiated at runtime.
146 # Class choices for things that will be instantiated at runtime.
147 _CrashHandler = crashhandler.CrashHandler
147 _CrashHandler = crashhandler.CrashHandler
148
148
149 def __init__(self, argv=None, constructor_config=None, override_config=None):
149 def __init__(self, argv=None, constructor_config=None, override_config=None):
150 self.argv = sys.argv[1:] if argv is None else argv
150 self.argv = sys.argv[1:] if argv is None else argv
151 self.constructor_config = constructor_config
151 self.constructor_config = constructor_config
152 self.override_config = override_config
152 self.override_config = override_config
153 self.init_logger()
153 self.init_logger()
154
154
155 def init_logger(self):
155 def init_logger(self):
156 self.log = logging.getLogger(self.__class__.__name__)
156 self.log = logging.getLogger(self.__class__.__name__)
157 # This is used as the default until the command line arguments are read.
157 # This is used as the default until the command line arguments are read.
158 self.log.setLevel(self.default_log_level)
158 self.log.setLevel(self.default_log_level)
159 self._log_handler = logging.StreamHandler()
159 self._log_handler = logging.StreamHandler()
160 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
160 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
161 self._log_handler.setFormatter(self._log_formatter)
161 self._log_handler.setFormatter(self._log_formatter)
162 self.log.addHandler(self._log_handler)
162 self.log.addHandler(self._log_handler)
163
163
164 def _set_log_level(self, level):
164 def _set_log_level(self, level):
165 self.log.setLevel(level)
165 self.log.setLevel(level)
166
166
167 def _get_log_level(self):
167 def _get_log_level(self):
168 return self.log.level
168 return self.log.level
169
169
170 log_level = property(_get_log_level, _set_log_level)
170 log_level = property(_get_log_level, _set_log_level)
171
171
172 def initialize(self):
172 def initialize(self):
173 """Initialize the application.
173 """Initialize the application.
174
174
175 Loads all configuration information and sets all application state, but
175 Loads all configuration information and sets all application state, but
176 does not start any relevant processing (typically some kind of event
176 does not start any relevant processing (typically some kind of event
177 loop).
177 loop).
178
178
179 Once this method has been called, the application is flagged as
179 Once this method has been called, the application is flagged as
180 initialized and the method becomes a no-op."""
180 initialized and the method becomes a no-op."""
181
181
182 if self._initialized:
182 if self._initialized:
183 return
183 return
184
184
185 # The first part is protected with an 'attempt' wrapper, that will log
185 # The first part is protected with an 'attempt' wrapper, that will log
186 # failures with the basic system traceback machinery. Once our crash
186 # failures with the basic system traceback machinery. Once our crash
187 # handler is in place, we can let any subsequent exception propagate,
187 # handler is in place, we can let any subsequent exception propagate,
188 # as our handler will log it with much better detail than the default.
188 # as our handler will log it with much better detail than the default.
189 self.attempt(self.create_crash_handler)
189 self.attempt(self.create_crash_handler)
190
190
191 # Configuration phase
191 # Configuration phase
192 # Default config (internally hardwired in application code)
192 # Default config (internally hardwired in application code)
193 self.create_default_config()
193 self.create_default_config()
194 self.log_default_config()
194 self.log_default_config()
195 self.set_default_config_log_level()
195 self.set_default_config_log_level()
196
196
197 if self.override_config is None:
197 if self.override_config is None:
198 # Command-line config
198 # Command-line config
199 self.pre_load_command_line_config()
199 self.pre_load_command_line_config()
200 self.load_command_line_config()
200 self.load_command_line_config()
201 self.set_command_line_config_log_level()
201 self.set_command_line_config_log_level()
202 self.post_load_command_line_config()
202 self.post_load_command_line_config()
203 self.log_command_line_config()
203 self.log_command_line_config()
204
204
205 # Find resources needed for filesystem access, using information from
205 # Find resources needed for filesystem access, using information from
206 # the above two
206 # the above two
207 self.find_ipython_dir()
207 self.find_ipython_dir()
208 self.find_resources()
208 self.find_resources()
209 self.find_config_file_name()
209 self.find_config_file_name()
210 self.find_config_file_paths()
210 self.find_config_file_paths()
211
211
212 if self.override_config is None:
212 if self.override_config is None:
213 # File-based config
213 # File-based config
214 self.pre_load_file_config()
214 self.pre_load_file_config()
215 self.load_file_config()
215 self.load_file_config()
216 self.set_file_config_log_level()
216 self.set_file_config_log_level()
217 self.post_load_file_config()
217 self.post_load_file_config()
218 self.log_file_config()
218 self.log_file_config()
219
219
220 # Merge all config objects into a single one the app can then use
220 # Merge all config objects into a single one the app can then use
221 self.merge_configs()
221 self.merge_configs()
222 self.log_master_config()
222 self.log_master_config()
223
223
224 # Construction phase
224 # Construction phase
225 self.pre_construct()
225 self.pre_construct()
226 self.construct()
226 self.construct()
227 self.post_construct()
227 self.post_construct()
228
228
229 # Done, flag as such and
229 # Done, flag as such and
230 self._initialized = True
230 self._initialized = True
231
231
232 def start(self):
232 def start(self):
233 """Start the application."""
233 """Start the application."""
234 self.initialize()
234 self.initialize()
235 self.start_app()
235 self.start_app()
236
236
237 #-------------------------------------------------------------------------
237 #-------------------------------------------------------------------------
238 # Various stages of Application creation
238 # Various stages of Application creation
239 #-------------------------------------------------------------------------
239 #-------------------------------------------------------------------------
240
240
241 def create_crash_handler(self):
241 def create_crash_handler(self):
242 """Create a crash handler, typically setting sys.excepthook to it."""
242 """Create a crash handler, typically setting sys.excepthook to it."""
243 self.crash_handler = self._CrashHandler(self, self.name)
243 self.crash_handler = self._CrashHandler(self, self.name)
244 sys.excepthook = self.crash_handler
244 sys.excepthook = self.crash_handler
245
245
246 def create_default_config(self):
246 def create_default_config(self):
247 """Create defaults that can't be set elsewhere.
247 """Create defaults that can't be set elsewhere.
248
248
249 For the most part, we try to set default in the class attributes
249 For the most part, we try to set default in the class attributes
250 of Components. But, defaults the top-level Application (which is
250 of Components. But, defaults the top-level Application (which is
251 not a HasTraitlets or Component) are not set in this way. Instead
251 not a HasTraitlets or Component) are not set in this way. Instead
252 we set them here. The Global section is for variables like this that
252 we set them here. The Global section is for variables like this that
253 don't belong to a particular component.
253 don't belong to a particular component.
254 """
254 """
255 c = Config()
255 c = Config()
256 c.Global.ipython_dir = get_ipython_dir()
256 c.Global.ipython_dir = get_ipython_dir()
257 c.Global.log_level = self.log_level
257 c.Global.log_level = self.log_level
258 self.default_config = c
258 self.default_config = c
259
259
260 def log_default_config(self):
260 def log_default_config(self):
261 self.log.debug('Default config loaded:')
261 self.log.debug('Default config loaded:')
262 self.log.debug(repr(self.default_config))
262 self.log.debug(repr(self.default_config))
263
263
264 def set_default_config_log_level(self):
264 def set_default_config_log_level(self):
265 try:
265 try:
266 self.log_level = self.default_config.Global.log_level
266 self.log_level = self.default_config.Global.log_level
267 except AttributeError:
267 except AttributeError:
268 # Fallback to the default_log_level class attribute
268 # Fallback to the default_log_level class attribute
269 pass
269 pass
270
270
271 def create_command_line_config(self):
271 def create_command_line_config(self):
272 """Create and return a command line config loader."""
272 """Create and return a command line config loader."""
273 return ArgParseConfigLoader(self.argv, self.cl_arguments,
273 return ArgParseConfigLoader(self.argv, self.cl_arguments,
274 description=self.description,
274 description=self.description,
275 version=release.version,
275 version=release.version,
276 usage=self.usage,
276 usage=self.usage,
277 )
277 )
278
278
279 def pre_load_command_line_config(self):
279 def pre_load_command_line_config(self):
280 """Do actions just before loading the command line config."""
280 """Do actions just before loading the command line config."""
281 pass
281 pass
282
282
283 def load_command_line_config(self):
283 def load_command_line_config(self):
284 """Load the command line config."""
284 """Load the command line config."""
285 loader = self.create_command_line_config()
285 loader = self.create_command_line_config()
286 self.command_line_config = loader.load_config()
286 self.command_line_config = loader.load_config()
287 self.extra_args = loader.get_extra_args()
287 self.extra_args = loader.get_extra_args()
288
288
289 def set_command_line_config_log_level(self):
289 def set_command_line_config_log_level(self):
290 try:
290 try:
291 self.log_level = self.command_line_config.Global.log_level
291 self.log_level = self.command_line_config.Global.log_level
292 except AttributeError:
292 except AttributeError:
293 pass
293 pass
294
294
295 def post_load_command_line_config(self):
295 def post_load_command_line_config(self):
296 """Do actions just after loading the command line config."""
296 """Do actions just after loading the command line config."""
297 pass
297 pass
298
298
299 def log_command_line_config(self):
299 def log_command_line_config(self):
300 self.log.debug("Command line config loaded:")
300 self.log.debug("Command line config loaded:")
301 self.log.debug(repr(self.command_line_config))
301 self.log.debug(repr(self.command_line_config))
302
302
303 def find_ipython_dir(self):
303 def find_ipython_dir(self):
304 """Set the IPython directory.
304 """Set the IPython directory.
305
305
306 This sets ``self.ipython_dir``, but the actual value that is passed to
306 This sets ``self.ipython_dir``, but the actual value that is passed to
307 the application is kept in either ``self.default_config`` or
307 the application is kept in either ``self.default_config`` or
308 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
308 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
309 ``sys.path`` so config files there can be referenced by other config
309 ``sys.path`` so config files there can be referenced by other config
310 files.
310 files.
311 """
311 """
312
312
313 try:
313 try:
314 self.ipython_dir = self.command_line_config.Global.ipython_dir
314 self.ipython_dir = self.command_line_config.Global.ipython_dir
315 except AttributeError:
315 except AttributeError:
316 self.ipython_dir = self.default_config.Global.ipython_dir
316 self.ipython_dir = self.default_config.Global.ipython_dir
317 sys.path.append(os.path.abspath(self.ipython_dir))
317 sys.path.append(os.path.abspath(self.ipython_dir))
318 if not os.path.isdir(self.ipython_dir):
318 if not os.path.isdir(self.ipython_dir):
319 os.makedirs(self.ipython_dir, mode=0777)
319 os.makedirs(self.ipython_dir, mode=0777)
320 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
320 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
321
321
322 def find_resources(self):
322 def find_resources(self):
323 """Find other resources that need to be in place.
323 """Find other resources that need to be in place.
324
324
325 Things like cluster directories need to be in place to find the
325 Things like cluster directories need to be in place to find the
326 config file. These happen right after the IPython directory has
326 config file. These happen right after the IPython directory has
327 been set.
327 been set.
328 """
328 """
329 pass
329 pass
330
330
331 def find_config_file_name(self):
331 def find_config_file_name(self):
332 """Find the config file name for this application.
332 """Find the config file name for this application.
333
333
334 This must set ``self.config_file_name`` to the filename of the
334 This must set ``self.config_file_name`` to the filename of the
335 config file to use (just the filename). The search paths for the
335 config file to use (just the filename). The search paths for the
336 config file are set in :meth:`find_config_file_paths` and then passed
336 config file are set in :meth:`find_config_file_paths` and then passed
337 to the config file loader where they are resolved to an absolute path.
337 to the config file loader where they are resolved to an absolute path.
338
338
339 If a profile has been set at the command line, this will resolve it.
339 If a profile has been set at the command line, this will resolve it.
340 """
340 """
341
341
342 try:
342 try:
343 self.config_file_name = self.command_line_config.Global.config_file
343 self.config_file_name = self.command_line_config.Global.config_file
344 except AttributeError:
344 except AttributeError:
345 pass
345 pass
346
346
347 try:
347 try:
348 self.profile_name = self.command_line_config.Global.profile
348 self.profile_name = self.command_line_config.Global.profile
349 except AttributeError:
349 except AttributeError:
350 pass
350 pass
351 else:
351 else:
352 name_parts = self.config_file_name.split('.')
352 name_parts = self.config_file_name.split('.')
353 name_parts.insert(1, u'_' + self.profile_name + u'.')
353 name_parts.insert(1, u'_' + self.profile_name + u'.')
354 self.config_file_name = ''.join(name_parts)
354 self.config_file_name = ''.join(name_parts)
355
355
356 def find_config_file_paths(self):
356 def find_config_file_paths(self):
357 """Set the search paths for resolving the config file.
357 """Set the search paths for resolving the config file.
358
358
359 This must set ``self.config_file_paths`` to a sequence of search
359 This must set ``self.config_file_paths`` to a sequence of search
360 paths to pass to the config file loader.
360 paths to pass to the config file loader.
361 """
361 """
362 # Include our own profiles directory last, so that users can still find
362 # Include our own profiles directory last, so that users can still find
363 # our shipped copies of builtin profiles even if they don't have them
363 # our shipped copies of builtin profiles even if they don't have them
364 # in their local ipython directory.
364 # in their local ipython directory.
365 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
365 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
366 self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir)
366 self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir)
367
367
368 def pre_load_file_config(self):
368 def pre_load_file_config(self):
369 """Do actions before the config file is loaded."""
369 """Do actions before the config file is loaded."""
370 pass
370 pass
371
371
372 def load_file_config(self):
372 def load_file_config(self):
373 """Load the config file.
373 """Load the config file.
374
374
375 This tries to load the config file from disk. If successful, the
375 This tries to load the config file from disk. If successful, the
376 ``CONFIG_FILE`` config variable is set to the resolved config file
376 ``CONFIG_FILE`` config variable is set to the resolved config file
377 location. If not successful, an empty config is used.
377 location. If not successful, an empty config is used.
378 """
378 """
379 self.log.debug("Attempting to load config file: %s" %
379 self.log.debug("Attempting to load config file: %s" %
380 self.config_file_name)
380 self.config_file_name)
381 loader = PyFileConfigLoader(self.config_file_name,
381 loader = PyFileConfigLoader(self.config_file_name,
382 path=self.config_file_paths)
382 path=self.config_file_paths)
383 try:
383 try:
384 self.file_config = loader.load_config()
384 self.file_config = loader.load_config()
385 self.file_config.Global.config_file = loader.full_filename
385 self.file_config.Global.config_file = loader.full_filename
386 except IOError:
386 except IOError:
387 # Only warn if the default config file was NOT being used.
387 # Only warn if the default config file was NOT being used.
388 if not self.config_file_name==self.default_config_file_name:
388 if not self.config_file_name==self.default_config_file_name:
389 self.log.warn("Config file not found, skipping: %s" %
389 self.log.warn("Config file not found, skipping: %s" %
390 self.config_file_name, exc_info=True)
390 self.config_file_name, exc_info=True)
391 self.file_config = Config()
391 self.file_config = Config()
392 except:
392 except:
393 self.log.warn("Error loading config file: %s" %
393 self.log.warn("Error loading config file: %s" %
394 self.config_file_name, exc_info=True)
394 self.config_file_name, exc_info=True)
395 self.file_config = Config()
395 self.file_config = Config()
396
396
397 def set_file_config_log_level(self):
397 def set_file_config_log_level(self):
398 # We need to keeep self.log_level updated. But we only use the value
398 # We need to keeep self.log_level updated. But we only use the value
399 # of the file_config if a value was not specified at the command
399 # of the file_config if a value was not specified at the command
400 # line, because the command line overrides everything.
400 # line, because the command line overrides everything.
401 if not hasattr(self.command_line_config.Global, 'log_level'):
401 if not hasattr(self.command_line_config.Global, 'log_level'):
402 try:
402 try:
403 self.log_level = self.file_config.Global.log_level
403 self.log_level = self.file_config.Global.log_level
404 except AttributeError:
404 except AttributeError:
405 pass # Use existing value
405 pass # Use existing value
406
406
407 def post_load_file_config(self):
407 def post_load_file_config(self):
408 """Do actions after the config file is loaded."""
408 """Do actions after the config file is loaded."""
409 pass
409 pass
410
410
411 def log_file_config(self):
411 def log_file_config(self):
412 if hasattr(self.file_config.Global, 'config_file'):
412 if hasattr(self.file_config.Global, 'config_file'):
413 self.log.debug("Config file loaded: %s" %
413 self.log.debug("Config file loaded: %s" %
414 self.file_config.Global.config_file)
414 self.file_config.Global.config_file)
415 self.log.debug(repr(self.file_config))
415 self.log.debug(repr(self.file_config))
416
416
417 def merge_configs(self):
417 def merge_configs(self):
418 """Merge the default, command line and file config objects."""
418 """Merge the default, command line and file config objects."""
419 config = Config()
419 config = Config()
420 config._merge(self.default_config)
420 config._merge(self.default_config)
421 if self.override_config is None:
421 if self.override_config is None:
422 config._merge(self.file_config)
422 config._merge(self.file_config)
423 config._merge(self.command_line_config)
423 config._merge(self.command_line_config)
424 if self.constructor_config is not None:
424 if self.constructor_config is not None:
425 config._merge(self.constructor_config)
425 config._merge(self.constructor_config)
426 else:
426 else:
427 config._merge(self.override_config)
427 config._merge(self.override_config)
428 # XXX fperez - propose to Brian we rename master_config to simply
428 # XXX fperez - propose to Brian we rename master_config to simply
429 # config, I think this is going to be heavily used in examples and
429 # config, I think this is going to be heavily used in examples and
430 # application code and the name is shorter/easier to find/remember.
430 # application code and the name is shorter/easier to find/remember.
431 # For now, just alias it...
431 # For now, just alias it...
432 self.master_config = config
432 self.master_config = config
433 self.config = config
433 self.config = config
434
434
435 def log_master_config(self):
435 def log_master_config(self):
436 self.log.debug("Master config created:")
436 self.log.debug("Master config created:")
437 self.log.debug(repr(self.master_config))
437 self.log.debug(repr(self.master_config))
438
438
439 def pre_construct(self):
439 def pre_construct(self):
440 """Do actions after the config has been built, but before construct."""
440 """Do actions after the config has been built, but before construct."""
441 pass
441 pass
442
442
443 def construct(self):
443 def construct(self):
444 """Construct the main components that make up this app."""
444 """Construct the main components that make up this app."""
445 self.log.debug("Constructing components for application")
445 self.log.debug("Constructing components for application")
446
446
447 def post_construct(self):
447 def post_construct(self):
448 """Do actions after construct, but before starting the app."""
448 """Do actions after construct, but before starting the app."""
449 pass
449 pass
450
450
451 def start_app(self):
451 def start_app(self):
452 """Actually start the app."""
452 """Actually start the app."""
453 self.log.debug("Starting application")
453 self.log.debug("Starting application")
454
454
455 #-------------------------------------------------------------------------
455 #-------------------------------------------------------------------------
456 # Utility methods
456 # Utility methods
457 #-------------------------------------------------------------------------
457 #-------------------------------------------------------------------------
458
458
459 def abort(self):
459 def abort(self):
460 """Abort the starting of the application."""
460 """Abort the starting of the application."""
461 if self._exiting:
461 if self._exiting:
462 pass
462 pass
463 else:
463 else:
464 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
464 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
465 self._exiting = True
465 self._exiting = True
466 sys.exit(1)
466 sys.exit(1)
467
467
468 def exit(self, exit_status=0):
468 def exit(self, exit_status=0):
469 if self._exiting:
469 if self._exiting:
470 pass
470 pass
471 else:
471 else:
472 self.log.debug("Exiting application: %s" % self.name)
472 self.log.debug("Exiting application: %s" % self.name)
473 self._exiting = True
473 self._exiting = True
474 sys.exit(exit_status)
474 sys.exit(exit_status)
475
475
476 def attempt(self, func, action='abort'):
476 def attempt(self, func, action='abort'):
477 try:
477 try:
478 func()
478 func()
479 except SystemExit:
479 except SystemExit:
480 raise
480 raise
481 except:
481 except:
482 if action == 'abort':
482 if action == 'abort':
483 self.log.critical("Aborting application: %s" % self.name,
483 self.log.critical("Aborting application: %s" % self.name,
484 exc_info=True)
484 exc_info=True)
485 self.abort()
485 self.abort()
486 raise
486 raise
487 elif action == 'exit':
487 elif action == 'exit':
488 self.exit(0)
488 self.exit(0)
489
489
@@ -1,658 +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 """
47 """
48
48
49 #*****************************************************************************
49 #*****************************************************************************
50 #
50 #
51 # 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
52 # 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
53 # 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
54 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
55 #
55 #
56 # Copyright (C) 2008-2010 IPython Development Team
56 # Copyright (C) 2008-2010 IPython Development Team
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
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 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 import __builtin__
69 import __builtin__
70 import __main__
70 import __main__
71 import glob
71 import glob
72 import inspect
72 import itertools
73 import itertools
73 import keyword
74 import keyword
74 import os
75 import os
75 import re
76 import re
76 import shlex
77 import shlex
77 import sys
78 import sys
78 import types
79
79
80 import IPython.utils.rlineimpl as readline
81 from IPython.core.error import TryNext
80 from IPython.core.error import TryNext
82 from IPython.core.prefilter import ESC_MAGIC
81 from IPython.core.prefilter import ESC_MAGIC
83 from IPython.utils import generics
82 from IPython.utils import generics
84 from IPython.utils.genutils import debugx, dir2
83 from IPython.utils.frame import debugx
84 from IPython.utils.dir2 import dir2
85 import IPython.utils.rlineimpl as readline
85
86
86 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
87 # Globals
88 # Globals
88 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
89
90
90 # Public API
91 # Public API
91 __all__ = ['Completer','IPCompleter']
92 __all__ = ['Completer','IPCompleter']
92
93
93 if sys.platform == 'win32':
94 if sys.platform == 'win32':
94 PROTECTABLES = ' '
95 PROTECTABLES = ' '
95 else:
96 else:
96 PROTECTABLES = ' ()'
97 PROTECTABLES = ' ()'
97
98
98 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
99 # Main functions and classes
100 # Main functions and classes
100 #-----------------------------------------------------------------------------
101 #-----------------------------------------------------------------------------
101
102
102 def protect_filename(s):
103 def protect_filename(s):
103 """Escape a string to protect certain characters."""
104 """Escape a string to protect certain characters."""
104
105
105 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
106 for ch in s])
107 for ch in s])
107
108
108
109
109 def single_dir_expand(matches):
110 def single_dir_expand(matches):
110 "Recursively expand match lists containing a single dir."
111 "Recursively expand match lists containing a single dir."
111
112
112 if len(matches) == 1 and os.path.isdir(matches[0]):
113 if len(matches) == 1 and os.path.isdir(matches[0]):
113 # Takes care of links to directories also. Use '/'
114 # Takes care of links to directories also. Use '/'
114 # explicitly, even under Windows, so that name completions
115 # explicitly, even under Windows, so that name completions
115 # don't end up escaped.
116 # don't end up escaped.
116 d = matches[0]
117 d = matches[0]
117 if d[-1] in ['/','\\']:
118 if d[-1] in ['/','\\']:
118 d = d[:-1]
119 d = d[:-1]
119
120
120 subdirs = os.listdir(d)
121 subdirs = os.listdir(d)
121 if subdirs:
122 if subdirs:
122 matches = [ (d + '/' + p) for p in subdirs]
123 matches = [ (d + '/' + p) for p in subdirs]
123 return single_dir_expand(matches)
124 return single_dir_expand(matches)
124 else:
125 else:
125 return matches
126 return matches
126 else:
127 else:
127 return matches
128 return matches
128
129
129 class Bunch: pass
130 class Bunch: pass
130
131
131 class Completer:
132 class Completer:
132 def __init__(self,namespace=None,global_namespace=None):
133 def __init__(self,namespace=None,global_namespace=None):
133 """Create a new completer for the command line.
134 """Create a new completer for the command line.
134
135
135 Completer([namespace,global_namespace]) -> completer instance.
136 Completer([namespace,global_namespace]) -> completer instance.
136
137
137 If unspecified, the default namespace where completions are performed
138 If unspecified, the default namespace where completions are performed
138 is __main__ (technically, __main__.__dict__). Namespaces should be
139 is __main__ (technically, __main__.__dict__). Namespaces should be
139 given as dictionaries.
140 given as dictionaries.
140
141
141 An optional second namespace can be given. This allows the completer
142 An optional second namespace can be given. This allows the completer
142 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
143 distinguished.
144 distinguished.
144
145
145 Completer instances should be used as the completion mechanism of
146 Completer instances should be used as the completion mechanism of
146 readline via the set_completer() call:
147 readline via the set_completer() call:
147
148
148 readline.set_completer(Completer(my_namespace).complete)
149 readline.set_completer(Completer(my_namespace).complete)
149 """
150 """
150
151
151 # 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
152 # specific namespace or to use __main__.__dict__. This will allow us
153 # specific namespace or to use __main__.__dict__. This will allow us
153 # to bind to __main__.__dict__ at completion time, not now.
154 # to bind to __main__.__dict__ at completion time, not now.
154 if namespace is None:
155 if namespace is None:
155 self.use_main_ns = 1
156 self.use_main_ns = 1
156 else:
157 else:
157 self.use_main_ns = 0
158 self.use_main_ns = 0
158 self.namespace = namespace
159 self.namespace = namespace
159
160
160 # The global namespace, if given, can be bound directly
161 # The global namespace, if given, can be bound directly
161 if global_namespace is None:
162 if global_namespace is None:
162 self.global_namespace = {}
163 self.global_namespace = {}
163 else:
164 else:
164 self.global_namespace = global_namespace
165 self.global_namespace = global_namespace
165
166
166 def complete(self, text, state):
167 def complete(self, text, state):
167 """Return the next possible completion for 'text'.
168 """Return the next possible completion for 'text'.
168
169
169 This is called successively with state == 0, 1, 2, ... until it
170 This is called successively with state == 0, 1, 2, ... until it
170 returns None. The completion should begin with 'text'.
171 returns None. The completion should begin with 'text'.
171
172
172 """
173 """
173 if self.use_main_ns:
174 if self.use_main_ns:
174 self.namespace = __main__.__dict__
175 self.namespace = __main__.__dict__
175
176
176 if state == 0:
177 if state == 0:
177 if "." in text:
178 if "." in text:
178 self.matches = self.attr_matches(text)
179 self.matches = self.attr_matches(text)
179 else:
180 else:
180 self.matches = self.global_matches(text)
181 self.matches = self.global_matches(text)
181 try:
182 try:
182 return self.matches[state]
183 return self.matches[state]
183 except IndexError:
184 except IndexError:
184 return None
185 return None
185
186
186 def global_matches(self, text):
187 def global_matches(self, text):
187 """Compute matches when text is a simple name.
188 """Compute matches when text is a simple name.
188
189
189 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
190 defined in self.namespace or self.global_namespace that match.
191 defined in self.namespace or self.global_namespace that match.
191
192
192 """
193 """
193 #print 'Completer->global_matches, txt=%r' % text # dbg
194 #print 'Completer->global_matches, txt=%r' % text # dbg
194 matches = []
195 matches = []
195 match_append = matches.append
196 match_append = matches.append
196 n = len(text)
197 n = len(text)
197 for lst in [keyword.kwlist,
198 for lst in [keyword.kwlist,
198 __builtin__.__dict__.keys(),
199 __builtin__.__dict__.keys(),
199 self.namespace.keys(),
200 self.namespace.keys(),
200 self.global_namespace.keys()]:
201 self.global_namespace.keys()]:
201 for word in lst:
202 for word in lst:
202 if word[:n] == text and word != "__builtins__":
203 if word[:n] == text and word != "__builtins__":
203 match_append(word)
204 match_append(word)
204 return matches
205 return matches
205
206
206 def attr_matches(self, text):
207 def attr_matches(self, text):
207 """Compute matches when text contains a dot.
208 """Compute matches when text contains a dot.
208
209
209 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
210 evaluatable in self.namespace or self.global_namespace, it will be
211 evaluatable in self.namespace or self.global_namespace, it will be
211 evaluated and its attributes (as revealed by dir()) are used as
212 evaluated and its attributes (as revealed by dir()) are used as
212 possible completions. (For class instances, class members are are
213 possible completions. (For class instances, class members are are
213 also considered.)
214 also considered.)
214
215
215 WARNING: this can still invoke arbitrary C code, if an object
216 WARNING: this can still invoke arbitrary C code, if an object
216 with a __getattr__ hook is evaluated.
217 with a __getattr__ hook is evaluated.
217
218
218 """
219 """
219 import re
220
220
221 #print 'Completer->attr_matches, txt=%r' % text # dbg
221 #print 'Completer->attr_matches, txt=%r' % text # dbg
222 # Another option, seems to work great. Catches things like ''.<tab>
222 # Another option, seems to work great. Catches things like ''.<tab>
223 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
223 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
224
224
225 if not m:
225 if not m:
226 return []
226 return []
227
227
228 expr, attr = m.group(1, 3)
228 expr, attr = m.group(1, 3)
229 try:
229 try:
230 obj = eval(expr, self.namespace)
230 obj = eval(expr, self.namespace)
231 except:
231 except:
232 try:
232 try:
233 obj = eval(expr, self.global_namespace)
233 obj = eval(expr, self.global_namespace)
234 except:
234 except:
235 return []
235 return []
236
236
237 words = dir2(obj)
237 words = dir2(obj)
238
238
239 try:
239 try:
240 words = generics.complete_object(obj, words)
240 words = generics.complete_object(obj, words)
241 except TryNext:
241 except TryNext:
242 pass
242 pass
243 # Build match list to return
243 # Build match list to return
244 n = len(attr)
244 n = len(attr)
245 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 ]
246 return res
246 return res
247
247
248
248
249 class IPCompleter(Completer):
249 class IPCompleter(Completer):
250 """Extension of the completer class with IPython-specific features"""
250 """Extension of the completer class with IPython-specific features"""
251
251
252 def __init__(self,shell,namespace=None,global_namespace=None,
252 def __init__(self,shell,namespace=None,global_namespace=None,
253 omit__names=0,alias_table=None):
253 omit__names=0,alias_table=None):
254 """IPCompleter() -> completer
254 """IPCompleter() -> completer
255
255
256 Return a completer object suitable for use by the readline library
256 Return a completer object suitable for use by the readline library
257 via readline.set_completer().
257 via readline.set_completer().
258
258
259 Inputs:
259 Inputs:
260
260
261 - shell: a pointer to the ipython shell itself. This is needed
261 - shell: a pointer to the ipython shell itself. This is needed
262 because this completer knows about magic functions, and those can
262 because this completer knows about magic functions, and those can
263 only be accessed via the ipython instance.
263 only be accessed via the ipython instance.
264
264
265 - namespace: an optional dict where completions are performed.
265 - namespace: an optional dict where completions are performed.
266
266
267 - global_namespace: secondary optional dict for completions, to
267 - global_namespace: secondary optional dict for completions, to
268 handle cases (such as IPython embedded inside functions) where
268 handle cases (such as IPython embedded inside functions) where
269 both Python scopes are visible.
269 both Python scopes are visible.
270
270
271 - The optional omit__names parameter sets the completer to omit the
271 - The optional omit__names parameter sets the completer to omit the
272 'magic' names (__magicname__) for python objects unless the text
272 'magic' names (__magicname__) for python objects unless the text
273 to be completed explicitly starts with one or more underscores.
273 to be completed explicitly starts with one or more underscores.
274
274
275 - 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
276 to complete. """
276 to complete. """
277
277
278 Completer.__init__(self,namespace,global_namespace)
278 Completer.__init__(self,namespace,global_namespace)
279
279
280 self.magic_escape = ESC_MAGIC
280 self.magic_escape = ESC_MAGIC
281 self.readline = readline
281 self.readline = readline
282 delims = self.readline.get_completer_delims()
282 delims = self.readline.get_completer_delims()
283 delims = delims.replace(self.magic_escape,'')
283 delims = delims.replace(self.magic_escape,'')
284 self.readline.set_completer_delims(delims)
284 self.readline.set_completer_delims(delims)
285 self.get_line_buffer = self.readline.get_line_buffer
285 self.get_line_buffer = self.readline.get_line_buffer
286 self.get_endidx = self.readline.get_endidx
286 self.get_endidx = self.readline.get_endidx
287 self.omit__names = omit__names
287 self.omit__names = omit__names
288 self.merge_completions = shell.readline_merge_completions
288 self.merge_completions = shell.readline_merge_completions
289 self.shell = shell.shell
289 self.shell = shell.shell
290 if alias_table is None:
290 if alias_table is None:
291 alias_table = {}
291 alias_table = {}
292 self.alias_table = alias_table
292 self.alias_table = alias_table
293 # Regexp to split filenames with spaces in them
293 # Regexp to split filenames with spaces in them
294 self.space_name_re = re.compile(r'([^\\] )')
294 self.space_name_re = re.compile(r'([^\\] )')
295 # Hold a local ref. to glob.glob for speed
295 # Hold a local ref. to glob.glob for speed
296 self.glob = glob.glob
296 self.glob = glob.glob
297
297
298 # Determine if we are running on 'dumb' terminals, like (X)Emacs
298 # Determine if we are running on 'dumb' terminals, like (X)Emacs
299 # buffers, to avoid completion problems.
299 # buffers, to avoid completion problems.
300 term = os.environ.get('TERM','xterm')
300 term = os.environ.get('TERM','xterm')
301 self.dumb_terminal = term in ['dumb','emacs']
301 self.dumb_terminal = term in ['dumb','emacs']
302
302
303 # Special handling of backslashes needed in win32 platforms
303 # Special handling of backslashes needed in win32 platforms
304 if sys.platform == "win32":
304 if sys.platform == "win32":
305 self.clean_glob = self._clean_glob_win32
305 self.clean_glob = self._clean_glob_win32
306 else:
306 else:
307 self.clean_glob = self._clean_glob
307 self.clean_glob = self._clean_glob
308
308
309 # All active matcher routines for completion
309 # All active matcher routines for completion
310 self.matchers = [self.python_matches,
310 self.matchers = [self.python_matches,
311 self.file_matches,
311 self.file_matches,
312 self.magic_matches,
312 self.magic_matches,
313 self.alias_matches,
313 self.alias_matches,
314 self.python_func_kw_matches]
314 self.python_func_kw_matches]
315
315
316 # Code contributed by Alex Schmolck, for ipython/emacs integration
316 # Code contributed by Alex Schmolck, for ipython/emacs integration
317 def all_completions(self, text):
317 def all_completions(self, text):
318 """Return all possible completions for the benefit of emacs."""
318 """Return all possible completions for the benefit of emacs."""
319
319
320 completions = []
320 completions = []
321 comp_append = completions.append
321 comp_append = completions.append
322 try:
322 try:
323 for i in xrange(sys.maxint):
323 for i in xrange(sys.maxint):
324 res = self.complete(text, i)
324 res = self.complete(text, i)
325 if not res:
325 if not res:
326 break
326 break
327 comp_append(res)
327 comp_append(res)
328 #XXX workaround for ``notDefined.<tab>``
328 #XXX workaround for ``notDefined.<tab>``
329 except NameError:
329 except NameError:
330 pass
330 pass
331 return completions
331 return completions
332 # /end Alex Schmolck code.
332 # /end Alex Schmolck code.
333
333
334 def _clean_glob(self,text):
334 def _clean_glob(self,text):
335 return self.glob("%s*" % text)
335 return self.glob("%s*" % text)
336
336
337 def _clean_glob_win32(self,text):
337 def _clean_glob_win32(self,text):
338 return [f.replace("\\","/")
338 return [f.replace("\\","/")
339 for f in self.glob("%s*" % text)]
339 for f in self.glob("%s*" % text)]
340
340
341 def file_matches(self, text):
341 def file_matches(self, text):
342 """Match filenames, expanding ~USER type strings.
342 """Match filenames, expanding ~USER type strings.
343
343
344 Most of the seemingly convoluted logic in this completer is an
344 Most of the seemingly convoluted logic in this completer is an
345 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
346 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
347 GNU readline details needed for this to be done correctly.
347 GNU readline details needed for this to be done correctly.
348
348
349 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
350 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
351 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
352 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
353 better."""
353 better."""
354
354
355 #print 'Completer->file_matches: <%s>' % text # dbg
355 #print 'Completer->file_matches: <%s>' % text # dbg
356
356
357 # chars that require escaping with backslash - i.e. chars
357 # chars that require escaping with backslash - i.e. chars
358 # that readline treats incorrectly as delimiters, but we
358 # that readline treats incorrectly as delimiters, but we
359 # don't want to treat as delimiters in filename matching
359 # don't want to treat as delimiters in filename matching
360 # when escaped with backslash
360 # when escaped with backslash
361
361
362 if text.startswith('!'):
362 if text.startswith('!'):
363 text = text[1:]
363 text = text[1:]
364 text_prefix = '!'
364 text_prefix = '!'
365 else:
365 else:
366 text_prefix = ''
366 text_prefix = ''
367
367
368 lbuf = self.lbuf
368 lbuf = self.lbuf
369 open_quotes = 0 # track strings with open quotes
369 open_quotes = 0 # track strings with open quotes
370 try:
370 try:
371 lsplit = shlex.split(lbuf)[-1]
371 lsplit = shlex.split(lbuf)[-1]
372 except ValueError:
372 except ValueError:
373 # typically an unmatched ", or backslash without escaped char.
373 # typically an unmatched ", or backslash without escaped char.
374 if lbuf.count('"')==1:
374 if lbuf.count('"')==1:
375 open_quotes = 1
375 open_quotes = 1
376 lsplit = lbuf.split('"')[-1]
376 lsplit = lbuf.split('"')[-1]
377 elif lbuf.count("'")==1:
377 elif lbuf.count("'")==1:
378 open_quotes = 1
378 open_quotes = 1
379 lsplit = lbuf.split("'")[-1]
379 lsplit = lbuf.split("'")[-1]
380 else:
380 else:
381 return []
381 return []
382 except IndexError:
382 except IndexError:
383 # tab pressed on empty line
383 # tab pressed on empty line
384 lsplit = ""
384 lsplit = ""
385
385
386 if lsplit != protect_filename(lsplit):
386 if lsplit != protect_filename(lsplit):
387 # if protectables are found, do matching on the whole escaped
387 # if protectables are found, do matching on the whole escaped
388 # name
388 # name
389 has_protectables = 1
389 has_protectables = 1
390 text0,text = text,lsplit
390 text0,text = text,lsplit
391 else:
391 else:
392 has_protectables = 0
392 has_protectables = 0
393 text = os.path.expanduser(text)
393 text = os.path.expanduser(text)
394
394
395 if text == "":
395 if text == "":
396 return [text_prefix + protect_filename(f) for f in self.glob("*")]
396 return [text_prefix + protect_filename(f) for f in self.glob("*")]
397
397
398 m0 = self.clean_glob(text.replace('\\',''))
398 m0 = self.clean_glob(text.replace('\\',''))
399 if has_protectables:
399 if has_protectables:
400 # 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
401 # 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
402 # of the filename we have so far
402 # of the filename we have so far
403 len_lsplit = len(lsplit)
403 len_lsplit = len(lsplit)
404 matches = [text_prefix + text0 +
404 matches = [text_prefix + text0 +
405 protect_filename(f[len_lsplit:]) for f in m0]
405 protect_filename(f[len_lsplit:]) for f in m0]
406 else:
406 else:
407 if open_quotes:
407 if open_quotes:
408 # 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
409 # protect the names at all (and we _shouldn't_, as it
409 # protect the names at all (and we _shouldn't_, as it
410 # would cause bugs when the filesystem call is made).
410 # would cause bugs when the filesystem call is made).
411 matches = m0
411 matches = m0
412 else:
412 else:
413 matches = [text_prefix +
413 matches = [text_prefix +
414 protect_filename(f) for f in m0]
414 protect_filename(f) for f in m0]
415
415
416 #print 'mm',matches # dbg
416 #print 'mm',matches # dbg
417 return single_dir_expand(matches)
417 return single_dir_expand(matches)
418
418
419 def magic_matches(self, text):
419 def magic_matches(self, text):
420 """Match magics"""
420 """Match magics"""
421 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
421 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
422 # Get all shell magics now rather than statically, so magics loaded at
422 # Get all shell magics now rather than statically, so magics loaded at
423 # runtime show up too
423 # runtime show up too
424 magics = self.shell.lsmagic()
424 magics = self.shell.lsmagic()
425 pre = self.magic_escape
425 pre = self.magic_escape
426 baretext = text.lstrip(pre)
426 baretext = text.lstrip(pre)
427 return [ pre+m for m in magics if m.startswith(baretext)]
427 return [ pre+m for m in magics if m.startswith(baretext)]
428
428
429 def alias_matches(self, text):
429 def alias_matches(self, text):
430 """Match internal system aliases"""
430 """Match internal system aliases"""
431 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
431 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
432
432
433 # if we are not in the first 'item', alias matching
433 # if we are not in the first 'item', alias matching
434 # doesn't make sense - unless we are starting with 'sudo' command.
434 # doesn't make sense - unless we are starting with 'sudo' command.
435 if ' ' in self.lbuf.lstrip() and \
435 if ' ' in self.lbuf.lstrip() and \
436 not self.lbuf.lstrip().startswith('sudo'):
436 not self.lbuf.lstrip().startswith('sudo'):
437 return []
437 return []
438 text = os.path.expanduser(text)
438 text = os.path.expanduser(text)
439 aliases = self.alias_table.keys()
439 aliases = self.alias_table.keys()
440 if text == "":
440 if text == "":
441 return aliases
441 return aliases
442 else:
442 else:
443 return [alias for alias in aliases if alias.startswith(text)]
443 return [alias for alias in aliases if alias.startswith(text)]
444
444
445 def python_matches(self,text):
445 def python_matches(self,text):
446 """Match attributes or global python names"""
446 """Match attributes or global python names"""
447
447
448 #print 'Completer->python_matches, txt=%r' % text # dbg
448 #print 'Completer->python_matches, txt=%r' % text # dbg
449 if "." in text:
449 if "." in text:
450 try:
450 try:
451 matches = self.attr_matches(text)
451 matches = self.attr_matches(text)
452 if text.endswith('.') and self.omit__names:
452 if text.endswith('.') and self.omit__names:
453 if self.omit__names == 1:
453 if self.omit__names == 1:
454 # true if txt is _not_ a __ name, false otherwise:
454 # true if txt is _not_ a __ name, false otherwise:
455 no__name = (lambda txt:
455 no__name = (lambda txt:
456 re.match(r'.*\.__.*?__',txt) is None)
456 re.match(r'.*\.__.*?__',txt) is None)
457 else:
457 else:
458 # true if txt is _not_ a _ name, false otherwise:
458 # true if txt is _not_ a _ name, false otherwise:
459 no__name = (lambda txt:
459 no__name = (lambda txt:
460 re.match(r'.*\._.*?',txt) is None)
460 re.match(r'.*\._.*?',txt) is None)
461 matches = filter(no__name, matches)
461 matches = filter(no__name, matches)
462 except NameError:
462 except NameError:
463 # catches <undefined attributes>.<tab>
463 # catches <undefined attributes>.<tab>
464 matches = []
464 matches = []
465 else:
465 else:
466 matches = self.global_matches(text)
466 matches = self.global_matches(text)
467
467
468 return matches
468 return matches
469
469
470 def _default_arguments(self, obj):
470 def _default_arguments(self, obj):
471 """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,
472 or empty list otherwise."""
472 or empty list otherwise."""
473
473
474 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
474 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
475 # for classes, check for __init__,__new__
475 # for classes, check for __init__,__new__
476 if inspect.isclass(obj):
476 if inspect.isclass(obj):
477 obj = (getattr(obj,'__init__',None) or
477 obj = (getattr(obj,'__init__',None) or
478 getattr(obj,'__new__',None))
478 getattr(obj,'__new__',None))
479 # for all others, check if they are __call__able
479 # for all others, check if they are __call__able
480 elif hasattr(obj, '__call__'):
480 elif hasattr(obj, '__call__'):
481 obj = obj.__call__
481 obj = obj.__call__
482 # XXX: is there a way to handle the builtins ?
482 # XXX: is there a way to handle the builtins ?
483 try:
483 try:
484 args,_,_1,defaults = inspect.getargspec(obj)
484 args,_,_1,defaults = inspect.getargspec(obj)
485 if defaults:
485 if defaults:
486 return args[-len(defaults):]
486 return args[-len(defaults):]
487 except TypeError: pass
487 except TypeError: pass
488 return []
488 return []
489
489
490 def python_func_kw_matches(self,text):
490 def python_func_kw_matches(self,text):
491 """Match named parameters (kwargs) of the last open function"""
491 """Match named parameters (kwargs) of the last open function"""
492
492
493 if "." in text: # a parameter cannot be dotted
493 if "." in text: # a parameter cannot be dotted
494 return []
494 return []
495 try: regexp = self.__funcParamsRegex
495 try: regexp = self.__funcParamsRegex
496 except AttributeError:
496 except AttributeError:
497 regexp = self.__funcParamsRegex = re.compile(r'''
497 regexp = self.__funcParamsRegex = re.compile(r'''
498 '.*?' | # single quoted strings or
498 '.*?' | # single quoted strings or
499 ".*?" | # double quoted strings or
499 ".*?" | # double quoted strings or
500 \w+ | # identifier
500 \w+ | # identifier
501 \S # other characters
501 \S # other characters
502 ''', re.VERBOSE | re.DOTALL)
502 ''', re.VERBOSE | re.DOTALL)
503 # 1. find the nearest identifier that comes before an unclosed
503 # 1. find the nearest identifier that comes before an unclosed
504 # 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"
505 tokens = regexp.findall(self.get_line_buffer())
505 tokens = regexp.findall(self.get_line_buffer())
506 tokens.reverse()
506 tokens.reverse()
507 iterTokens = iter(tokens); openPar = 0
507 iterTokens = iter(tokens); openPar = 0
508 for token in iterTokens:
508 for token in iterTokens:
509 if token == ')':
509 if token == ')':
510 openPar -= 1
510 openPar -= 1
511 elif token == '(':
511 elif token == '(':
512 openPar += 1
512 openPar += 1
513 if openPar > 0:
513 if openPar > 0:
514 # found the last unclosed parenthesis
514 # found the last unclosed parenthesis
515 break
515 break
516 else:
516 else:
517 return []
517 return []
518 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
518 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
519 ids = []
519 ids = []
520 isId = re.compile(r'\w+$').match
520 isId = re.compile(r'\w+$').match
521 while True:
521 while True:
522 try:
522 try:
523 ids.append(iterTokens.next())
523 ids.append(iterTokens.next())
524 if not isId(ids[-1]):
524 if not isId(ids[-1]):
525 ids.pop(); break
525 ids.pop(); break
526 if not iterTokens.next() == '.':
526 if not iterTokens.next() == '.':
527 break
527 break
528 except StopIteration:
528 except StopIteration:
529 break
529 break
530 # lookup the candidate callable matches either using global_matches
530 # lookup the candidate callable matches either using global_matches
531 # or attr_matches for dotted names
531 # or attr_matches for dotted names
532 if len(ids) == 1:
532 if len(ids) == 1:
533 callableMatches = self.global_matches(ids[0])
533 callableMatches = self.global_matches(ids[0])
534 else:
534 else:
535 callableMatches = self.attr_matches('.'.join(ids[::-1]))
535 callableMatches = self.attr_matches('.'.join(ids[::-1]))
536 argMatches = []
536 argMatches = []
537 for callableMatch in callableMatches:
537 for callableMatch in callableMatches:
538 try:
538 try:
539 namedArgs = self._default_arguments(eval(callableMatch,
539 namedArgs = self._default_arguments(eval(callableMatch,
540 self.namespace))
540 self.namespace))
541 except:
541 except:
542 continue
542 continue
543 for namedArg in namedArgs:
543 for namedArg in namedArgs:
544 if namedArg.startswith(text):
544 if namedArg.startswith(text):
545 argMatches.append("%s=" %namedArg)
545 argMatches.append("%s=" %namedArg)
546 return argMatches
546 return argMatches
547
547
548 def dispatch_custom_completer(self,text):
548 def dispatch_custom_completer(self,text):
549 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
549 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
550 line = self.full_lbuf
550 line = self.full_lbuf
551 if not line.strip():
551 if not line.strip():
552 return None
552 return None
553
553
554 event = Bunch()
554 event = Bunch()
555 event.line = line
555 event.line = line
556 event.symbol = text
556 event.symbol = text
557 cmd = line.split(None,1)[0]
557 cmd = line.split(None,1)[0]
558 event.command = cmd
558 event.command = cmd
559 #print "\ncustom:{%s]\n" % event # dbg
559 #print "\ncustom:{%s]\n" % event # dbg
560
560
561 # for foo etc, try also to find completer for %foo
561 # for foo etc, try also to find completer for %foo
562 if not cmd.startswith(self.magic_escape):
562 if not cmd.startswith(self.magic_escape):
563 try_magic = self.custom_completers.s_matches(
563 try_magic = self.custom_completers.s_matches(
564 self.magic_escape + cmd)
564 self.magic_escape + cmd)
565 else:
565 else:
566 try_magic = []
566 try_magic = []
567
567
568 for c in itertools.chain(self.custom_completers.s_matches(cmd),
568 for c in itertools.chain(self.custom_completers.s_matches(cmd),
569 try_magic,
569 try_magic,
570 self.custom_completers.flat_matches(self.lbuf)):
570 self.custom_completers.flat_matches(self.lbuf)):
571 #print "try",c # dbg
571 #print "try",c # dbg
572 try:
572 try:
573 res = c(event)
573 res = c(event)
574 # first, try case sensitive match
574 # first, try case sensitive match
575 withcase = [r for r in res if r.startswith(text)]
575 withcase = [r for r in res if r.startswith(text)]
576 if withcase:
576 if withcase:
577 return withcase
577 return withcase
578 # if none, then case insensitive ones are ok too
578 # if none, then case insensitive ones are ok too
579 text_low = text.lower()
579 text_low = text.lower()
580 return [r for r in res if r.lower().startswith(text_low)]
580 return [r for r in res if r.lower().startswith(text_low)]
581 except TryNext:
581 except TryNext:
582 pass
582 pass
583
583
584 return None
584 return None
585
585
586 def complete(self, text, state,line_buffer=None):
586 def complete(self, text, state,line_buffer=None):
587 """Return the next possible completion for 'text'.
587 """Return the next possible completion for 'text'.
588
588
589 This is called successively with state == 0, 1, 2, ... until it
589 This is called successively with state == 0, 1, 2, ... until it
590 returns None. The completion should begin with 'text'.
590 returns None. The completion should begin with 'text'.
591
591
592 :Keywords:
592 :Keywords:
593 - line_buffer: string
593 - line_buffer: string
594 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
595 via readline. This keyword allows clients which are requesting for
595 via readline. This keyword allows clients which are requesting for
596 text completions in non-readline contexts to inform the completer of
596 text completions in non-readline contexts to inform the completer of
597 the entire text.
597 the entire text.
598 """
598 """
599
599
600 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
600 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
601
601
602 # 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
603 # of the mostly useless 'do you want to see all million
603 # of the mostly useless 'do you want to see all million
604 # completions' message, just do the right thing and give the user
604 # completions' message, just do the right thing and give the user
605 # his tab! Incidentally, this enables pasting of tabbed text from
605 # his tab! Incidentally, this enables pasting of tabbed text from
606 # an editor (as long as autoindent is off).
606 # an editor (as long as autoindent is off).
607
607
608 # It should be noted that at least pyreadline still shows
608 # It should be noted that at least pyreadline still shows
609 # file completions - is there a way around it?
609 # file completions - is there a way around it?
610
610
611 # 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
612 # don't interfere with their own tab-completion mechanism.
612 # don't interfere with their own tab-completion mechanism.
613 if line_buffer is None:
613 if line_buffer is None:
614 self.full_lbuf = self.get_line_buffer()
614 self.full_lbuf = self.get_line_buffer()
615 else:
615 else:
616 self.full_lbuf = line_buffer
616 self.full_lbuf = line_buffer
617
617
618 if not (self.dumb_terminal or self.full_lbuf.strip()):
618 if not (self.dumb_terminal or self.full_lbuf.strip()):
619 self.readline.insert_text('\t')
619 self.readline.insert_text('\t')
620 return None
620 return None
621
621
622 magic_escape = self.magic_escape
622 magic_escape = self.magic_escape
623
623
624 self.lbuf = self.full_lbuf[:self.get_endidx()]
624 self.lbuf = self.full_lbuf[:self.get_endidx()]
625
625
626 try:
626 try:
627 if text.startswith('~'):
627 if text.startswith('~'):
628 text = os.path.expanduser(text)
628 text = os.path.expanduser(text)
629 if state == 0:
629 if state == 0:
630 custom_res = self.dispatch_custom_completer(text)
630 custom_res = self.dispatch_custom_completer(text)
631 if custom_res is not None:
631 if custom_res is not None:
632 # did custom completers produce something?
632 # did custom completers produce something?
633 self.matches = custom_res
633 self.matches = custom_res
634 else:
634 else:
635 # Extend the list of completions with the results of each
635 # Extend the list of completions with the results of each
636 # matcher, so we return results to the user from all
636 # matcher, so we return results to the user from all
637 # namespaces.
637 # namespaces.
638 if self.merge_completions:
638 if self.merge_completions:
639 self.matches = []
639 self.matches = []
640 for matcher in self.matchers:
640 for matcher in self.matchers:
641 self.matches.extend(matcher(text))
641 self.matches.extend(matcher(text))
642 else:
642 else:
643 for matcher in self.matchers:
643 for matcher in self.matchers:
644 self.matches = matcher(text)
644 self.matches = matcher(text)
645 if self.matches:
645 if self.matches:
646 break
646 break
647 self.matches = list(set(self.matches))
647 self.matches = list(set(self.matches))
648 try:
648 try:
649 #print "MATCH: %r" % self.matches[state] # dbg
649 #print "MATCH: %r" % self.matches[state] # dbg
650 return self.matches[state]
650 return self.matches[state]
651 except IndexError:
651 except IndexError:
652 return None
652 return None
653 except:
653 except:
654 #from IPython.core.ultratb import AutoFormattedTB; # dbg
654 #from IPython.core.ultratb import AutoFormattedTB; # dbg
655 #tb=AutoFormattedTB('Verbose');tb() #dbg
655 #tb=AutoFormattedTB('Verbose');tb() #dbg
656
656
657 # If completion fails, don't annoy the user.
657 # If completion fails, don't annoy the user.
658 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,223 +1,223 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: 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
4
5 Authors
5 Authors
6 -------
6 -------
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
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) 2008-2009 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
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 # Required modules
20
20
21 # From the standard library
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
26 # Our own
27 from IPython.core import release
27 from IPython.core import release
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.utils.genutils import sys_info
29 from IPython.utils.sysinfo import sys_info
30
30
31 from IPython.external.Itpl import itpl
31 from IPython.external.Itpl import itpl
32
32
33 #****************************************************************************
33 #****************************************************************************
34
34
35 class CrashHandler(object):
35 class CrashHandler(object):
36 """Customizable crash handlers for IPython-based systems.
36 """Customizable crash handlers for IPython-based systems.
37
37
38 Instances of this class provide a __call__ method which can be used as a
38 Instances of this class provide a __call__ method which can be used as a
39 sys.excepthook, i.e., the __call__ signature is:
39 sys.excepthook, i.e., the __call__ signature is:
40
40
41 def __call__(self,etype, evalue, etb)
41 def __call__(self,etype, evalue, etb)
42
42
43 """
43 """
44
44
45 def __init__(self,app, app_name, contact_name=None, contact_email=None,
45 def __init__(self,app, app_name, contact_name=None, contact_email=None,
46 bug_tracker=None, crash_report_fname='CrashReport.txt',
46 bug_tracker=None, crash_report_fname='CrashReport.txt',
47 show_crash_traceback=True, call_pdb=False):
47 show_crash_traceback=True, call_pdb=False):
48 """New crash handler.
48 """New crash handler.
49
49
50 Inputs:
50 Inputs:
51
51
52 - app: a running application instance, which will be queried at crash
52 - app: a running application instance, which will be queried at crash
53 time for internal information.
53 time for internal information.
54
54
55 - app_name: a string containing the name of your application.
55 - app_name: a string containing the name of your application.
56
56
57 - contact_name: a string with the name of the person to contact.
57 - contact_name: a string with the name of the person to contact.
58
58
59 - contact_email: a string with the email address of the contact.
59 - contact_email: a string with the email address of the contact.
60
60
61 - bug_tracker: a string with the URL for your project's bug tracker.
61 - bug_tracker: a string with the URL for your project's bug tracker.
62
62
63 - crash_report_fname: a string with the filename for the crash report
63 - crash_report_fname: a string with the filename for the crash report
64 to be saved in. These reports are left in the ipython user directory
64 to be saved in. These reports are left in the ipython user directory
65 as determined by the running IPython instance.
65 as determined by the running IPython instance.
66
66
67 Optional inputs:
67 Optional inputs:
68
68
69 - show_crash_traceback(True): if false, don't print the crash
69 - show_crash_traceback(True): if false, don't print the crash
70 traceback on stderr, only generate the on-disk report
70 traceback on stderr, only generate the on-disk report
71
71
72
72
73 Non-argument instance attributes:
73 Non-argument instance attributes:
74
74
75 These instances contain some non-argument attributes which allow for
75 These instances contain some non-argument attributes which allow for
76 further customization of the crash handler's behavior. Please see the
76 further customization of the crash handler's behavior. Please see the
77 source for further details.
77 source for further details.
78 """
78 """
79
79
80 # apply args into instance
80 # apply args into instance
81 self.app = app
81 self.app = app
82 self.app_name = app_name
82 self.app_name = app_name
83 self.contact_name = contact_name
83 self.contact_name = contact_name
84 self.contact_email = contact_email
84 self.contact_email = contact_email
85 self.bug_tracker = bug_tracker
85 self.bug_tracker = bug_tracker
86 self.crash_report_fname = crash_report_fname
86 self.crash_report_fname = crash_report_fname
87 self.show_crash_traceback = show_crash_traceback
87 self.show_crash_traceback = show_crash_traceback
88 self.section_sep = '\n\n'+'*'*75+'\n\n'
88 self.section_sep = '\n\n'+'*'*75+'\n\n'
89 self.call_pdb = call_pdb
89 self.call_pdb = call_pdb
90 #self.call_pdb = True # dbg
90 #self.call_pdb = True # dbg
91
91
92 # Hardcoded defaults, which can be overridden either by subclasses or
92 # Hardcoded defaults, which can be overridden either by subclasses or
93 # at runtime for the instance.
93 # at runtime for the instance.
94
94
95 # Template for the user message. Subclasses which completely override
95 # Template for the user message. Subclasses which completely override
96 # this, or user apps, can modify it to suit their tastes. It gets
96 # this, or user apps, can modify it to suit their tastes. It gets
97 # expanded using itpl, so calls of the kind $self.foo are valid.
97 # expanded using itpl, so calls of the kind $self.foo are valid.
98 self.user_message_template = """
98 self.user_message_template = """
99 Oops, $self.app_name crashed. We do our best to make it stable, but...
99 Oops, $self.app_name crashed. We do our best to make it stable, but...
100
100
101 A crash report was automatically generated with the following information:
101 A crash report was automatically generated with the following information:
102 - A verbatim copy of the crash traceback.
102 - A verbatim copy of the crash traceback.
103 - A copy of your input history during this session.
103 - A copy of your input history during this session.
104 - Data on your current $self.app_name configuration.
104 - Data on your current $self.app_name configuration.
105
105
106 It was left in the file named:
106 It was left in the file named:
107 \t'$self.crash_report_fname'
107 \t'$self.crash_report_fname'
108 If you can email this file to the developers, the information in it will help
108 If you can email this file to the developers, the information in it will help
109 them in understanding and correcting the problem.
109 them in understanding and correcting the problem.
110
110
111 You can mail it to: $self.contact_name at $self.contact_email
111 You can mail it to: $self.contact_name at $self.contact_email
112 with the subject '$self.app_name Crash Report'.
112 with the subject '$self.app_name Crash Report'.
113
113
114 If you want to do it now, the following command will work (under Unix):
114 If you want to do it now, the following command will work (under Unix):
115 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
115 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
116
116
117 To ensure accurate tracking of this issue, please file a report about it at:
117 To ensure accurate tracking of this issue, please file a report about it at:
118 $self.bug_tracker
118 $self.bug_tracker
119 """
119 """
120
120
121 def __call__(self,etype, evalue, etb):
121 def __call__(self,etype, evalue, etb):
122 """Handle an exception, call for compatible with sys.excepthook"""
122 """Handle an exception, call for compatible with sys.excepthook"""
123
123
124 # Report tracebacks shouldn't use color in general (safer for users)
124 # Report tracebacks shouldn't use color in general (safer for users)
125 color_scheme = 'NoColor'
125 color_scheme = 'NoColor'
126
126
127 # Use this ONLY for developer debugging (keep commented out for release)
127 # Use this ONLY for developer debugging (keep commented out for release)
128 #color_scheme = 'Linux' # dbg
128 #color_scheme = 'Linux' # dbg
129
129
130 try:
130 try:
131 rptdir = self.app.ipython_dir
131 rptdir = self.app.ipython_dir
132 except:
132 except:
133 rptdir = os.getcwd()
133 rptdir = os.getcwd()
134 if not os.path.isdir(rptdir):
134 if not os.path.isdir(rptdir):
135 rptdir = os.getcwd()
135 rptdir = os.getcwd()
136 report_name = os.path.join(rptdir,self.crash_report_fname)
136 report_name = os.path.join(rptdir,self.crash_report_fname)
137 # write the report filename into the instance dict so it can get
137 # write the report filename into the instance dict so it can get
138 # properly expanded out in the user message template
138 # properly expanded out in the user message template
139 self.crash_report_fname = report_name
139 self.crash_report_fname = report_name
140 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
140 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
141 long_header=1,
141 long_header=1,
142 call_pdb=self.call_pdb,
142 call_pdb=self.call_pdb,
143 )
143 )
144 if self.call_pdb:
144 if self.call_pdb:
145 TBhandler(etype,evalue,etb)
145 TBhandler(etype,evalue,etb)
146 return
146 return
147 else:
147 else:
148 traceback = TBhandler.text(etype,evalue,etb,context=31)
148 traceback = TBhandler.text(etype,evalue,etb,context=31)
149
149
150 # print traceback to screen
150 # print traceback to screen
151 if self.show_crash_traceback:
151 if self.show_crash_traceback:
152 print >> sys.stderr, traceback
152 print >> sys.stderr, traceback
153
153
154 # and generate a complete report on disk
154 # and generate a complete report on disk
155 try:
155 try:
156 report = open(report_name,'w')
156 report = open(report_name,'w')
157 except:
157 except:
158 print >> sys.stderr, 'Could not create crash report on disk.'
158 print >> sys.stderr, 'Could not create crash report on disk.'
159 return
159 return
160
160
161 # Inform user on stderr of what happened
161 # Inform user on stderr of what happened
162 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
162 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
163 print >> sys.stderr, msg
163 print >> sys.stderr, msg
164
164
165 # Construct report on disk
165 # Construct report on disk
166 report.write(self.make_report(traceback))
166 report.write(self.make_report(traceback))
167 report.close()
167 report.close()
168 raw_input("Hit <Enter> to quit this message (your terminal may close):")
168 raw_input("Hit <Enter> to quit this message (your terminal may close):")
169
169
170 def make_report(self,traceback):
170 def make_report(self,traceback):
171 """Return a string containing a crash report."""
171 """Return a string containing a crash report."""
172
172
173 sec_sep = self.section_sep
173 sec_sep = self.section_sep
174
174
175 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
175 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
176 rpt_add = report.append
176 rpt_add = report.append
177 rpt_add(sys_info())
177 rpt_add(sys_info())
178
178
179 try:
179 try:
180 config = pformat(self.app.config)
180 config = pformat(self.app.config)
181 rpt_add(sec_sep+'Current user configuration structure:\n\n')
181 rpt_add(sec_sep+'Current user configuration structure:\n\n')
182 rpt_add(config)
182 rpt_add(config)
183 except:
183 except:
184 pass
184 pass
185 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
185 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
186
186
187 return ''.join(report)
187 return ''.join(report)
188
188
189
189
190 class IPythonCrashHandler(CrashHandler):
190 class IPythonCrashHandler(CrashHandler):
191 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
191 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
192
192
193 def __init__(self, app, app_name='IPython'):
193 def __init__(self, app, app_name='IPython'):
194
194
195 # Set here which of the IPython authors should be listed as contact
195 # Set here which of the IPython authors should be listed as contact
196 AUTHOR_CONTACT = 'Fernando'
196 AUTHOR_CONTACT = 'Fernando'
197
197
198 # Set argument defaults
198 # Set argument defaults
199 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
199 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
200 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
200 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
201 crash_report_fname = 'IPython_crash_report.txt'
201 crash_report_fname = 'IPython_crash_report.txt'
202 # Call parent constructor
202 # Call parent constructor
203 CrashHandler.__init__(self,app,app_name,contact_name,contact_email,
203 CrashHandler.__init__(self,app,app_name,contact_name,contact_email,
204 bug_tracker,crash_report_fname)
204 bug_tracker,crash_report_fname)
205
205
206 def make_report(self,traceback):
206 def make_report(self,traceback):
207 """Return a string containing a crash report."""
207 """Return a string containing a crash report."""
208
208
209 sec_sep = self.section_sep
209 sec_sep = self.section_sep
210 # Start with parent report
210 # Start with parent report
211 report = [super(IPythonCrashHandler, self).make_report(traceback)]
211 report = [super(IPythonCrashHandler, self).make_report(traceback)]
212 # Add interactive-specific info we may have
212 # Add interactive-specific info we may have
213 rpt_add = report.append
213 rpt_add = report.append
214 try:
214 try:
215 rpt_add(sec_sep+"History of session input:")
215 rpt_add(sec_sep+"History of session input:")
216 for line in self.app.shell.user_ns['_ih']:
216 for line in self.app.shell.user_ns['_ih']:
217 rpt_add(line)
217 rpt_add(line)
218 rpt_add('\n*** Last line of input (may not be in above history):\n')
218 rpt_add('\n*** Last line of input (may not be in above history):\n')
219 rpt_add(self.app.shell._last_input_line+'\n')
219 rpt_add(self.app.shell._last_input_line+'\n')
220 except:
220 except:
221 pass
221 pass
222
222
223 return ''.join(report)
223 return ''.join(report)
@@ -1,512 +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)
480
478
481 def checkline(self, filename, lineno):
479 def checkline(self, filename, lineno):
482 """Check whether specified line seems to be executable.
480 """Check whether specified line seems to be executable.
483
481
484 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
485 line or EOF). Warning: testing is not comprehensive.
483 line or EOF). Warning: testing is not comprehensive.
486 """
484 """
487 #######################################################################
485 #######################################################################
488 # XXX Hack! Use python-2.5 compatible code for this call, because with
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
489 # all of our changes, we've drifted from the pdb api in 2.6. For now,
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
490 # changing:
488 # changing:
491 #
489 #
492 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
493 # to:
491 # to:
494 #
492 #
495 line = linecache.getline(filename, lineno)
493 line = linecache.getline(filename, lineno)
496 #
494 #
497 # does the trick. But in reality, we need to fix this by reconciling
495 # does the trick. But in reality, we need to fix this by reconciling
498 # our updates with the new Pdb APIs in Python 2.6.
496 # our updates with the new Pdb APIs in Python 2.6.
499 #
497 #
500 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
501 #######################################################################
499 #######################################################################
502
500
503 if not line:
501 if not line:
504 print >>self.stdout, 'End of file'
502 print >>self.stdout, 'End of file'
505 return 0
503 return 0
506 line = line.strip()
504 line = line.strip()
507 # Don't allow setting breakpoint at a blank line
505 # Don't allow setting breakpoint at a blank line
508 if (not line or (line[0] == '#') or
506 if (not line or (line[0] == '#') or
509 (line[:3] == '"""') or line[:3] == "'''"):
507 (line[:3] == '"""') or line[:3] == "'''"):
510 print >>self.stdout, '*** Blank or comment'
508 print >>self.stdout, '*** Blank or comment'
511 return 0
509 return 0
512 return lineno
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,276 +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
18 By default, input history is printed without line numbers so it can be
19 By default, input history is printed without line numbers so it can be
19 directly pasted into an editor.
20 directly pasted into an editor.
20
21
21 With -n, each input's number <n> is shown, and is accessible as the
22 With -n, each input's number <n> is shown, and is accessible as the
22 automatically generated variable _i<n> as well as In[<n>]. Multi-line
23 automatically generated variable _i<n> as well as In[<n>]. Multi-line
23 statements are printed starting at a new line for easy copy/paste.
24 statements are printed starting at a new line for easy copy/paste.
24
25
25 Options:
26 Options:
26
27
27 -n: print line numbers for each input.
28 -n: print line numbers for each input.
28 This feature is only available if numbered prompts are in use.
29 This feature is only available if numbered prompts are in use.
29
30
30 -o: also print outputs for each input.
31 -o: also print outputs for each input.
31
32
32 -p: print classic '>>>' python prompts before each input. This is useful
33 -p: print classic '>>>' python prompts before each input. This is useful
33 for making documentation, and in conjunction with -o, for producing
34 for making documentation, and in conjunction with -o, for producing
34 doctest-ready output.
35 doctest-ready output.
35
36
36 -t: (default) print the 'translated' history, as IPython understands it.
37 -t: (default) print the 'translated' history, as IPython understands it.
37 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
38 before executing it (things like magics or aliases are turned into
39 before executing it (things like magics or aliases are turned into
39 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
40 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
41 '_ip.magic("%cd /")' instead of '%cd /'.
42 '_ip.magic("%cd /")' instead of '%cd /'.
42
43
43 -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.
44
45
45 -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.
46 This includes the "shadow history" (almost all commands ever written).
47 This includes the "shadow history" (almost all commands ever written).
47 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).
48 In shadow history, every index nuwber starts with 0.
49 In shadow history, every index nuwber starts with 0.
49
50
50 -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
51 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
52 confirmation first if it already exists.
53 confirmation first if it already exists.
53 """
54 """
54
55
55 if not self.outputcache.do_full_cache:
56 if not self.outputcache.do_full_cache:
56 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.'
57 return
58 return
58 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
59 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
59
60
60 # Check if output to specific file was requested.
61 # Check if output to specific file was requested.
61 try:
62 try:
62 outfname = opts['f']
63 outfname = opts['f']
63 except KeyError:
64 except KeyError:
64 outfile = Term.cout # default
65 outfile = Term.cout # default
65 # We don't want to close stdout at the end!
66 # We don't want to close stdout at the end!
66 close_at_end = False
67 close_at_end = False
67 else:
68 else:
68 if os.path.exists(outfname):
69 if os.path.exists(outfname):
69 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
70 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
70 print 'Aborting.'
71 print 'Aborting.'
71 return
72 return
72
73
73 outfile = open(outfname,'w')
74 outfile = open(outfname,'w')
74 close_at_end = True
75 close_at_end = True
75
76
76 if 't' in opts:
77 if 't' in opts:
77 input_hist = self.input_hist
78 input_hist = self.input_hist
78 elif 'r' in opts:
79 elif 'r' in opts:
79 input_hist = self.input_hist_raw
80 input_hist = self.input_hist_raw
80 else:
81 else:
81 input_hist = self.input_hist
82 input_hist = self.input_hist
82
83
83 default_length = 40
84 default_length = 40
84 pattern = None
85 pattern = None
85 if 'g' in opts:
86 if 'g' in opts:
86 init = 1
87 init = 1
87 final = len(input_hist)
88 final = len(input_hist)
88 parts = parameter_s.split(None, 1)
89 parts = parameter_s.split(None, 1)
89 if len(parts) == 1:
90 if len(parts) == 1:
90 parts += '*'
91 parts += '*'
91 head, pattern = parts
92 head, pattern = parts
92 pattern = "*" + pattern + "*"
93 pattern = "*" + pattern + "*"
93 elif len(args) == 0:
94 elif len(args) == 0:
94 final = len(input_hist)-1
95 final = len(input_hist)-1
95 init = max(1,final-default_length)
96 init = max(1,final-default_length)
96 elif len(args) == 1:
97 elif len(args) == 1:
97 final = len(input_hist)
98 final = len(input_hist)
98 init = max(1, final-int(args[0]))
99 init = max(1, final-int(args[0]))
99 elif len(args) == 2:
100 elif len(args) == 2:
100 init, final = map(int, args)
101 init, final = map(int, args)
101 else:
102 else:
102 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
103 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
103 print >> Term.cout, self.magic_hist.__doc__
104 print >> Term.cout, self.magic_hist.__doc__
104 return
105 return
105
106
106 width = len(str(final))
107 width = len(str(final))
107 line_sep = ['','\n']
108 line_sep = ['','\n']
108 print_nums = 'n' in opts
109 print_nums = 'n' in opts
109 print_outputs = 'o' in opts
110 print_outputs = 'o' in opts
110 pyprompts = 'p' in opts
111 pyprompts = 'p' in opts
111
112
112 found = False
113 found = False
113 if pattern is not None:
114 if pattern is not None:
114 sh = self.shadowhist.all()
115 sh = self.shadowhist.all()
115 for idx, s in sh:
116 for idx, s in sh:
116 if fnmatch.fnmatch(s, pattern):
117 if fnmatch.fnmatch(s, pattern):
117 print >> outfile, "0%d: %s" %(idx, s)
118 print >> outfile, "0%d: %s" %(idx, s)
118 found = True
119 found = True
119
120
120 if found:
121 if found:
121 print >> outfile, "==="
122 print >> outfile, "==="
122 print >> outfile, \
123 print >> outfile, \
123 "shadow history ends, fetch by %rep <number> (must start with 0)"
124 "shadow history ends, fetch by %rep <number> (must start with 0)"
124 print >> outfile, "=== start of normal history ==="
125 print >> outfile, "=== start of normal history ==="
125
126
126 for in_num in range(init,final):
127 for in_num in range(init,final):
127 inline = input_hist[in_num]
128 inline = input_hist[in_num]
128 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
129 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
129 continue
130 continue
130
131
131 multiline = int(inline.count('\n') > 1)
132 multiline = int(inline.count('\n') > 1)
132 if print_nums:
133 if print_nums:
133 print >> outfile, \
134 print >> outfile, \
134 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
135 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
135 if pyprompts:
136 if pyprompts:
136 print >> outfile, '>>>',
137 print >> outfile, '>>>',
137 if multiline:
138 if multiline:
138 lines = inline.splitlines()
139 lines = inline.splitlines()
139 print >> outfile, '\n... '.join(lines)
140 print >> outfile, '\n... '.join(lines)
140 print >> outfile, '... '
141 print >> outfile, '... '
141 else:
142 else:
142 print >> outfile, inline,
143 print >> outfile, inline,
143 else:
144 else:
144 print >> outfile, inline,
145 print >> outfile, inline,
145 if print_outputs:
146 if print_outputs:
146 output = self.shell.user_ns['Out'].get(in_num)
147 output = self.shell.user_ns['Out'].get(in_num)
147 if output is not None:
148 if output is not None:
148 print >> outfile, repr(output)
149 print >> outfile, repr(output)
149
150
150 if close_at_end:
151 if close_at_end:
151 outfile.close()
152 outfile.close()
152
153
153
154
154 def magic_hist(self, parameter_s=''):
155 def magic_hist(self, parameter_s=''):
155 """Alternate name for %history."""
156 """Alternate name for %history."""
156 return self.magic_history(parameter_s)
157 return self.magic_history(parameter_s)
157
158
158
159
159 def rep_f(self, arg):
160 def rep_f(self, arg):
160 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
161
162
162 - %rep (no arguments):
163 - %rep (no arguments):
163
164
164 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 '_'
165 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
166 lines without using copy-paste::
167 lines without using copy-paste::
167
168
168 $ l = ["hei", "vaan"]
169 $ l = ["hei", "vaan"]
169 $ "".join(l)
170 $ "".join(l)
170 ==> heivaan
171 ==> heivaan
171 $ %rep
172 $ %rep
172 $ heivaan_ <== cursor blinking
173 $ heivaan_ <== cursor blinking
173
174
174 %rep 45
175 %rep 45
175
176
176 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
177 number.
178 number.
178
179
179 %rep 1-4 6-7 3
180 %rep 1-4 6-7 3
180
181
181 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
182 in %macro and %save.
183 in %macro and %save.
183
184
184 %rep foo
185 %rep foo
185
186
186 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.
187 (e.g. 'svn ci -m foobar').
188 (e.g. 'svn ci -m foobar').
188 """
189 """
189
190
190 opts,args = self.parse_options(arg,'',mode='list')
191 opts,args = self.parse_options(arg,'',mode='list')
191 if not args:
192 if not args:
192 self.set_next_input(str(self.user_ns["_"]))
193 self.set_next_input(str(self.user_ns["_"]))
193 return
194 return
194
195
195 if len(args) == 1 and not '-' in args[0]:
196 if len(args) == 1 and not '-' in args[0]:
196 arg = args[0]
197 arg = args[0]
197 if len(arg) > 1 and arg.startswith('0'):
198 if len(arg) > 1 and arg.startswith('0'):
198 # get from shadow hist
199 # get from shadow hist
199 num = int(arg[1:])
200 num = int(arg[1:])
200 line = self.shadowhist.get(num)
201 line = self.shadowhist.get(num)
201 self.set_next_input(str(line))
202 self.set_next_input(str(line))
202 return
203 return
203 try:
204 try:
204 num = int(args[0])
205 num = int(args[0])
205 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
206 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
206 return
207 return
207 except ValueError:
208 except ValueError:
208 pass
209 pass
209
210
210 for h in reversed(self.input_hist_raw):
211 for h in reversed(self.input_hist_raw):
211 if 'rep' in h:
212 if 'rep' in h:
212 continue
213 continue
213 if fnmatch.fnmatch(h,'*' + arg + '*'):
214 if fnmatch.fnmatch(h,'*' + arg + '*'):
214 self.set_next_input(str(h).rstrip())
215 self.set_next_input(str(h).rstrip())
215 return
216 return
216
217
217 try:
218 try:
218 lines = self.extract_input_slices(args, True)
219 lines = self.extract_input_slices(args, True)
219 print "lines",lines
220 print "lines",lines
220 self.runlines(lines)
221 self.runlines(lines)
221 except ValueError:
222 except ValueError:
222 print "Not found in recent history:", args
223 print "Not found in recent history:", args
223
224
224
225
225 _sentinel = object()
226 _sentinel = object()
226
227
227 class ShadowHist(object):
228 class ShadowHist(object):
228 def __init__(self,db):
229 def __init__(self,db):
229 # cmd => idx mapping
230 # cmd => idx mapping
230 self.curidx = 0
231 self.curidx = 0
231 self.db = db
232 self.db = db
232 self.disabled = False
233 self.disabled = False
233
234
234 def inc_idx(self):
235 def inc_idx(self):
235 idx = self.db.get('shadowhist_idx', 1)
236 idx = self.db.get('shadowhist_idx', 1)
236 self.db['shadowhist_idx'] = idx + 1
237 self.db['shadowhist_idx'] = idx + 1
237 return idx
238 return idx
238
239
239 def add(self, ent):
240 def add(self, ent):
240 if self.disabled:
241 if self.disabled:
241 return
242 return
242 try:
243 try:
243 old = self.db.hget('shadowhist', ent, _sentinel)
244 old = self.db.hget('shadowhist', ent, _sentinel)
244 if old is not _sentinel:
245 if old is not _sentinel:
245 return
246 return
246 newidx = self.inc_idx()
247 newidx = self.inc_idx()
247 #print "new",newidx # dbg
248 #print "new",newidx # dbg
248 self.db.hset('shadowhist',ent, newidx)
249 self.db.hset('shadowhist',ent, newidx)
249 except:
250 except:
250 ipapi.get().showtraceback()
251 ipapi.get().showtraceback()
251 print "WARNING: disabling shadow history"
252 print "WARNING: disabling shadow history"
252 self.disabled = True
253 self.disabled = True
253
254
254 def all(self):
255 def all(self):
255 d = self.db.hdict('shadowhist')
256 d = self.db.hdict('shadowhist')
256 items = [(i,s) for (s,i) in d.items()]
257 items = [(i,s) for (s,i) in d.items()]
257 items.sort()
258 items.sort()
258 return items
259 return items
259
260
260 def get(self, idx):
261 def get(self, idx):
261 all = self.all()
262 all = self.all()
262
263
263 for k, v in all:
264 for k, v in all:
264 #print k,v
265 #print k,v
265 if k == idx:
266 if k == idx:
266 return v
267 return v
267
268
268
269
269 def init_ipython(ip):
270 def init_ipython(ip):
270 ip.define_magic("rep",rep_f)
271 ip.define_magic("rep",rep_f)
271 ip.define_magic("hist",magic_hist)
272 ip.define_magic("hist",magic_hist)
272 ip.define_magic("history",magic_history)
273 ip.define_magic("history",magic_history)
273
274
274 # XXX - ipy_completers are in quarantine, need to be updated to new apis
275 # XXX - ipy_completers are in quarantine, need to be updated to new apis
275 #import ipy_completers
276 #import ipy_completers
276 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
277 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,273 +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 return cmd(*args, **kw)
143 return cmd(*args, **kw)
141 except TryNext, exc:
144 except TryNext, exc:
142 if exc.args or exc.kwargs:
145 if exc.args or exc.kwargs:
143 args = exc.args
146 args = exc.args
144 kw = exc.kwargs
147 kw = exc.kwargs
145 # 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
146 raise TryNext
149 raise TryNext
147
150
148 def __str__(self):
151 def __str__(self):
149 return str(self.chain)
152 return str(self.chain)
150
153
151 def add(self, func, priority=0):
154 def add(self, func, priority=0):
152 """ Add a func to the cmd chain with given priority """
155 """ Add a func to the cmd chain with given priority """
153 bisect.insort(self.chain,(priority,func))
156 bisect.insort(self.chain,(priority,func))
154
157
155 def __iter__(self):
158 def __iter__(self):
156 """ Return all objects in chain.
159 """ Return all objects in chain.
157
160
158 Handy if the objects are not callable.
161 Handy if the objects are not callable.
159 """
162 """
160 return iter(self.chain)
163 return iter(self.chain)
161
164
162
165
163 def result_display(self,arg):
166 def result_display(self,arg):
164 """ Default display hook.
167 """ Default display hook.
165
168
166 Called for displaying the result to the user.
169 Called for displaying the result to the user.
167 """
170 """
168
171
169 if self.pprint:
172 if self.pprint:
170 out = pformat(arg)
173 out = pformat(arg)
171 if '\n' in out:
174 if '\n' in out:
172 # 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
173 # the screen, instead of having the output prompt mess up
176 # the screen, instead of having the output prompt mess up
174 # their first line.
177 # their first line.
175 Term.cout.write('\n')
178 Term.cout.write('\n')
176 print >>Term.cout, out
179 print >>Term.cout, out
177 else:
180 else:
178 # By default, the interactive prompt uses repr() to display results,
181 # By default, the interactive prompt uses repr() to display results,
179 # 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
180 # mechanism can easily override this hook.
183 # mechanism can easily override this hook.
181 print >>Term.cout, repr(arg)
184 print >>Term.cout, repr(arg)
182 # 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
183 return None
186 return None
184
187
185
188
186 def input_prefilter(self,line):
189 def input_prefilter(self,line):
187 """ Default input prefilter
190 """ Default input prefilter
188
191
189 This returns the line as unchanged, so that the interpreter
192 This returns the line as unchanged, so that the interpreter
190 knows that nothing was done and proceeds with "classic" prefiltering
193 knows that nothing was done and proceeds with "classic" prefiltering
191 (%magics, !shell commands etc.).
194 (%magics, !shell commands etc.).
192
195
193 Note that leading whitespace is not passed to this hook. Prefilter
196 Note that leading whitespace is not passed to this hook. Prefilter
194 can't alter indentation.
197 can't alter indentation.
195
198
196 """
199 """
197 #print "attempt to rewrite",line #dbg
200 #print "attempt to rewrite",line #dbg
198 return line
201 return line
199
202
200
203
201 def shutdown_hook(self):
204 def shutdown_hook(self):
202 """ default shutdown hook
205 """ default shutdown hook
203
206
204 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
205 """
208 """
206
209
207 #print "default shutdown hook ok" # dbg
210 #print "default shutdown hook ok" # dbg
208 return
211 return
209
212
210
213
211 def late_startup_hook(self):
214 def late_startup_hook(self):
212 """ Executed after ipython has been constructed and configured
215 """ Executed after ipython has been constructed and configured
213
216
214 """
217 """
215 #print "default startup hook ok" # dbg
218 #print "default startup hook ok" # dbg
216
219
217
220
218 def generate_prompt(self, is_continuation):
221 def generate_prompt(self, is_continuation):
219 """ calculate and return a string with the prompt to display """
222 """ calculate and return a string with the prompt to display """
220 if is_continuation:
223 if is_continuation:
221 return str(self.outputcache.prompt2)
224 return str(self.outputcache.prompt2)
222 return str(self.outputcache.prompt1)
225 return str(self.outputcache.prompt1)
223
226
224
227
225 def generate_output_prompt(self):
228 def generate_output_prompt(self):
226 return str(self.outputcache.prompt_out)
229 return str(self.outputcache.prompt_out)
227
230
228
231
229 def shell_hook(self,cmd):
232 def shell_hook(self,cmd):
230 """ Run system/shell command a'la os.system() """
233 """ Run system/shell command a'la os.system() """
231
234
232 shell(cmd, header=self.system_header, verbose=self.system_verbose)
235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
233
236
234
237
235 def show_in_pager(self,s):
238 def show_in_pager(self,s):
236 """ Run a string through pager """
239 """ Run a string through pager """
237 # raising TryNext here will use the default paging functionality
240 # raising TryNext here will use the default paging functionality
238 raise TryNext
241 raise TryNext
239
242
240
243
241 def pre_prompt_hook(self):
244 def pre_prompt_hook(self):
242 """ Run before displaying the next prompt
245 """ Run before displaying the next prompt
243
246
244 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
245 to not mess up text entry)
248 to not mess up text entry)
246 """
249 """
247
250
248 return None
251 return None
249
252
250
253
251 def pre_runcode_hook(self):
254 def pre_runcode_hook(self):
252 """ Executed before running the (prefiltered) code in IPython """
255 """ Executed before running the (prefiltered) code in IPython """
253 return None
256 return None
254
257
255
258
256 def clipboard_get(self):
259 def clipboard_get(self):
257 """ Get text from the clipboard.
260 """ Get text from the clipboard.
258 """
261 """
259 from IPython.lib.clipboard import (
262 from IPython.lib.clipboard import (
260 osx_clipboard_get, tkinter_clipboard_get,
263 osx_clipboard_get, tkinter_clipboard_get,
261 win32_clipboard_get
264 win32_clipboard_get
262 )
265 )
263 if sys.platform == 'win32':
266 if sys.platform == 'win32':
264 chain = [win32_clipboard_get, tkinter_clipboard_get]
267 chain = [win32_clipboard_get, tkinter_clipboard_get]
265 elif sys.platform == 'darwin':
268 elif sys.platform == 'darwin':
266 chain = [osx_clipboard_get, tkinter_clipboard_get]
269 chain = [osx_clipboard_get, tkinter_clipboard_get]
267 else:
270 else:
268 chain = [tkinter_clipboard_get]
271 chain = [tkinter_clipboard_get]
269 dispatcher = CommandChainDispatcher()
272 dispatcher = CommandChainDispatcher()
270 for func in chain:
273 for func in chain:
271 dispatcher.add(func)
274 dispatcher.add(func)
272 text = dispatcher()
275 text = dispatcher()
273 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
@@ -1,655 +1,649 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
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 """
12 """
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2010 The IPython Development Team
15 # Copyright (C) 2008-2010 The IPython Development Team
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 from __future__ import absolute_import
24 from __future__ import absolute_import
25
25
26 import logging
26 import logging
27 import os
27 import os
28 import sys
28 import sys
29
29
30 from IPython.core import crashhandler
30 from IPython.core import crashhandler
31 from IPython.core.application import Application
31 from IPython.core.application import Application
32 from IPython.core.iplib import InteractiveShell
32 from IPython.core.iplib import InteractiveShell
33 from IPython.config.loader import (
33 from IPython.config.loader import (
34 Config,
34 Config,
35 PyFileConfigLoader,
35 PyFileConfigLoader,
36 # NoConfigDefault,
36 # NoConfigDefault,
37 )
37 )
38 from IPython.lib import inputhook
38 from IPython.lib import inputhook
39 from IPython.utils.genutils import filefind, get_ipython_dir
39 from IPython.utils.path import filefind, get_ipython_dir
40 from . import usage
40 from . import usage
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals, utilities and helpers
43 # Globals, utilities and helpers
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45
45
46 default_config_file_name = u'ipython_config.py'
46 default_config_file_name = u'ipython_config.py'
47
47
48 cl_args = (
48 cl_args = (
49 (('--autocall',), dict(
49 (('--autocall',), dict(
50 type=int, dest='InteractiveShell.autocall',
50 type=int, dest='InteractiveShell.autocall',
51 help=
51 help=
52 """Make IPython automatically call any callable object even if you
52 """Make IPython automatically call any callable object even if you
53 didn't type explicit parentheses. For example, 'str 43' becomes
53 didn't type explicit parentheses. For example, 'str 43' becomes
54 'str(43)' automatically. The value can be '0' to disable the feature,
54 'str(43)' automatically. The value can be '0' to disable the feature,
55 '1' for 'smart' autocall, where it is not applied if there are no more
55 '1' for 'smart' autocall, where it is not applied if there are no more
56 arguments on the line, and '2' for 'full' autocall, where all callable
56 arguments on the line, and '2' for 'full' autocall, where all callable
57 objects are automatically called (even if no arguments are present).
57 objects are automatically called (even if no arguments are present).
58 The default is '1'.""",
58 The default is '1'.""",
59 metavar='InteractiveShell.autocall')
59 metavar='InteractiveShell.autocall')
60 ),
60 ),
61 (('--autoindent',), dict(
61 (('--autoindent',), dict(
62 action='store_true', dest='InteractiveShell.autoindent',
62 action='store_true', dest='InteractiveShell.autoindent',
63 help='Turn on autoindenting.')
63 help='Turn on autoindenting.')
64 ),
64 ),
65 (('--no-autoindent',), dict(
65 (('--no-autoindent',), dict(
66 action='store_false', dest='InteractiveShell.autoindent',
66 action='store_false', dest='InteractiveShell.autoindent',
67 help='Turn off autoindenting.')
67 help='Turn off autoindenting.')
68 ),
68 ),
69 (('--automagic',), dict(
69 (('--automagic',), dict(
70 action='store_true', dest='InteractiveShell.automagic',
70 action='store_true', dest='InteractiveShell.automagic',
71 help='Turn on the auto calling of magic commands.'
71 help='Turn on the auto calling of magic commands.'
72 'Type %%magic at the IPython prompt for more information.')
72 'Type %%magic at the IPython prompt for more information.')
73 ),
73 ),
74 (('--no-automagic',), dict(
74 (('--no-automagic',), dict(
75 action='store_false', dest='InteractiveShell.automagic',
75 action='store_false', dest='InteractiveShell.automagic',
76 help='Turn off the auto calling of magic commands.')
76 help='Turn off the auto calling of magic commands.')
77 ),
77 ),
78 (('--autoedit-syntax',), dict(
78 (('--autoedit-syntax',), dict(
79 action='store_true', dest='InteractiveShell.autoedit_syntax',
79 action='store_true', dest='InteractiveShell.autoedit_syntax',
80 help='Turn on auto editing of files with syntax errors.')
80 help='Turn on auto editing of files with syntax errors.')
81 ),
81 ),
82 (('--no-autoedit-syntax',), dict(
82 (('--no-autoedit-syntax',), dict(
83 action='store_false', dest='InteractiveShell.autoedit_syntax',
83 action='store_false', dest='InteractiveShell.autoedit_syntax',
84 help='Turn off auto editing of files with syntax errors.')
84 help='Turn off auto editing of files with syntax errors.')
85 ),
85 ),
86 (('--banner',), dict(
86 (('--banner',), dict(
87 action='store_true', dest='Global.display_banner',
87 action='store_true', dest='Global.display_banner',
88 help='Display a banner upon starting IPython.')
88 help='Display a banner upon starting IPython.')
89 ),
89 ),
90 (('--no-banner',), dict(
90 (('--no-banner',), dict(
91 action='store_false', dest='Global.display_banner',
91 action='store_false', dest='Global.display_banner',
92 help="Don't display a banner upon starting IPython.")
92 help="Don't display a banner upon starting IPython.")
93 ),
93 ),
94 (('--cache-size',), dict(
94 (('--cache-size',), dict(
95 type=int, dest='InteractiveShell.cache_size',
95 type=int, dest='InteractiveShell.cache_size',
96 help=
96 help=
97 """Set the size of the output cache. The default is 1000, you can
97 """Set the size of the output cache. The default is 1000, you can
98 change it permanently in your config file. Setting it to 0 completely
98 change it permanently in your config file. Setting it to 0 completely
99 disables the caching system, and the minimum value accepted is 20 (if
99 disables the caching system, and the minimum value accepted is 20 (if
100 you provide a value less than 20, it is reset to 0 and a warning is
100 you provide a value less than 20, it is reset to 0 and a warning is
101 issued). This limit is defined because otherwise you'll spend more
101 issued). This limit is defined because otherwise you'll spend more
102 time re-flushing a too small cache than working.
102 time re-flushing a too small cache than working.
103 """,
103 """,
104 metavar='InteractiveShell.cache_size')
104 metavar='InteractiveShell.cache_size')
105 ),
105 ),
106 (('--classic',), dict(
106 (('--classic',), dict(
107 action='store_true', dest='Global.classic',
107 action='store_true', dest='Global.classic',
108 help="Gives IPython a similar feel to the classic Python prompt.")
108 help="Gives IPython a similar feel to the classic Python prompt.")
109 ),
109 ),
110 (('--colors',), dict(
110 (('--colors',), dict(
111 type=str, dest='InteractiveShell.colors',
111 type=str, dest='InteractiveShell.colors',
112 help="Set the color scheme (NoColor, Linux, and LightBG).",
112 help="Set the color scheme (NoColor, Linux, and LightBG).",
113 metavar='InteractiveShell.colors')
113 metavar='InteractiveShell.colors')
114 ),
114 ),
115 (('--color-info',), dict(
115 (('--color-info',), dict(
116 action='store_true', dest='InteractiveShell.color_info',
116 action='store_true', dest='InteractiveShell.color_info',
117 help=
117 help=
118 """IPython can display information about objects via a set of func-
118 """IPython can display information about objects via a set of func-
119 tions, and optionally can use colors for this, syntax highlighting
119 tions, and optionally can use colors for this, syntax highlighting
120 source code and various other elements. However, because this
120 source code and various other elements. However, because this
121 information is passed through a pager (like 'less') and many pagers get
121 information is passed through a pager (like 'less') and many pagers get
122 confused with color codes, this option is off by default. You can test
122 confused with color codes, this option is off by default. You can test
123 it and turn it on permanently in your ipython_config.py file if it
123 it and turn it on permanently in your ipython_config.py file if it
124 works for you. Test it and turn it on permanently if it works with
124 works for you. Test it and turn it on permanently if it works with
125 your system. The magic function %%color_info allows you to toggle this
125 your system. The magic function %%color_info allows you to toggle this
126 inter- actively for testing."""
126 inter- actively for testing."""
127 )
127 )
128 ),
128 ),
129 (('--no-color-info',), dict(
129 (('--no-color-info',), dict(
130 action='store_false', dest='InteractiveShell.color_info',
130 action='store_false', dest='InteractiveShell.color_info',
131 help="Disable using colors for info related things.")
131 help="Disable using colors for info related things.")
132 ),
132 ),
133 (('--confirm-exit',), dict(
133 (('--confirm-exit',), dict(
134 action='store_true', dest='InteractiveShell.confirm_exit',
134 action='store_true', dest='InteractiveShell.confirm_exit',
135 help=
135 help=
136 """Set to confirm when you try to exit IPython with an EOF (Control-D
136 """Set to confirm when you try to exit IPython with an EOF (Control-D
137 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
137 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
138 '%%Exit', you can force a direct exit without any confirmation.
138 '%%Exit', you can force a direct exit without any confirmation.
139 """
139 """
140 )
140 )
141 ),
141 ),
142 (('--no-confirm-exit',), dict(
142 (('--no-confirm-exit',), dict(
143 action='store_false', dest='InteractiveShell.confirm_exit',
143 action='store_false', dest='InteractiveShell.confirm_exit',
144 help="Don't prompt the user when exiting.")
144 help="Don't prompt the user when exiting.")
145 ),
145 ),
146 (('--deep-reload',), dict(
146 (('--deep-reload',), dict(
147 action='store_true', dest='InteractiveShell.deep_reload',
147 action='store_true', dest='InteractiveShell.deep_reload',
148 help=
148 help=
149 """Enable deep (recursive) reloading by default. IPython can use the
149 """Enable deep (recursive) reloading by default. IPython can use the
150 deep_reload module which reloads changes in modules recursively (it
150 deep_reload module which reloads changes in modules recursively (it
151 replaces the reload() function, so you don't need to change anything to
151 replaces the reload() function, so you don't need to change anything to
152 use it). deep_reload() forces a full reload of modules whose code may
152 use it). deep_reload() forces a full reload of modules whose code may
153 have changed, which the default reload() function does not. When
153 have changed, which the default reload() function does not. When
154 deep_reload is off, IPython will use the normal reload(), but
154 deep_reload is off, IPython will use the normal reload(), but
155 deep_reload will still be available as dreload(). This fea- ture is off
155 deep_reload will still be available as dreload(). This fea- ture is off
156 by default [which means that you have both normal reload() and
156 by default [which means that you have both normal reload() and
157 dreload()].""")
157 dreload()].""")
158 ),
158 ),
159 (('--no-deep-reload',), dict(
159 (('--no-deep-reload',), dict(
160 action='store_false', dest='InteractiveShell.deep_reload',
160 action='store_false', dest='InteractiveShell.deep_reload',
161 help="Disable deep (recursive) reloading by default.")
161 help="Disable deep (recursive) reloading by default.")
162 ),
162 ),
163 (('--editor',), dict(
163 (('--editor',), dict(
164 type=str, dest='InteractiveShell.editor',
164 type=str, dest='InteractiveShell.editor',
165 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
165 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
166 metavar='InteractiveShell.editor')
166 metavar='InteractiveShell.editor')
167 ),
167 ),
168 (('--log','-l'), dict(
168 (('--log','-l'), dict(
169 action='store_true', dest='InteractiveShell.logstart',
169 action='store_true', dest='InteractiveShell.logstart',
170 help="Start logging to the default log file (./ipython_log.py).")
170 help="Start logging to the default log file (./ipython_log.py).")
171 ),
171 ),
172 (('--logfile','-lf'), dict(
172 (('--logfile','-lf'), dict(
173 type=unicode, dest='InteractiveShell.logfile',
173 type=unicode, dest='InteractiveShell.logfile',
174 help="Start logging to logfile with this name.",
174 help="Start logging to logfile with this name.",
175 metavar='InteractiveShell.logfile')
175 metavar='InteractiveShell.logfile')
176 ),
176 ),
177 (('--log-append','-la'), dict(
177 (('--log-append','-la'), dict(
178 type=unicode, dest='InteractiveShell.logappend',
178 type=unicode, dest='InteractiveShell.logappend',
179 help="Start logging to the given file in append mode.",
179 help="Start logging to the given file in append mode.",
180 metavar='InteractiveShell.logfile')
180 metavar='InteractiveShell.logfile')
181 ),
181 ),
182 (('--pdb',), dict(
182 (('--pdb',), dict(
183 action='store_true', dest='InteractiveShell.pdb',
183 action='store_true', dest='InteractiveShell.pdb',
184 help="Enable auto calling the pdb debugger after every exception.")
184 help="Enable auto calling the pdb debugger after every exception.")
185 ),
185 ),
186 (('--no-pdb',), dict(
186 (('--no-pdb',), dict(
187 action='store_false', dest='InteractiveShell.pdb',
187 action='store_false', dest='InteractiveShell.pdb',
188 help="Disable auto calling the pdb debugger after every exception.")
188 help="Disable auto calling the pdb debugger after every exception.")
189 ),
189 ),
190 (('--pprint',), dict(
190 (('--pprint',), dict(
191 action='store_true', dest='InteractiveShell.pprint',
191 action='store_true', dest='InteractiveShell.pprint',
192 help="Enable auto pretty printing of results.")
192 help="Enable auto pretty printing of results.")
193 ),
193 ),
194 (('--no-pprint',), dict(
194 (('--no-pprint',), dict(
195 action='store_false', dest='InteractiveShell.pprint',
195 action='store_false', dest='InteractiveShell.pprint',
196 help="Disable auto auto pretty printing of results.")
196 help="Disable auto auto pretty printing of results.")
197 ),
197 ),
198 (('--prompt-in1','-pi1'), dict(
198 (('--prompt-in1','-pi1'), dict(
199 type=str, dest='InteractiveShell.prompt_in1',
199 type=str, dest='InteractiveShell.prompt_in1',
200 help=
200 help=
201 """Set the main input prompt ('In [\#]: '). Note that if you are using
201 """Set the main input prompt ('In [\#]: '). Note that if you are using
202 numbered prompts, the number is represented with a '\#' in the string.
202 numbered prompts, the number is represented with a '\#' in the string.
203 Don't forget to quote strings with spaces embedded in them. Most
203 Don't forget to quote strings with spaces embedded in them. Most
204 bash-like escapes can be used to customize IPython's prompts, as well
204 bash-like escapes can be used to customize IPython's prompts, as well
205 as a few additional ones which are IPython-spe- cific. All valid
205 as a few additional ones which are IPython-spe- cific. All valid
206 prompt escapes are described in detail in the Customization section of
206 prompt escapes are described in detail in the Customization section of
207 the IPython manual.""",
207 the IPython manual.""",
208 metavar='InteractiveShell.prompt_in1')
208 metavar='InteractiveShell.prompt_in1')
209 ),
209 ),
210 (('--prompt-in2','-pi2'), dict(
210 (('--prompt-in2','-pi2'), dict(
211 type=str, dest='InteractiveShell.prompt_in2',
211 type=str, dest='InteractiveShell.prompt_in2',
212 help=
212 help=
213 """Set the secondary input prompt (' .\D.: '). Similar to the previous
213 """Set the secondary input prompt (' .\D.: '). Similar to the previous
214 option, but used for the continuation prompts. The special sequence
214 option, but used for the continuation prompts. The special sequence
215 '\D' is similar to '\#', but with all digits replaced by dots (so you
215 '\D' is similar to '\#', but with all digits replaced by dots (so you
216 can have your continuation prompt aligned with your input prompt).
216 can have your continuation prompt aligned with your input prompt).
217 Default: ' .\D.: ' (note three spaces at the start for alignment with
217 Default: ' .\D.: ' (note three spaces at the start for alignment with
218 'In [\#]')""",
218 'In [\#]')""",
219 metavar='InteractiveShell.prompt_in2')
219 metavar='InteractiveShell.prompt_in2')
220 ),
220 ),
221 (('--prompt-out','-po'), dict(
221 (('--prompt-out','-po'), dict(
222 type=str, dest='InteractiveShell.prompt_out',
222 type=str, dest='InteractiveShell.prompt_out',
223 help="Set the output prompt ('Out[\#]:')",
223 help="Set the output prompt ('Out[\#]:')",
224 metavar='InteractiveShell.prompt_out')
224 metavar='InteractiveShell.prompt_out')
225 ),
225 ),
226 (('--quick',), dict(
226 (('--quick',), dict(
227 action='store_true', dest='Global.quick',
227 action='store_true', dest='Global.quick',
228 help="Enable quick startup with no config files.")
228 help="Enable quick startup with no config files.")
229 ),
229 ),
230 (('--readline',), dict(
230 (('--readline',), dict(
231 action='store_true', dest='InteractiveShell.readline_use',
231 action='store_true', dest='InteractiveShell.readline_use',
232 help="Enable readline for command line usage.")
232 help="Enable readline for command line usage.")
233 ),
233 ),
234 (('--no-readline',), dict(
234 (('--no-readline',), dict(
235 action='store_false', dest='InteractiveShell.readline_use',
235 action='store_false', dest='InteractiveShell.readline_use',
236 help="Disable readline for command line usage.")
236 help="Disable readline for command line usage.")
237 ),
237 ),
238 (('--screen-length','-sl'), dict(
238 (('--screen-length','-sl'), dict(
239 type=int, dest='InteractiveShell.screen_length',
239 type=int, dest='InteractiveShell.screen_length',
240 help=
240 help=
241 """Number of lines of your screen, used to control printing of very
241 """Number of lines of your screen, used to control printing of very
242 long strings. Strings longer than this number of lines will be sent
242 long strings. Strings longer than this number of lines will be sent
243 through a pager instead of directly printed. The default value for
243 through a pager instead of directly printed. The default value for
244 this is 0, which means IPython will auto-detect your screen size every
244 this is 0, which means IPython will auto-detect your screen size every
245 time it needs to print certain potentially long strings (this doesn't
245 time it needs to print certain potentially long strings (this doesn't
246 change the behavior of the 'print' keyword, it's only triggered
246 change the behavior of the 'print' keyword, it's only triggered
247 internally). If for some reason this isn't working well (it needs
247 internally). If for some reason this isn't working well (it needs
248 curses support), specify it yourself. Otherwise don't change the
248 curses support), specify it yourself. Otherwise don't change the
249 default.""",
249 default.""",
250 metavar='InteractiveShell.screen_length')
250 metavar='InteractiveShell.screen_length')
251 ),
251 ),
252 (('--separate-in','-si'), dict(
252 (('--separate-in','-si'), dict(
253 type=str, dest='InteractiveShell.separate_in',
253 type=str, dest='InteractiveShell.separate_in',
254 help="Separator before input prompts. Default '\\n'.",
254 help="Separator before input prompts. Default '\\n'.",
255 metavar='InteractiveShell.separate_in')
255 metavar='InteractiveShell.separate_in')
256 ),
256 ),
257 (('--separate-out','-so'), dict(
257 (('--separate-out','-so'), dict(
258 type=str, dest='InteractiveShell.separate_out',
258 type=str, dest='InteractiveShell.separate_out',
259 help="Separator before output prompts. Default 0 (nothing).",
259 help="Separator before output prompts. Default 0 (nothing).",
260 metavar='InteractiveShell.separate_out')
260 metavar='InteractiveShell.separate_out')
261 ),
261 ),
262 (('--separate-out2','-so2'), dict(
262 (('--separate-out2','-so2'), dict(
263 type=str, dest='InteractiveShell.separate_out2',
263 type=str, dest='InteractiveShell.separate_out2',
264 help="Separator after output prompts. Default 0 (nonight).",
264 help="Separator after output prompts. Default 0 (nonight).",
265 metavar='InteractiveShell.separate_out2')
265 metavar='InteractiveShell.separate_out2')
266 ),
266 ),
267 (('-no-sep',), dict(
267 (('-no-sep',), dict(
268 action='store_true', dest='Global.nosep',
268 action='store_true', dest='Global.nosep',
269 help="Eliminate all spacing between prompts.")
269 help="Eliminate all spacing between prompts.")
270 ),
270 ),
271 (('--term-title',), dict(
271 (('--term-title',), dict(
272 action='store_true', dest='InteractiveShell.term_title',
272 action='store_true', dest='InteractiveShell.term_title',
273 help="Enable auto setting the terminal title.")
273 help="Enable auto setting the terminal title.")
274 ),
274 ),
275 (('--no-term-title',), dict(
275 (('--no-term-title',), dict(
276 action='store_false', dest='InteractiveShell.term_title',
276 action='store_false', dest='InteractiveShell.term_title',
277 help="Disable auto setting the terminal title.")
277 help="Disable auto setting the terminal title.")
278 ),
278 ),
279 (('--xmode',), dict(
279 (('--xmode',), dict(
280 type=str, dest='InteractiveShell.xmode',
280 type=str, dest='InteractiveShell.xmode',
281 help=
281 help=
282 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
282 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
283 similar to python's normal traceback printing. Context: prints 5 lines
283 similar to python's normal traceback printing. Context: prints 5 lines
284 of context source code around each line in the traceback. Verbose:
284 of context source code around each line in the traceback. Verbose:
285 similar to Context, but additionally prints the variables currently
285 similar to Context, but additionally prints the variables currently
286 visible where the exception happened (shortening their strings if too
286 visible where the exception happened (shortening their strings if too
287 long). This can potentially be very slow, if you happen to have a huge
287 long). This can potentially be very slow, if you happen to have a huge
288 data structure whose string representation is complex to compute.
288 data structure whose string representation is complex to compute.
289 Your computer may appear to freeze for a while with cpu usage at 100%%.
289 Your computer may appear to freeze for a while with cpu usage at 100%%.
290 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
290 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
291 it more than once).
291 it more than once).
292 """,
292 """,
293 metavar='InteractiveShell.xmode')
293 metavar='InteractiveShell.xmode')
294 ),
294 ),
295 (('--ext',), dict(
295 (('--ext',), dict(
296 type=str, dest='Global.extra_extension',
296 type=str, dest='Global.extra_extension',
297 help="The dotted module name of an IPython extension to load.",
297 help="The dotted module name of an IPython extension to load.",
298 metavar='Global.extra_extension')
298 metavar='Global.extra_extension')
299 ),
299 ),
300 (('-c',), dict(
300 (('-c',), dict(
301 type=str, dest='Global.code_to_run',
301 type=str, dest='Global.code_to_run',
302 help="Execute the given command string.",
302 help="Execute the given command string.",
303 metavar='Global.code_to_run')
303 metavar='Global.code_to_run')
304 ),
304 ),
305 (('-i',), dict(
305 (('-i',), dict(
306 action='store_true', dest='Global.force_interact',
306 action='store_true', dest='Global.force_interact',
307 help=
307 help=
308 "If running code from the command line, become interactive afterwards."
308 "If running code from the command line, become interactive afterwards."
309 )
309 )
310 ),
310 ),
311
311
312 # Options to start with GUI control enabled from the beginning
312 # Options to start with GUI control enabled from the beginning
313 (('--gui',), dict(
313 (('--gui',), dict(
314 type=str, dest='Global.gui',
314 type=str, dest='Global.gui',
315 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
315 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
316 metavar='gui-mode')
316 metavar='gui-mode')
317 ),
317 ),
318
318
319 (('--pylab','-pylab'), dict(
319 (('--pylab','-pylab'), dict(
320 type=str, dest='Global.pylab',
320 type=str, dest='Global.pylab',
321 nargs='?', const='auto', metavar='gui-mode',
321 nargs='?', const='auto', metavar='gui-mode',
322 help="Pre-load matplotlib and numpy for interactive use. "+
322 help="Pre-load matplotlib and numpy for interactive use. "+
323 "If no value is given, the gui backend is matplotlib's, else use "+
323 "If no value is given, the gui backend is matplotlib's, else use "+
324 "one of: ['tk', 'qt', 'wx', 'gtk'].")
324 "one of: ['tk', 'qt', 'wx', 'gtk'].")
325 ),
325 ),
326
326
327 # Legacy GUI options. Leave them in for backwards compatibility, but the
327 # Legacy GUI options. Leave them in for backwards compatibility, but the
328 # 'thread' names are really a misnomer now.
328 # 'thread' names are really a misnomer now.
329 (('--wthread','-wthread'), dict(
329 (('--wthread','-wthread'), dict(
330 action='store_true', dest='Global.wthread',
330 action='store_true', dest='Global.wthread',
331 help="Enable wxPython event loop integration "+
331 help="Enable wxPython event loop integration "+
332 "(DEPRECATED, use --gui wx)")
332 "(DEPRECATED, use --gui wx)")
333 ),
333 ),
334 (('--q4thread','--qthread','-q4thread','-qthread'), dict(
334 (('--q4thread','--qthread','-q4thread','-qthread'), dict(
335 action='store_true', dest='Global.q4thread',
335 action='store_true', dest='Global.q4thread',
336 help="Enable Qt4 event loop integration. Qt3 is no longer supported. "+
336 help="Enable Qt4 event loop integration. Qt3 is no longer supported. "+
337 "(DEPRECATED, use --gui qt)")
337 "(DEPRECATED, use --gui qt)")
338 ),
338 ),
339 (('--gthread','-gthread'), dict(
339 (('--gthread','-gthread'), dict(
340 action='store_true', dest='Global.gthread',
340 action='store_true', dest='Global.gthread',
341 help="Enable GTK event loop integration. "+
341 help="Enable GTK event loop integration. "+
342 "(DEPRECATED, use --gui gtk)")
342 "(DEPRECATED, use --gui gtk)")
343 ),
343 ),
344 )
344 )
345
345
346 #-----------------------------------------------------------------------------
346 #-----------------------------------------------------------------------------
347 # Main classes and functions
347 # Main classes and functions
348 #-----------------------------------------------------------------------------
348 #-----------------------------------------------------------------------------
349
349
350 class IPythonApp(Application):
350 class IPythonApp(Application):
351 name = u'ipython'
351 name = u'ipython'
352 #: argparse formats better the 'usage' than the 'description' field
352 #: argparse formats better the 'usage' than the 'description' field
353 description = None
353 description = None
354 #: usage message printed by argparse. If None, auto-generate
354 #: usage message printed by argparse. If None, auto-generate
355 usage = usage.cl_usage
355 usage = usage.cl_usage
356
356
357 config_file_name = default_config_file_name
357 config_file_name = default_config_file_name
358
358
359 cl_arguments = Application.cl_arguments + cl_args
359 cl_arguments = Application.cl_arguments + cl_args
360
360
361 # Private and configuration attributes
361 # Private and configuration attributes
362 _CrashHandler = crashhandler.IPythonCrashHandler
362 _CrashHandler = crashhandler.IPythonCrashHandler
363
363
364 def __init__(self, argv=None,
364 def __init__(self, argv=None,
365 constructor_config=None, override_config=None,
365 constructor_config=None, override_config=None,
366 **shell_params):
366 **shell_params):
367 """Create a new IPythonApp.
367 """Create a new IPythonApp.
368
368
369 See the parent class for details on how configuration is handled.
369 See the parent class for details on how configuration is handled.
370
370
371 Parameters
371 Parameters
372 ----------
372 ----------
373 argv : optional, list
373 argv : optional, list
374 If given, used as the command-line argv environment to read arguments
374 If given, used as the command-line argv environment to read arguments
375 from.
375 from.
376
376
377 constructor_config : optional, Config
377 constructor_config : optional, Config
378 If given, additional config that is merged last, after internal
378 If given, additional config that is merged last, after internal
379 defaults, command-line and file-based configs.
379 defaults, command-line and file-based configs.
380
380
381 override_config : optional, Config
381 override_config : optional, Config
382 If given, config that overrides all others unconditionally (except
382 If given, config that overrides all others unconditionally (except
383 for internal defaults, which ensure that all parameters exist).
383 for internal defaults, which ensure that all parameters exist).
384
384
385 shell_params : optional, dict
385 shell_params : optional, dict
386 All other keywords are passed to the :class:`iplib.InteractiveShell`
386 All other keywords are passed to the :class:`iplib.InteractiveShell`
387 constructor.
387 constructor.
388 """
388 """
389 super(IPythonApp, self).__init__(argv, constructor_config,
389 super(IPythonApp, self).__init__(argv, constructor_config,
390 override_config)
390 override_config)
391 self.shell_params = shell_params
391 self.shell_params = shell_params
392
392
393 def create_default_config(self):
393 def create_default_config(self):
394 super(IPythonApp, self).create_default_config()
394 super(IPythonApp, self).create_default_config()
395 # Eliminate multiple lookups
395 # Eliminate multiple lookups
396 Global = self.default_config.Global
396 Global = self.default_config.Global
397
397
398 # Set all default values
398 # Set all default values
399 Global.display_banner = True
399 Global.display_banner = True
400
400
401 # If the -c flag is given or a file is given to run at the cmd line
401 # If the -c flag is given or a file is given to run at the cmd line
402 # like "ipython foo.py", normally we exit without starting the main
402 # like "ipython foo.py", normally we exit without starting the main
403 # loop. The force_interact config variable allows a user to override
403 # loop. The force_interact config variable allows a user to override
404 # this and interact. It is also set by the -i cmd line flag, just
404 # this and interact. It is also set by the -i cmd line flag, just
405 # like Python.
405 # like Python.
406 Global.force_interact = False
406 Global.force_interact = False
407
407
408 # By default always interact by starting the IPython mainloop.
408 # By default always interact by starting the IPython mainloop.
409 Global.interact = True
409 Global.interact = True
410
410
411 # No GUI integration by default
411 # No GUI integration by default
412 Global.gui = False
412 Global.gui = False
413 # Pylab off by default
413 # Pylab off by default
414 Global.pylab = False
414 Global.pylab = False
415
415
416 # Deprecated versions of gui support that used threading, we support
416 # Deprecated versions of gui support that used threading, we support
417 # them just for bacwards compatibility as an alternate spelling for
417 # them just for bacwards compatibility as an alternate spelling for
418 # '--gui X'
418 # '--gui X'
419 Global.qthread = False
419 Global.qthread = False
420 Global.q4thread = False
420 Global.q4thread = False
421 Global.wthread = False
421 Global.wthread = False
422 Global.gthread = False
422 Global.gthread = False
423
423
424 def load_file_config(self):
424 def load_file_config(self):
425 if hasattr(self.command_line_config.Global, 'quick'):
425 if hasattr(self.command_line_config.Global, 'quick'):
426 if self.command_line_config.Global.quick:
426 if self.command_line_config.Global.quick:
427 self.file_config = Config()
427 self.file_config = Config()
428 return
428 return
429 super(IPythonApp, self).load_file_config()
429 super(IPythonApp, self).load_file_config()
430
430
431 def post_load_file_config(self):
431 def post_load_file_config(self):
432 if hasattr(self.command_line_config.Global, 'extra_extension'):
432 if hasattr(self.command_line_config.Global, 'extra_extension'):
433 if not hasattr(self.file_config.Global, 'extensions'):
433 if not hasattr(self.file_config.Global, 'extensions'):
434 self.file_config.Global.extensions = []
434 self.file_config.Global.extensions = []
435 self.file_config.Global.extensions.append(
435 self.file_config.Global.extensions.append(
436 self.command_line_config.Global.extra_extension)
436 self.command_line_config.Global.extra_extension)
437 del self.command_line_config.Global.extra_extension
437 del self.command_line_config.Global.extra_extension
438
438
439 def pre_construct(self):
439 def pre_construct(self):
440 config = self.master_config
440 config = self.master_config
441
441
442 if hasattr(config.Global, 'classic'):
442 if hasattr(config.Global, 'classic'):
443 if config.Global.classic:
443 if config.Global.classic:
444 config.InteractiveShell.cache_size = 0
444 config.InteractiveShell.cache_size = 0
445 config.InteractiveShell.pprint = 0
445 config.InteractiveShell.pprint = 0
446 config.InteractiveShell.prompt_in1 = '>>> '
446 config.InteractiveShell.prompt_in1 = '>>> '
447 config.InteractiveShell.prompt_in2 = '... '
447 config.InteractiveShell.prompt_in2 = '... '
448 config.InteractiveShell.prompt_out = ''
448 config.InteractiveShell.prompt_out = ''
449 config.InteractiveShell.separate_in = \
449 config.InteractiveShell.separate_in = \
450 config.InteractiveShell.separate_out = \
450 config.InteractiveShell.separate_out = \
451 config.InteractiveShell.separate_out2 = ''
451 config.InteractiveShell.separate_out2 = ''
452 config.InteractiveShell.colors = 'NoColor'
452 config.InteractiveShell.colors = 'NoColor'
453 config.InteractiveShell.xmode = 'Plain'
453 config.InteractiveShell.xmode = 'Plain'
454
454
455 if hasattr(config.Global, 'nosep'):
455 if hasattr(config.Global, 'nosep'):
456 if config.Global.nosep:
456 if config.Global.nosep:
457 config.InteractiveShell.separate_in = \
457 config.InteractiveShell.separate_in = \
458 config.InteractiveShell.separate_out = \
458 config.InteractiveShell.separate_out = \
459 config.InteractiveShell.separate_out2 = ''
459 config.InteractiveShell.separate_out2 = ''
460
460
461 # if there is code of files to run from the cmd line, don't interact
461 # if there is code of files to run from the cmd line, don't interact
462 # unless the -i flag (Global.force_interact) is true.
462 # unless the -i flag (Global.force_interact) is true.
463 code_to_run = config.Global.get('code_to_run','')
463 code_to_run = config.Global.get('code_to_run','')
464 file_to_run = False
464 file_to_run = False
465 if self.extra_args and self.extra_args[0]:
465 if self.extra_args and self.extra_args[0]:
466 file_to_run = True
466 file_to_run = True
467 if file_to_run or code_to_run:
467 if file_to_run or code_to_run:
468 if not config.Global.force_interact:
468 if not config.Global.force_interact:
469 config.Global.interact = False
469 config.Global.interact = False
470
470
471 def construct(self):
471 def construct(self):
472 # I am a little hesitant to put these into InteractiveShell itself.
472 # I am a little hesitant to put these into InteractiveShell itself.
473 # But that might be the place for them
473 # But that might be the place for them
474 sys.path.insert(0, '')
474 sys.path.insert(0, '')
475
475
476 # Create an InteractiveShell instance
476 # Create an InteractiveShell instance
477 self.shell = InteractiveShell(None, self.master_config,
477 self.shell = InteractiveShell(None, self.master_config,
478 **self.shell_params )
478 **self.shell_params )
479
479
480 def post_construct(self):
480 def post_construct(self):
481 """Do actions after construct, but before starting the app."""
481 """Do actions after construct, but before starting the app."""
482 config = self.master_config
482 config = self.master_config
483
483
484 # shell.display_banner should always be False for the terminal
484 # shell.display_banner should always be False for the terminal
485 # based app, because we call shell.show_banner() by hand below
485 # based app, because we call shell.show_banner() by hand below
486 # so the banner shows *before* all extension loading stuff.
486 # so the banner shows *before* all extension loading stuff.
487 self.shell.display_banner = False
487 self.shell.display_banner = False
488
488
489 if config.Global.display_banner and \
489 if config.Global.display_banner and \
490 config.Global.interact:
490 config.Global.interact:
491 self.shell.show_banner()
491 self.shell.show_banner()
492
492
493 # Make sure there is a space below the banner.
493 # Make sure there is a space below the banner.
494 if self.log_level <= logging.INFO: print
494 if self.log_level <= logging.INFO: print
495
495
496 # 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.
497 self._enable_gui_pylab()
497 self._enable_gui_pylab()
498 self._load_extensions()
498 self._load_extensions()
499 self._run_exec_lines()
499 self._run_exec_lines()
500 self._run_exec_files()
500 self._run_exec_files()
501 self._run_cmd_line_code()
501 self._run_cmd_line_code()
502 self._configure_xmode()
503
502
504 def _enable_gui_pylab(self):
503 def _enable_gui_pylab(self):
505 """Enable GUI event loop integration, taking pylab into account."""
504 """Enable GUI event loop integration, taking pylab into account."""
506 Global = self.master_config.Global
505 Global = self.master_config.Global
507
506
508 # Select which gui to use
507 # Select which gui to use
509 if Global.gui:
508 if Global.gui:
510 gui = Global.gui
509 gui = Global.gui
511 # The following are deprecated, but there's likely to be a lot of use
510 # The following are deprecated, but there's likely to be a lot of use
512 # of this form out there, so we might as well support it for now. But
511 # of this form out there, so we might as well support it for now. But
513 # the --gui option above takes precedence.
512 # the --gui option above takes precedence.
514 elif Global.wthread:
513 elif Global.wthread:
515 gui = inputhook.GUI_WX
514 gui = inputhook.GUI_WX
516 elif Global.qthread:
515 elif Global.qthread:
517 gui = inputhook.GUI_QT
516 gui = inputhook.GUI_QT
518 elif Global.gthread:
517 elif Global.gthread:
519 gui = inputhook.GUI_GTK
518 gui = inputhook.GUI_GTK
520 else:
519 else:
521 gui = None
520 gui = None
522
521
523 # Using --pylab will also require gui activation, though which toolkit
522 # Using --pylab will also require gui activation, though which toolkit
524 # to use may be chosen automatically based on mpl configuration.
523 # to use may be chosen automatically based on mpl configuration.
525 if Global.pylab:
524 if Global.pylab:
526 activate = self.shell.enable_pylab
525 activate = self.shell.enable_pylab
527 if Global.pylab == 'auto':
526 if Global.pylab == 'auto':
528 gui = None
527 gui = None
529 else:
528 else:
530 gui = Global.pylab
529 gui = Global.pylab
531 else:
530 else:
532 # Enable only GUI integration, no pylab
531 # Enable only GUI integration, no pylab
533 activate = inputhook.enable_gui
532 activate = inputhook.enable_gui
534
533
535 if gui or Global.pylab:
534 if gui or Global.pylab:
536 try:
535 try:
537 self.log.info("Enabling GUI event loop integration, "
536 self.log.info("Enabling GUI event loop integration, "
538 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
539 activate(gui)
538 activate(gui)
540 except:
539 except:
541 self.log.warn("Error in enabling GUI event loop integration:")
540 self.log.warn("Error in enabling GUI event loop integration:")
542 self.shell.showtraceback()
541 self.shell.showtraceback()
543
542
544 def _load_extensions(self):
543 def _load_extensions(self):
545 """Load all IPython extensions in Global.extensions.
544 """Load all IPython extensions in Global.extensions.
546
545
547 This uses the :meth:`InteractiveShell.load_extensions` to load all
546 This uses the :meth:`InteractiveShell.load_extensions` to load all
548 the extensions listed in ``self.master_config.Global.extensions``.
547 the extensions listed in ``self.master_config.Global.extensions``.
549 """
548 """
550 try:
549 try:
551 if hasattr(self.master_config.Global, 'extensions'):
550 if hasattr(self.master_config.Global, 'extensions'):
552 self.log.debug("Loading IPython extensions...")
551 self.log.debug("Loading IPython extensions...")
553 extensions = self.master_config.Global.extensions
552 extensions = self.master_config.Global.extensions
554 for ext in extensions:
553 for ext in extensions:
555 try:
554 try:
556 self.log.info("Loading IPython extension: %s" % ext)
555 self.log.info("Loading IPython extension: %s" % ext)
557 self.shell.load_extension(ext)
556 self.shell.load_extension(ext)
558 except:
557 except:
559 self.log.warn("Error in loading extension: %s" % ext)
558 self.log.warn("Error in loading extension: %s" % ext)
560 self.shell.showtraceback()
559 self.shell.showtraceback()
561 except:
560 except:
562 self.log.warn("Unknown error in loading extensions:")
561 self.log.warn("Unknown error in loading extensions:")
563 self.shell.showtraceback()
562 self.shell.showtraceback()
564
563
565 def _run_exec_lines(self):
564 def _run_exec_lines(self):
566 """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."""
567 try:
566 try:
568 if hasattr(self.master_config.Global, 'exec_lines'):
567 if hasattr(self.master_config.Global, 'exec_lines'):
569 self.log.debug("Running code from Global.exec_lines...")
568 self.log.debug("Running code from Global.exec_lines...")
570 exec_lines = self.master_config.Global.exec_lines
569 exec_lines = self.master_config.Global.exec_lines
571 for line in exec_lines:
570 for line in exec_lines:
572 try:
571 try:
573 self.log.info("Running code in user namespace: %s" % line)
572 self.log.info("Running code in user namespace: %s" % line)
574 self.shell.runlines(line)
573 self.shell.runlines(line)
575 except:
574 except:
576 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)
577 self.shell.showtraceback()
576 self.shell.showtraceback()
578 except:
577 except:
579 self.log.warn("Unknown error in handling Global.exec_lines:")
578 self.log.warn("Unknown error in handling Global.exec_lines:")
580 self.shell.showtraceback()
579 self.shell.showtraceback()
581
580
582 def _exec_file(self, fname):
581 def _exec_file(self, fname):
583 full_filename = filefind(fname, [u'.', self.ipython_dir])
582 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 if os.path.isfile(full_filename):
583 if os.path.isfile(full_filename):
585 if full_filename.endswith(u'.py'):
584 if full_filename.endswith(u'.py'):
586 self.log.info("Running file in user namespace: %s" % full_filename)
585 self.log.info("Running file in user namespace: %s" % full_filename)
587 self.shell.safe_execfile(full_filename, self.shell.user_ns)
586 self.shell.safe_execfile(full_filename, self.shell.user_ns)
588 elif full_filename.endswith('.ipy'):
587 elif full_filename.endswith('.ipy'):
589 self.log.info("Running file in user namespace: %s" % full_filename)
588 self.log.info("Running file in user namespace: %s" % full_filename)
590 self.shell.safe_execfile_ipy(full_filename)
589 self.shell.safe_execfile_ipy(full_filename)
591 else:
590 else:
592 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)
593
592
594 def _run_exec_files(self):
593 def _run_exec_files(self):
595 try:
594 try:
596 if hasattr(self.master_config.Global, 'exec_files'):
595 if hasattr(self.master_config.Global, 'exec_files'):
597 self.log.debug("Running files in Global.exec_files...")
596 self.log.debug("Running files in Global.exec_files...")
598 exec_files = self.master_config.Global.exec_files
597 exec_files = self.master_config.Global.exec_files
599 for fname in exec_files:
598 for fname in exec_files:
600 self._exec_file(fname)
599 self._exec_file(fname)
601 except:
600 except:
602 self.log.warn("Unknown error in handling Global.exec_files:")
601 self.log.warn("Unknown error in handling Global.exec_files:")
603 self.shell.showtraceback()
602 self.shell.showtraceback()
604
603
605 def _run_cmd_line_code(self):
604 def _run_cmd_line_code(self):
606 if hasattr(self.master_config.Global, 'code_to_run'):
605 if hasattr(self.master_config.Global, 'code_to_run'):
607 line = self.master_config.Global.code_to_run
606 line = self.master_config.Global.code_to_run
608 try:
607 try:
609 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)
610 self.shell.runlines(line)
609 self.shell.runlines(line)
611 except:
610 except:
612 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)
613 self.shell.showtraceback()
612 self.shell.showtraceback()
614 return
613 return
615 # 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
616 try:
615 try:
617 fname = self.extra_args[0]
616 fname = self.extra_args[0]
618 except:
617 except:
619 pass
618 pass
620 else:
619 else:
621 try:
620 try:
622 self._exec_file(fname)
621 self._exec_file(fname)
623 except:
622 except:
624 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)
625 self.shell.showtraceback()
624 self.shell.showtraceback()
626
625
627 def _configure_xmode(self):
628 # XXX - shouldn't this be read from the config? I'm still a little
629 # lost with all the details of handling the new config guys...
630 self.shell.InteractiveTB.set_mode(mode=self.shell.xmode)
631
632 def start_app(self):
626 def start_app(self):
633 if self.master_config.Global.interact:
627 if self.master_config.Global.interact:
634 self.log.debug("Starting IPython's mainloop...")
628 self.log.debug("Starting IPython's mainloop...")
635 self.shell.mainloop()
629 self.shell.mainloop()
636 else:
630 else:
637 self.log.debug("IPython not interactive, start_app is no-op...")
631 self.log.debug("IPython not interactive, start_app is no-op...")
638
632
639
633
640 def load_default_config(ipython_dir=None):
634 def load_default_config(ipython_dir=None):
641 """Load the default config file from the default ipython_dir.
635 """Load the default config file from the default ipython_dir.
642
636
643 This is useful for embedded shells.
637 This is useful for embedded shells.
644 """
638 """
645 if ipython_dir is None:
639 if ipython_dir is None:
646 ipython_dir = get_ipython_dir()
640 ipython_dir = get_ipython_dir()
647 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
641 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
648 config = cl.load_config()
642 config = cl.load_config()
649 return config
643 return config
650
644
651
645
652 def launch_new_instance():
646 def launch_new_instance():
653 """Create and run a full blown IPython instance"""
647 """Create and run a full blown IPython instance"""
654 app = IPythonApp()
648 app = IPythonApp()
655 app.start()
649 app.start()
@@ -1,2549 +1,2558 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 from __future__ import absolute_import
21
21
22 import __builtin__
22 import __builtin__
23 import StringIO
24 import bdb
23 import bdb
25 import codeop
24 import codeop
26 import exceptions
25 import exceptions
27 import new
26 import new
28 import os
27 import os
29 import re
28 import re
30 import string
29 import string
31 import sys
30 import sys
32 import tempfile
31 import tempfile
33 from contextlib import nested
32 from contextlib import nested
34
33
35 from IPython.core import debugger, oinspect
34 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
35 from IPython.core import history as ipcorehist
37 from IPython.core import prefilter
36 from IPython.core import prefilter
38 from IPython.core import shadowns
37 from IPython.core import shadowns
39 from IPython.core import ultratb
38 from IPython.core import ultratb
40 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
41 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.component import Component
41 from IPython.core.component import Component
43 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.error import TryNext, UsageError
43 from IPython.core.error import TryNext, UsageError
45 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
46 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
47 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
48 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.prefilter import PrefilterManager
49 from IPython.core.prompts import CachedOutput
48 from IPython.core.prompts import CachedOutput
50 from IPython.core.pylabtools import pylab_activate
51 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.usage import interactive_usage, default_banner
50 import IPython.core.hooks
52 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
53 from IPython.lib.inputhook import enable_gui
52 from IPython.lib.inputhook import enable_gui
54 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.lib.pylabtools import pylab_activate
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils import pickleshare
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.ipstruct import Struct
58 from IPython.utils.ipstruct import Struct
59 from IPython.utils.platutils import toggle_set_term_title, set_term_title
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
60 from IPython.utils.strdispatch import StrDispatch
67 from IPython.utils.strdispatch import StrDispatch
61 from IPython.utils.syspathcontext import prepended_to_syspath
68 from IPython.utils.syspathcontext import prepended_to_syspath
62
69 from IPython.utils.terminal import toggle_set_term_title, set_term_title
63 # XXX - need to clean up this import * line
70 from IPython.utils.warn import warn, error, fatal
64 from IPython.utils.genutils import *
65
66 # from IPython.utils import growl
67 # growl.start("IPython")
68
69 from IPython.utils.traitlets import (
71 from IPython.utils.traitlets import (
70 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
72 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
71 )
73 )
72
74
75 # from IPython.utils import growl
76 # growl.start("IPython")
77
73 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
74 # Globals
79 # Globals
75 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
76
81
77 # 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
78 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
79 raw_input_original = raw_input
84 raw_input_original = raw_input
80
85
81 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83
88
84 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
85 # Utilities
90 # Utilities
86 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
87
92
88 ini_spaces_re = re.compile(r'^(\s+)')
93 ini_spaces_re = re.compile(r'^(\s+)')
89
94
90
95
91 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
92 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
93
98
94 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
95 if ini_spaces:
100 if ini_spaces:
96 return ini_spaces.end()
101 return ini_spaces.end()
97 else:
102 else:
98 return 0
103 return 0
99
104
100
105
101 def softspace(file, newvalue):
106 def softspace(file, newvalue):
102 """Copied from code.py, to remove the dependency"""
107 """Copied from code.py, to remove the dependency"""
103
108
104 oldvalue = 0
109 oldvalue = 0
105 try:
110 try:
106 oldvalue = file.softspace
111 oldvalue = file.softspace
107 except AttributeError:
112 except AttributeError:
108 pass
113 pass
109 try:
114 try:
110 file.softspace = newvalue
115 file.softspace = newvalue
111 except (AttributeError, TypeError):
116 except (AttributeError, TypeError):
112 # "attribute-less object" or "read-only attributes"
117 # "attribute-less object" or "read-only attributes"
113 pass
118 pass
114 return oldvalue
119 return oldvalue
115
120
116
121
117 def no_op(*a, **kw): pass
122 def no_op(*a, **kw): pass
118
123
119 class SpaceInInput(exceptions.Exception): pass
124 class SpaceInInput(exceptions.Exception): pass
120
125
121 class Bunch: pass
126 class Bunch: pass
122
127
123 class InputList(list):
128 class InputList(list):
124 """Class to store user input.
129 """Class to store user input.
125
130
126 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
127 allowing things like (assuming 'In' is an instance):
132 allowing things like (assuming 'In' is an instance):
128
133
129 exec In[4:7]
134 exec In[4:7]
130
135
131 or
136 or
132
137
133 exec In[5:9] + In[14] + In[21:25]"""
138 exec In[5:9] + In[14] + In[21:25]"""
134
139
135 def __getslice__(self,i,j):
140 def __getslice__(self,i,j):
136 return ''.join(list.__getslice__(self,i,j))
141 return ''.join(list.__getslice__(self,i,j))
137
142
138
143
139 class SyntaxTB(ultratb.ListTB):
144 class SyntaxTB(ultratb.ListTB):
140 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
141
146
142 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
143 ultratb.ListTB.__init__(self,color_scheme)
148 ultratb.ListTB.__init__(self,color_scheme)
144 self.last_syntax_error = None
149 self.last_syntax_error = None
145
150
146 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
147 self.last_syntax_error = value
152 self.last_syntax_error = value
148 ultratb.ListTB.__call__(self,etype,value,elist)
153 ultratb.ListTB.__call__(self,etype,value,elist)
149
154
150 def clear_err_state(self):
155 def clear_err_state(self):
151 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
152 e = self.last_syntax_error
157 e = self.last_syntax_error
153 self.last_syntax_error = None
158 self.last_syntax_error = None
154 return e
159 return e
155
160
156
161
157 def get_default_editor():
162 def get_default_editor():
158 try:
163 try:
159 ed = os.environ['EDITOR']
164 ed = os.environ['EDITOR']
160 except KeyError:
165 except KeyError:
161 if os.name == 'posix':
166 if os.name == 'posix':
162 ed = 'vi' # the only one guaranteed to be there!
167 ed = 'vi' # the only one guaranteed to be there!
163 else:
168 else:
164 ed = 'notepad' # same in Windows!
169 ed = 'notepad' # same in Windows!
165 return ed
170 return ed
166
171
167
172
168 def get_default_colors():
173 def get_default_colors():
169 if sys.platform=='darwin':
174 if sys.platform=='darwin':
170 return "LightBG"
175 return "LightBG"
171 elif os.name=='nt':
176 elif os.name=='nt':
172 return 'Linux'
177 return 'Linux'
173 else:
178 else:
174 return 'Linux'
179 return 'Linux'
175
180
176
181
177 class SeparateStr(Str):
182 class SeparateStr(Str):
178 """A Str subclass to validate separate_in, separate_out, etc.
183 """A Str subclass to validate separate_in, separate_out, etc.
179
184
180 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'.
181 """
186 """
182
187
183 def validate(self, obj, value):
188 def validate(self, obj, value):
184 if value == '0': value = ''
189 if value == '0': value = ''
185 value = value.replace('\\n','\n')
190 value = value.replace('\\n','\n')
186 return super(SeparateStr, self).validate(obj, value)
191 return super(SeparateStr, self).validate(obj, value)
187
192
188
193
189 def make_user_namespaces(user_ns=None, user_global_ns=None):
194 def make_user_namespaces(user_ns=None, user_global_ns=None):
190 """Return a valid local and global user interactive namespaces.
195 """Return a valid local and global user interactive namespaces.
191
196
192 This builds a dict with the minimal information needed to operate as a
197 This builds a dict with the minimal information needed to operate as a
193 valid IPython user namespace, which you can pass to the various
198 valid IPython user namespace, which you can pass to the various
194 embedding classes in ipython. The default implementation returns the
199 embedding classes in ipython. The default implementation returns the
195 same dict for both the locals and the globals to allow functions to
200 same dict for both the locals and the globals to allow functions to
196 refer to variables in the namespace. Customized implementations can
201 refer to variables in the namespace. Customized implementations can
197 return different dicts. The locals dictionary can actually be anything
202 return different dicts. The locals dictionary can actually be anything
198 following the basic mapping protocol of a dict, but the globals dict
203 following the basic mapping protocol of a dict, but the globals dict
199 must be a true dict, not even a subclass. It is recommended that any
204 must be a true dict, not even a subclass. It is recommended that any
200 custom object for the locals namespace synchronize with the globals
205 custom object for the locals namespace synchronize with the globals
201 dict somehow.
206 dict somehow.
202
207
203 Raises TypeError if the provided globals namespace is not a true dict.
208 Raises TypeError if the provided globals namespace is not a true dict.
204
209
205 Parameters
210 Parameters
206 ----------
211 ----------
207 user_ns : dict-like, optional
212 user_ns : dict-like, optional
208 The current user namespace. The items in this namespace should
213 The current user namespace. The items in this namespace should
209 be included in the output. If None, an appropriate blank
214 be included in the output. If None, an appropriate blank
210 namespace should be created.
215 namespace should be created.
211 user_global_ns : dict, optional
216 user_global_ns : dict, optional
212 The current user global namespace. The items in this namespace
217 The current user global namespace. The items in this namespace
213 should be included in the output. If None, an appropriate
218 should be included in the output. If None, an appropriate
214 blank namespace should be created.
219 blank namespace should be created.
215
220
216 Returns
221 Returns
217 -------
222 -------
218 A pair of dictionary-like object to be used as the local namespace
223 A pair of dictionary-like object to be used as the local namespace
219 of the interpreter and a dict to be used as the global namespace.
224 of the interpreter and a dict to be used as the global namespace.
220 """
225 """
221
226
222
227
223 # We must ensure that __builtin__ (without the final 's') is always
228 # We must ensure that __builtin__ (without the final 's') is always
224 # available and pointing to the __builtin__ *module*. For more details:
229 # available and pointing to the __builtin__ *module*. For more details:
225 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
230 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
226
231
227 if user_ns is None:
232 if user_ns is None:
228 # Set __name__ to __main__ to better match the behavior of the
233 # Set __name__ to __main__ to better match the behavior of the
229 # normal interpreter.
234 # normal interpreter.
230 user_ns = {'__name__' :'__main__',
235 user_ns = {'__name__' :'__main__',
231 '__builtin__' : __builtin__,
236 '__builtin__' : __builtin__,
232 '__builtins__' : __builtin__,
237 '__builtins__' : __builtin__,
233 }
238 }
234 else:
239 else:
235 user_ns.setdefault('__name__','__main__')
240 user_ns.setdefault('__name__','__main__')
236 user_ns.setdefault('__builtin__',__builtin__)
241 user_ns.setdefault('__builtin__',__builtin__)
237 user_ns.setdefault('__builtins__',__builtin__)
242 user_ns.setdefault('__builtins__',__builtin__)
238
243
239 if user_global_ns is None:
244 if user_global_ns is None:
240 user_global_ns = user_ns
245 user_global_ns = user_ns
241 if type(user_global_ns) is not dict:
246 if type(user_global_ns) is not dict:
242 raise TypeError("user_global_ns must be a true dict; got %r"
247 raise TypeError("user_global_ns must be a true dict; got %r"
243 % type(user_global_ns))
248 % type(user_global_ns))
244
249
245 return user_ns, user_global_ns
250 return user_ns, user_global_ns
246
251
247 #-----------------------------------------------------------------------------
252 #-----------------------------------------------------------------------------
248 # Main IPython class
253 # Main IPython class
249 #-----------------------------------------------------------------------------
254 #-----------------------------------------------------------------------------
250
255
251
256
252 class InteractiveShell(Component, Magic):
257 class InteractiveShell(Component, Magic):
253 """An enhanced, interactive shell for Python."""
258 """An enhanced, interactive shell for Python."""
254
259
255 autocall = Enum((0,1,2), default_value=1, config=True)
260 autocall = Enum((0,1,2), default_value=1, config=True)
256 autoedit_syntax = CBool(False, config=True)
261 autoedit_syntax = CBool(False, config=True)
257 autoindent = CBool(True, config=True)
262 autoindent = CBool(True, config=True)
258 automagic = CBool(True, config=True)
263 automagic = CBool(True, config=True)
259 banner = Str('')
264 banner = Str('')
260 banner1 = Str(default_banner, config=True)
265 banner1 = Str(default_banner, config=True)
261 banner2 = Str('', config=True)
266 banner2 = Str('', config=True)
262 cache_size = Int(1000, config=True)
267 cache_size = Int(1000, config=True)
263 color_info = CBool(True, config=True)
268 color_info = CBool(True, config=True)
264 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
269 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
265 default_value=get_default_colors(), config=True)
270 default_value=get_default_colors(), config=True)
266 confirm_exit = CBool(True, config=True)
271 confirm_exit = CBool(True, config=True)
267 debug = CBool(False, config=True)
272 debug = CBool(False, config=True)
268 deep_reload = CBool(False, config=True)
273 deep_reload = CBool(False, config=True)
269 # This display_banner only controls whether or not self.show_banner()
274 # This display_banner only controls whether or not self.show_banner()
270 # is called when mainloop/interact are called. The default is False
275 # is called when mainloop/interact are called. The default is False
271 # because for the terminal based application, the banner behavior
276 # because for the terminal based application, the banner behavior
272 # is controlled by Global.display_banner, which IPythonApp looks at
277 # is controlled by Global.display_banner, which IPythonApp looks at
273 # to determine if *it* should call show_banner() by hand or not.
278 # to determine if *it* should call show_banner() by hand or not.
274 display_banner = CBool(False) # This isn't configurable!
279 display_banner = CBool(False) # This isn't configurable!
275 embedded = CBool(False)
280 embedded = CBool(False)
276 embedded_active = CBool(False)
281 embedded_active = CBool(False)
277 editor = Str(get_default_editor(), config=True)
282 editor = Str(get_default_editor(), config=True)
278 filename = Str("<ipython console>")
283 filename = Str("<ipython console>")
279 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
284 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
280 logstart = CBool(False, config=True)
285 logstart = CBool(False, config=True)
281 logfile = Str('', config=True)
286 logfile = Str('', config=True)
282 logappend = Str('', config=True)
287 logappend = Str('', config=True)
283 object_info_string_level = Enum((0,1,2), default_value=0,
288 object_info_string_level = Enum((0,1,2), default_value=0,
284 config=True)
289 config=True)
285 pager = Str('less', config=True)
290 pager = Str('less', config=True)
286 pdb = CBool(False, config=True)
291 pdb = CBool(False, config=True)
287 pprint = CBool(True, config=True)
292 pprint = CBool(True, config=True)
288 profile = Str('', config=True)
293 profile = Str('', config=True)
289 prompt_in1 = Str('In [\\#]: ', config=True)
294 prompt_in1 = Str('In [\\#]: ', config=True)
290 prompt_in2 = Str(' .\\D.: ', config=True)
295 prompt_in2 = Str(' .\\D.: ', config=True)
291 prompt_out = Str('Out[\\#]: ', config=True)
296 prompt_out = Str('Out[\\#]: ', config=True)
292 prompts_pad_left = CBool(True, config=True)
297 prompts_pad_left = CBool(True, config=True)
293 quiet = CBool(False, config=True)
298 quiet = CBool(False, config=True)
294
299
295 readline_use = CBool(True, config=True)
300 readline_use = CBool(True, config=True)
296 readline_merge_completions = CBool(True, config=True)
301 readline_merge_completions = CBool(True, config=True)
297 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
302 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
298 readline_remove_delims = Str('-/~', config=True)
303 readline_remove_delims = Str('-/~', config=True)
299 readline_parse_and_bind = List([
304 readline_parse_and_bind = List([
300 'tab: complete',
305 'tab: complete',
301 '"\C-l": possible-completions',
306 '"\C-l": possible-completions',
302 'set show-all-if-ambiguous on',
307 'set show-all-if-ambiguous on',
303 '"\C-o": tab-insert',
308 '"\C-o": tab-insert',
304 '"\M-i": " "',
309 '"\M-i": " "',
305 '"\M-o": "\d\d\d\d"',
310 '"\M-o": "\d\d\d\d"',
306 '"\M-I": "\d\d\d\d"',
311 '"\M-I": "\d\d\d\d"',
307 '"\C-r": reverse-search-history',
312 '"\C-r": reverse-search-history',
308 '"\C-s": forward-search-history',
313 '"\C-s": forward-search-history',
309 '"\C-p": history-search-backward',
314 '"\C-p": history-search-backward',
310 '"\C-n": history-search-forward',
315 '"\C-n": history-search-forward',
311 '"\e[A": history-search-backward',
316 '"\e[A": history-search-backward',
312 '"\e[B": history-search-forward',
317 '"\e[B": history-search-forward',
313 '"\C-k": kill-line',
318 '"\C-k": kill-line',
314 '"\C-u": unix-line-discard',
319 '"\C-u": unix-line-discard',
315 ], allow_none=False, config=True)
320 ], allow_none=False, config=True)
316
321
317 screen_length = Int(0, config=True)
322 screen_length = Int(0, config=True)
318
323
319 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
324 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
320 separate_in = SeparateStr('\n', config=True)
325 separate_in = SeparateStr('\n', config=True)
321 separate_out = SeparateStr('', config=True)
326 separate_out = SeparateStr('', config=True)
322 separate_out2 = SeparateStr('', config=True)
327 separate_out2 = SeparateStr('', config=True)
323
328
324 system_header = Str('IPython system call: ', config=True)
329 system_header = Str('IPython system call: ', config=True)
325 system_verbose = CBool(False, config=True)
330 system_verbose = CBool(False, config=True)
326 term_title = CBool(False, config=True)
331 term_title = CBool(False, config=True)
327 wildcards_case_sensitive = CBool(True, config=True)
332 wildcards_case_sensitive = CBool(True, config=True)
328 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
333 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
329 default_value='Context', config=True)
334 default_value='Context', config=True)
330
335
331 autoexec = List(allow_none=False)
336 autoexec = List(allow_none=False)
332
337
333 # class attribute to indicate whether the class supports threads or not.
338 # class attribute to indicate whether the class supports threads or not.
334 # Subclasses with thread support should override this as needed.
339 # Subclasses with thread support should override this as needed.
335 isthreaded = False
340 isthreaded = False
336
341
337 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
342 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
338 user_ns=None, user_global_ns=None,
343 user_ns=None, user_global_ns=None,
339 banner1=None, banner2=None, display_banner=None,
344 banner1=None, banner2=None, display_banner=None,
340 custom_exceptions=((),None)):
345 custom_exceptions=((),None)):
341
346
342 # This is where traitlets with a config_key argument are updated
347 # This is where traitlets with a config_key argument are updated
343 # from the values on config.
348 # from the values on config.
344 super(InteractiveShell, self).__init__(parent, config=config)
349 super(InteractiveShell, self).__init__(parent, config=config)
345
350
346 # These are relatively independent and stateless
351 # These are relatively independent and stateless
347 self.init_ipython_dir(ipython_dir)
352 self.init_ipython_dir(ipython_dir)
348 self.init_instance_attrs()
353 self.init_instance_attrs()
349 self.init_term_title()
354 self.init_term_title()
350 self.init_usage(usage)
355 self.init_usage(usage)
351 self.init_banner(banner1, banner2, display_banner)
356 self.init_banner(banner1, banner2, display_banner)
352
357
353 # Create namespaces (user_ns, user_global_ns, etc.)
358 # Create namespaces (user_ns, user_global_ns, etc.)
354 self.init_create_namespaces(user_ns, user_global_ns)
359 self.init_create_namespaces(user_ns, user_global_ns)
355 # This has to be done after init_create_namespaces because it uses
360 # This has to be done after init_create_namespaces because it uses
356 # something in self.user_ns, but before init_sys_modules, which
361 # something in self.user_ns, but before init_sys_modules, which
357 # is the first thing to modify sys.
362 # is the first thing to modify sys.
358 self.save_sys_module_state()
363 self.save_sys_module_state()
359 self.init_sys_modules()
364 self.init_sys_modules()
360
365
361 self.init_history()
366 self.init_history()
362 self.init_encoding()
367 self.init_encoding()
363 self.init_prefilter()
368 self.init_prefilter()
364
369
365 Magic.__init__(self, self)
370 Magic.__init__(self, self)
366
371
367 self.init_syntax_highlighting()
372 self.init_syntax_highlighting()
368 self.init_hooks()
373 self.init_hooks()
369 self.init_pushd_popd_magic()
374 self.init_pushd_popd_magic()
370 self.init_traceback_handlers(custom_exceptions)
375 self.init_traceback_handlers(custom_exceptions)
371 self.init_user_ns()
376 self.init_user_ns()
372 self.init_logger()
377 self.init_logger()
373 self.init_alias()
378 self.init_alias()
374 self.init_builtins()
379 self.init_builtins()
375
380
376 # pre_config_initialization
381 # pre_config_initialization
377 self.init_shadow_hist()
382 self.init_shadow_hist()
378
383
379 # The next section should contain averything that was in ipmaker.
384 # The next section should contain averything that was in ipmaker.
380 self.init_logstart()
385 self.init_logstart()
381
386
382 # The following was in post_config_initialization
387 # The following was in post_config_initialization
383 self.init_inspector()
388 self.init_inspector()
384 self.init_readline()
389 self.init_readline()
385 self.init_prompts()
390 self.init_prompts()
386 self.init_displayhook()
391 self.init_displayhook()
387 self.init_reload_doctest()
392 self.init_reload_doctest()
388 self.init_magics()
393 self.init_magics()
389 self.init_pdb()
394 self.init_pdb()
390 self.hooks.late_startup_hook()
395 self.hooks.late_startup_hook()
391
396
392 def get_ipython(self):
397 def get_ipython(self):
393 """Return the currently running IPython instance."""
398 """Return the currently running IPython instance."""
394 return self
399 return self
395
400
396 #-------------------------------------------------------------------------
401 #-------------------------------------------------------------------------
397 # Traitlet changed handlers
402 # Traitlet changed handlers
398 #-------------------------------------------------------------------------
403 #-------------------------------------------------------------------------
399
404
400 def _banner1_changed(self):
405 def _banner1_changed(self):
401 self.compute_banner()
406 self.compute_banner()
402
407
403 def _banner2_changed(self):
408 def _banner2_changed(self):
404 self.compute_banner()
409 self.compute_banner()
405
410
406 def _ipython_dir_changed(self, name, new):
411 def _ipython_dir_changed(self, name, new):
407 if not os.path.isdir(new):
412 if not os.path.isdir(new):
408 os.makedirs(new, mode = 0777)
413 os.makedirs(new, mode = 0777)
409 if not os.path.isdir(self.ipython_extension_dir):
414 if not os.path.isdir(self.ipython_extension_dir):
410 os.makedirs(self.ipython_extension_dir, mode = 0777)
415 os.makedirs(self.ipython_extension_dir, mode = 0777)
411
416
412 @property
417 @property
413 def ipython_extension_dir(self):
418 def ipython_extension_dir(self):
414 return os.path.join(self.ipython_dir, 'extensions')
419 return os.path.join(self.ipython_dir, 'extensions')
415
420
416 @property
421 @property
417 def usable_screen_length(self):
422 def usable_screen_length(self):
418 if self.screen_length == 0:
423 if self.screen_length == 0:
419 return 0
424 return 0
420 else:
425 else:
421 num_lines_bot = self.separate_in.count('\n')+1
426 num_lines_bot = self.separate_in.count('\n')+1
422 return self.screen_length - num_lines_bot
427 return self.screen_length - num_lines_bot
423
428
424 def _term_title_changed(self, name, new_value):
429 def _term_title_changed(self, name, new_value):
425 self.init_term_title()
430 self.init_term_title()
426
431
427 def set_autoindent(self,value=None):
432 def set_autoindent(self,value=None):
428 """Set the autoindent flag, checking for readline support.
433 """Set the autoindent flag, checking for readline support.
429
434
430 If called with no arguments, it acts as a toggle."""
435 If called with no arguments, it acts as a toggle."""
431
436
432 if not self.has_readline:
437 if not self.has_readline:
433 if os.name == 'posix':
438 if os.name == 'posix':
434 warn("The auto-indent feature requires the readline library")
439 warn("The auto-indent feature requires the readline library")
435 self.autoindent = 0
440 self.autoindent = 0
436 return
441 return
437 if value is None:
442 if value is None:
438 self.autoindent = not self.autoindent
443 self.autoindent = not self.autoindent
439 else:
444 else:
440 self.autoindent = value
445 self.autoindent = value
441
446
442 #-------------------------------------------------------------------------
447 #-------------------------------------------------------------------------
443 # init_* methods called by __init__
448 # init_* methods called by __init__
444 #-------------------------------------------------------------------------
449 #-------------------------------------------------------------------------
445
450
446 def init_ipython_dir(self, ipython_dir):
451 def init_ipython_dir(self, ipython_dir):
447 if ipython_dir is not None:
452 if ipython_dir is not None:
448 self.ipython_dir = ipython_dir
453 self.ipython_dir = ipython_dir
449 self.config.Global.ipython_dir = self.ipython_dir
454 self.config.Global.ipython_dir = self.ipython_dir
450 return
455 return
451
456
452 if hasattr(self.config.Global, 'ipython_dir'):
457 if hasattr(self.config.Global, 'ipython_dir'):
453 self.ipython_dir = self.config.Global.ipython_dir
458 self.ipython_dir = self.config.Global.ipython_dir
454 else:
459 else:
455 self.ipython_dir = get_ipython_dir()
460 self.ipython_dir = get_ipython_dir()
456
461
457 # All children can just read this
462 # All children can just read this
458 self.config.Global.ipython_dir = self.ipython_dir
463 self.config.Global.ipython_dir = self.ipython_dir
459
464
460 def init_instance_attrs(self):
465 def init_instance_attrs(self):
461 self.jobs = BackgroundJobManager()
466 self.jobs = BackgroundJobManager()
462 self.more = False
467 self.more = False
463
468
464 # command compiler
469 # command compiler
465 self.compile = codeop.CommandCompiler()
470 self.compile = codeop.CommandCompiler()
466
471
467 # User input buffer
472 # User input buffer
468 self.buffer = []
473 self.buffer = []
469
474
470 # Make an empty namespace, which extension writers can rely on both
475 # Make an empty namespace, which extension writers can rely on both
471 # existing and NEVER being used by ipython itself. This gives them a
476 # existing and NEVER being used by ipython itself. This gives them a
472 # convenient location for storing additional information and state
477 # convenient location for storing additional information and state
473 # their extensions may require, without fear of collisions with other
478 # their extensions may require, without fear of collisions with other
474 # ipython names that may develop later.
479 # ipython names that may develop later.
475 self.meta = Struct()
480 self.meta = Struct()
476
481
477 # Object variable to store code object waiting execution. This is
482 # Object variable to store code object waiting execution. This is
478 # used mainly by the multithreaded shells, but it can come in handy in
483 # used mainly by the multithreaded shells, but it can come in handy in
479 # other situations. No need to use a Queue here, since it's a single
484 # other situations. No need to use a Queue here, since it's a single
480 # item which gets cleared once run.
485 # item which gets cleared once run.
481 self.code_to_run = None
486 self.code_to_run = None
482
487
483 # Flag to mark unconditional exit
488 # Flag to mark unconditional exit
484 self.exit_now = False
489 self.exit_now = False
485
490
486 # Temporary files used for various purposes. Deleted at exit.
491 # Temporary files used for various purposes. Deleted at exit.
487 self.tempfiles = []
492 self.tempfiles = []
488
493
489 # Keep track of readline usage (later set by init_readline)
494 # Keep track of readline usage (later set by init_readline)
490 self.has_readline = False
495 self.has_readline = False
491
496
492 # keep track of where we started running (mainly for crash post-mortem)
497 # keep track of where we started running (mainly for crash post-mortem)
493 # This is not being used anywhere currently.
498 # This is not being used anywhere currently.
494 self.starting_dir = os.getcwd()
499 self.starting_dir = os.getcwd()
495
500
496 # Indentation management
501 # Indentation management
497 self.indent_current_nsp = 0
502 self.indent_current_nsp = 0
498
503
499 def init_term_title(self):
504 def init_term_title(self):
500 # Enable or disable the terminal title.
505 # Enable or disable the terminal title.
501 if self.term_title:
506 if self.term_title:
502 toggle_set_term_title(True)
507 toggle_set_term_title(True)
503 set_term_title('IPython: ' + abbrev_cwd())
508 set_term_title('IPython: ' + abbrev_cwd())
504 else:
509 else:
505 toggle_set_term_title(False)
510 toggle_set_term_title(False)
506
511
507 def init_usage(self, usage=None):
512 def init_usage(self, usage=None):
508 if usage is None:
513 if usage is None:
509 self.usage = interactive_usage
514 self.usage = interactive_usage
510 else:
515 else:
511 self.usage = usage
516 self.usage = usage
512
517
513 def init_encoding(self):
518 def init_encoding(self):
514 # Get system encoding at startup time. Certain terminals (like Emacs
519 # Get system encoding at startup time. Certain terminals (like Emacs
515 # under Win32 have it set to None, and we need to have a known valid
520 # under Win32 have it set to None, and we need to have a known valid
516 # encoding to use in the raw_input() method
521 # encoding to use in the raw_input() method
517 try:
522 try:
518 self.stdin_encoding = sys.stdin.encoding or 'ascii'
523 self.stdin_encoding = sys.stdin.encoding or 'ascii'
519 except AttributeError:
524 except AttributeError:
520 self.stdin_encoding = 'ascii'
525 self.stdin_encoding = 'ascii'
521
526
522 def init_syntax_highlighting(self):
527 def init_syntax_highlighting(self):
523 # Python source parser/formatter for syntax highlighting
528 # Python source parser/formatter for syntax highlighting
524 pyformat = PyColorize.Parser().format
529 pyformat = PyColorize.Parser().format
525 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
530 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
526
531
527 def init_pushd_popd_magic(self):
532 def init_pushd_popd_magic(self):
528 # for pushd/popd management
533 # for pushd/popd management
529 try:
534 try:
530 self.home_dir = get_home_dir()
535 self.home_dir = get_home_dir()
531 except HomeDirError, msg:
536 except HomeDirError, msg:
532 fatal(msg)
537 fatal(msg)
533
538
534 self.dir_stack = []
539 self.dir_stack = []
535
540
536 def init_logger(self):
541 def init_logger(self):
537 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
542 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
538 # local shortcut, this is used a LOT
543 # local shortcut, this is used a LOT
539 self.log = self.logger.log
544 self.log = self.logger.log
540
545
541 def init_logstart(self):
546 def init_logstart(self):
542 if self.logappend:
547 if self.logappend:
543 self.magic_logstart(self.logappend + ' append')
548 self.magic_logstart(self.logappend + ' append')
544 elif self.logfile:
549 elif self.logfile:
545 self.magic_logstart(self.logfile)
550 self.magic_logstart(self.logfile)
546 elif self.logstart:
551 elif self.logstart:
547 self.magic_logstart()
552 self.magic_logstart()
548
553
549 def init_builtins(self):
554 def init_builtins(self):
550 self.builtin_trap = BuiltinTrap(self)
555 self.builtin_trap = BuiltinTrap(self)
551
556
552 def init_inspector(self):
557 def init_inspector(self):
553 # Object inspector
558 # Object inspector
554 self.inspector = oinspect.Inspector(oinspect.InspectColors,
559 self.inspector = oinspect.Inspector(oinspect.InspectColors,
555 PyColorize.ANSICodeColors,
560 PyColorize.ANSICodeColors,
556 'NoColor',
561 'NoColor',
557 self.object_info_string_level)
562 self.object_info_string_level)
558
563
559 def init_prompts(self):
564 def init_prompts(self):
560 # Initialize cache, set in/out prompts and printing system
565 # Initialize cache, set in/out prompts and printing system
561 self.outputcache = CachedOutput(self,
566 self.outputcache = CachedOutput(self,
562 self.cache_size,
567 self.cache_size,
563 self.pprint,
568 self.pprint,
564 input_sep = self.separate_in,
569 input_sep = self.separate_in,
565 output_sep = self.separate_out,
570 output_sep = self.separate_out,
566 output_sep2 = self.separate_out2,
571 output_sep2 = self.separate_out2,
567 ps1 = self.prompt_in1,
572 ps1 = self.prompt_in1,
568 ps2 = self.prompt_in2,
573 ps2 = self.prompt_in2,
569 ps_out = self.prompt_out,
574 ps_out = self.prompt_out,
570 pad_left = self.prompts_pad_left)
575 pad_left = self.prompts_pad_left)
571
576
572 # user may have over-ridden the default print hook:
577 # user may have over-ridden the default print hook:
573 try:
578 try:
574 self.outputcache.__class__.display = self.hooks.display
579 self.outputcache.__class__.display = self.hooks.display
575 except AttributeError:
580 except AttributeError:
576 pass
581 pass
577
582
578 def init_displayhook(self):
583 def init_displayhook(self):
579 self.display_trap = DisplayTrap(self, self.outputcache)
584 self.display_trap = DisplayTrap(self, self.outputcache)
580
585
581 def init_reload_doctest(self):
586 def init_reload_doctest(self):
582 # Do a proper resetting of doctest, including the necessary displayhook
587 # Do a proper resetting of doctest, including the necessary displayhook
583 # monkeypatching
588 # monkeypatching
584 try:
589 try:
585 doctest_reload()
590 doctest_reload()
586 except ImportError:
591 except ImportError:
587 warn("doctest module does not exist.")
592 warn("doctest module does not exist.")
588
593
589 #-------------------------------------------------------------------------
594 #-------------------------------------------------------------------------
590 # Things related to the banner
595 # Things related to the banner
591 #-------------------------------------------------------------------------
596 #-------------------------------------------------------------------------
592
597
593 def init_banner(self, banner1, banner2, display_banner):
598 def init_banner(self, banner1, banner2, display_banner):
594 if banner1 is not None:
599 if banner1 is not None:
595 self.banner1 = banner1
600 self.banner1 = banner1
596 if banner2 is not None:
601 if banner2 is not None:
597 self.banner2 = banner2
602 self.banner2 = banner2
598 if display_banner is not None:
603 if display_banner is not None:
599 self.display_banner = display_banner
604 self.display_banner = display_banner
600 self.compute_banner()
605 self.compute_banner()
601
606
602 def show_banner(self, banner=None):
607 def show_banner(self, banner=None):
603 if banner is None:
608 if banner is None:
604 banner = self.banner
609 banner = self.banner
605 self.write(banner)
610 self.write(banner)
606
611
607 def compute_banner(self):
612 def compute_banner(self):
608 self.banner = self.banner1 + '\n'
613 self.banner = self.banner1 + '\n'
609 if self.profile:
614 if self.profile:
610 self.banner += '\nIPython profile: %s\n' % self.profile
615 self.banner += '\nIPython profile: %s\n' % self.profile
611 if self.banner2:
616 if self.banner2:
612 self.banner += '\n' + self.banner2 + '\n'
617 self.banner += '\n' + self.banner2 + '\n'
613
618
614 #-------------------------------------------------------------------------
619 #-------------------------------------------------------------------------
615 # Things related to injections into the sys module
620 # Things related to injections into the sys module
616 #-------------------------------------------------------------------------
621 #-------------------------------------------------------------------------
617
622
618 def save_sys_module_state(self):
623 def save_sys_module_state(self):
619 """Save the state of hooks in the sys module.
624 """Save the state of hooks in the sys module.
620
625
621 This has to be called after self.user_ns is created.
626 This has to be called after self.user_ns is created.
622 """
627 """
623 self._orig_sys_module_state = {}
628 self._orig_sys_module_state = {}
624 self._orig_sys_module_state['stdin'] = sys.stdin
629 self._orig_sys_module_state['stdin'] = sys.stdin
625 self._orig_sys_module_state['stdout'] = sys.stdout
630 self._orig_sys_module_state['stdout'] = sys.stdout
626 self._orig_sys_module_state['stderr'] = sys.stderr
631 self._orig_sys_module_state['stderr'] = sys.stderr
627 self._orig_sys_module_state['excepthook'] = sys.excepthook
632 self._orig_sys_module_state['excepthook'] = sys.excepthook
628 try:
633 try:
629 self._orig_sys_modules_main_name = self.user_ns['__name__']
634 self._orig_sys_modules_main_name = self.user_ns['__name__']
630 except KeyError:
635 except KeyError:
631 pass
636 pass
632
637
633 def restore_sys_module_state(self):
638 def restore_sys_module_state(self):
634 """Restore the state of the sys module."""
639 """Restore the state of the sys module."""
635 try:
640 try:
636 for k, v in self._orig_sys_module_state.items():
641 for k, v in self._orig_sys_module_state.items():
637 setattr(sys, k, v)
642 setattr(sys, k, v)
638 except AttributeError:
643 except AttributeError:
639 pass
644 pass
640 try:
645 try:
641 delattr(sys, 'ipcompleter')
646 delattr(sys, 'ipcompleter')
642 except AttributeError:
647 except AttributeError:
643 pass
648 pass
644 # Reset what what done in self.init_sys_modules
649 # Reset what what done in self.init_sys_modules
645 try:
650 try:
646 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
651 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
647 except (AttributeError, KeyError):
652 except (AttributeError, KeyError):
648 pass
653 pass
649
654
650 #-------------------------------------------------------------------------
655 #-------------------------------------------------------------------------
651 # Things related to hooks
656 # Things related to hooks
652 #-------------------------------------------------------------------------
657 #-------------------------------------------------------------------------
653
658
654 def init_hooks(self):
659 def init_hooks(self):
655 # hooks holds pointers used for user-side customizations
660 # hooks holds pointers used for user-side customizations
656 self.hooks = Struct()
661 self.hooks = Struct()
657
662
658 self.strdispatchers = {}
663 self.strdispatchers = {}
659
664
660 # Set all default hooks, defined in the IPython.hooks module.
665 # Set all default hooks, defined in the IPython.hooks module.
661 import IPython.core.hooks
662 hooks = IPython.core.hooks
666 hooks = IPython.core.hooks
663 for hook_name in hooks.__all__:
667 for hook_name in hooks.__all__:
664 # default hooks have priority 100, i.e. low; user hooks should have
668 # default hooks have priority 100, i.e. low; user hooks should have
665 # 0-100 priority
669 # 0-100 priority
666 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
670 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
667
671
668 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
672 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
669 """set_hook(name,hook) -> sets an internal IPython hook.
673 """set_hook(name,hook) -> sets an internal IPython hook.
670
674
671 IPython exposes some of its internal API as user-modifiable hooks. By
675 IPython exposes some of its internal API as user-modifiable hooks. By
672 adding your function to one of these hooks, you can modify IPython's
676 adding your function to one of these hooks, you can modify IPython's
673 behavior to call at runtime your own routines."""
677 behavior to call at runtime your own routines."""
674
678
675 # At some point in the future, this should validate the hook before it
679 # At some point in the future, this should validate the hook before it
676 # accepts it. Probably at least check that the hook takes the number
680 # accepts it. Probably at least check that the hook takes the number
677 # of args it's supposed to.
681 # of args it's supposed to.
678
682
679 f = new.instancemethod(hook,self,self.__class__)
683 f = new.instancemethod(hook,self,self.__class__)
680
684
681 # check if the hook is for strdispatcher first
685 # check if the hook is for strdispatcher first
682 if str_key is not None:
686 if str_key is not None:
683 sdp = self.strdispatchers.get(name, StrDispatch())
687 sdp = self.strdispatchers.get(name, StrDispatch())
684 sdp.add_s(str_key, f, priority )
688 sdp.add_s(str_key, f, priority )
685 self.strdispatchers[name] = sdp
689 self.strdispatchers[name] = sdp
686 return
690 return
687 if re_key is not None:
691 if re_key is not None:
688 sdp = self.strdispatchers.get(name, StrDispatch())
692 sdp = self.strdispatchers.get(name, StrDispatch())
689 sdp.add_re(re.compile(re_key), f, priority )
693 sdp.add_re(re.compile(re_key), f, priority )
690 self.strdispatchers[name] = sdp
694 self.strdispatchers[name] = sdp
691 return
695 return
692
696
693 dp = getattr(self.hooks, name, None)
697 dp = getattr(self.hooks, name, None)
694 if name not in IPython.core.hooks.__all__:
698 if name not in IPython.core.hooks.__all__:
695 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
699 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
696 if not dp:
700 if not dp:
697 dp = IPython.core.hooks.CommandChainDispatcher()
701 dp = IPython.core.hooks.CommandChainDispatcher()
698
702
699 try:
703 try:
700 dp.add(f,priority)
704 dp.add(f,priority)
701 except AttributeError:
705 except AttributeError:
702 # it was not commandchain, plain old func - replace
706 # it was not commandchain, plain old func - replace
703 dp = f
707 dp = f
704
708
705 setattr(self.hooks,name, dp)
709 setattr(self.hooks,name, dp)
706
710
707 #-------------------------------------------------------------------------
711 #-------------------------------------------------------------------------
708 # Things related to the "main" module
712 # Things related to the "main" module
709 #-------------------------------------------------------------------------
713 #-------------------------------------------------------------------------
710
714
711 def new_main_mod(self,ns=None):
715 def new_main_mod(self,ns=None):
712 """Return a new 'main' module object for user code execution.
716 """Return a new 'main' module object for user code execution.
713 """
717 """
714 main_mod = self._user_main_module
718 main_mod = self._user_main_module
715 init_fakemod_dict(main_mod,ns)
719 init_fakemod_dict(main_mod,ns)
716 return main_mod
720 return main_mod
717
721
718 def cache_main_mod(self,ns,fname):
722 def cache_main_mod(self,ns,fname):
719 """Cache a main module's namespace.
723 """Cache a main module's namespace.
720
724
721 When scripts are executed via %run, we must keep a reference to the
725 When scripts are executed via %run, we must keep a reference to the
722 namespace of their __main__ module (a FakeModule instance) around so
726 namespace of their __main__ module (a FakeModule instance) around so
723 that Python doesn't clear it, rendering objects defined therein
727 that Python doesn't clear it, rendering objects defined therein
724 useless.
728 useless.
725
729
726 This method keeps said reference in a private dict, keyed by the
730 This method keeps said reference in a private dict, keyed by the
727 absolute path of the module object (which corresponds to the script
731 absolute path of the module object (which corresponds to the script
728 path). This way, for multiple executions of the same script we only
732 path). This way, for multiple executions of the same script we only
729 keep one copy of the namespace (the last one), thus preventing memory
733 keep one copy of the namespace (the last one), thus preventing memory
730 leaks from old references while allowing the objects from the last
734 leaks from old references while allowing the objects from the last
731 execution to be accessible.
735 execution to be accessible.
732
736
733 Note: we can not allow the actual FakeModule instances to be deleted,
737 Note: we can not allow the actual FakeModule instances to be deleted,
734 because of how Python tears down modules (it hard-sets all their
738 because of how Python tears down modules (it hard-sets all their
735 references to None without regard for reference counts). This method
739 references to None without regard for reference counts). This method
736 must therefore make a *copy* of the given namespace, to allow the
740 must therefore make a *copy* of the given namespace, to allow the
737 original module's __dict__ to be cleared and reused.
741 original module's __dict__ to be cleared and reused.
738
742
739
743
740 Parameters
744 Parameters
741 ----------
745 ----------
742 ns : a namespace (a dict, typically)
746 ns : a namespace (a dict, typically)
743
747
744 fname : str
748 fname : str
745 Filename associated with the namespace.
749 Filename associated with the namespace.
746
750
747 Examples
751 Examples
748 --------
752 --------
749
753
750 In [10]: import IPython
754 In [10]: import IPython
751
755
752 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
756 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
753
757
754 In [12]: IPython.__file__ in _ip._main_ns_cache
758 In [12]: IPython.__file__ in _ip._main_ns_cache
755 Out[12]: True
759 Out[12]: True
756 """
760 """
757 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
761 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
758
762
759 def clear_main_mod_cache(self):
763 def clear_main_mod_cache(self):
760 """Clear the cache of main modules.
764 """Clear the cache of main modules.
761
765
762 Mainly for use by utilities like %reset.
766 Mainly for use by utilities like %reset.
763
767
764 Examples
768 Examples
765 --------
769 --------
766
770
767 In [15]: import IPython
771 In [15]: import IPython
768
772
769 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
773 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
770
774
771 In [17]: len(_ip._main_ns_cache) > 0
775 In [17]: len(_ip._main_ns_cache) > 0
772 Out[17]: True
776 Out[17]: True
773
777
774 In [18]: _ip.clear_main_mod_cache()
778 In [18]: _ip.clear_main_mod_cache()
775
779
776 In [19]: len(_ip._main_ns_cache) == 0
780 In [19]: len(_ip._main_ns_cache) == 0
777 Out[19]: True
781 Out[19]: True
778 """
782 """
779 self._main_ns_cache.clear()
783 self._main_ns_cache.clear()
780
784
781 #-------------------------------------------------------------------------
785 #-------------------------------------------------------------------------
782 # Things related to debugging
786 # Things related to debugging
783 #-------------------------------------------------------------------------
787 #-------------------------------------------------------------------------
784
788
785 def init_pdb(self):
789 def init_pdb(self):
786 # Set calling of pdb on exceptions
790 # Set calling of pdb on exceptions
787 # self.call_pdb is a property
791 # self.call_pdb is a property
788 self.call_pdb = self.pdb
792 self.call_pdb = self.pdb
789
793
790 def _get_call_pdb(self):
794 def _get_call_pdb(self):
791 return self._call_pdb
795 return self._call_pdb
792
796
793 def _set_call_pdb(self,val):
797 def _set_call_pdb(self,val):
794
798
795 if val not in (0,1,False,True):
799 if val not in (0,1,False,True):
796 raise ValueError,'new call_pdb value must be boolean'
800 raise ValueError,'new call_pdb value must be boolean'
797
801
798 # store value in instance
802 # store value in instance
799 self._call_pdb = val
803 self._call_pdb = val
800
804
801 # notify the actual exception handlers
805 # notify the actual exception handlers
802 self.InteractiveTB.call_pdb = val
806 self.InteractiveTB.call_pdb = val
803 if self.isthreaded:
807 if self.isthreaded:
804 try:
808 try:
805 self.sys_excepthook.call_pdb = val
809 self.sys_excepthook.call_pdb = val
806 except:
810 except:
807 warn('Failed to activate pdb for threaded exception handler')
811 warn('Failed to activate pdb for threaded exception handler')
808
812
809 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
813 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
810 'Control auto-activation of pdb at exceptions')
814 'Control auto-activation of pdb at exceptions')
811
815
812 def debugger(self,force=False):
816 def debugger(self,force=False):
813 """Call the pydb/pdb debugger.
817 """Call the pydb/pdb debugger.
814
818
815 Keywords:
819 Keywords:
816
820
817 - force(False): by default, this routine checks the instance call_pdb
821 - force(False): by default, this routine checks the instance call_pdb
818 flag and does not actually invoke the debugger if the flag is false.
822 flag and does not actually invoke the debugger if the flag is false.
819 The 'force' option forces the debugger to activate even if the flag
823 The 'force' option forces the debugger to activate even if the flag
820 is false.
824 is false.
821 """
825 """
822
826
823 if not (force or self.call_pdb):
827 if not (force or self.call_pdb):
824 return
828 return
825
829
826 if not hasattr(sys,'last_traceback'):
830 if not hasattr(sys,'last_traceback'):
827 error('No traceback has been produced, nothing to debug.')
831 error('No traceback has been produced, nothing to debug.')
828 return
832 return
829
833
830 # use pydb if available
834 # use pydb if available
831 if debugger.has_pydb:
835 if debugger.has_pydb:
832 from pydb import pm
836 from pydb import pm
833 else:
837 else:
834 # fallback to our internal debugger
838 # fallback to our internal debugger
835 pm = lambda : self.InteractiveTB.debugger(force=True)
839 pm = lambda : self.InteractiveTB.debugger(force=True)
836 self.history_saving_wrapper(pm)()
840 self.history_saving_wrapper(pm)()
837
841
838 #-------------------------------------------------------------------------
842 #-------------------------------------------------------------------------
839 # Things related to IPython's various namespaces
843 # Things related to IPython's various namespaces
840 #-------------------------------------------------------------------------
844 #-------------------------------------------------------------------------
841
845
842 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
846 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
843 # Create the namespace where the user will operate. user_ns is
847 # Create the namespace where the user will operate. user_ns is
844 # normally the only one used, and it is passed to the exec calls as
848 # normally the only one used, and it is passed to the exec calls as
845 # the locals argument. But we do carry a user_global_ns namespace
849 # the locals argument. But we do carry a user_global_ns namespace
846 # given as the exec 'globals' argument, This is useful in embedding
850 # given as the exec 'globals' argument, This is useful in embedding
847 # situations where the ipython shell opens in a context where the
851 # situations where the ipython shell opens in a context where the
848 # distinction between locals and globals is meaningful. For
852 # distinction between locals and globals is meaningful. For
849 # non-embedded contexts, it is just the same object as the user_ns dict.
853 # non-embedded contexts, it is just the same object as the user_ns dict.
850
854
851 # FIXME. For some strange reason, __builtins__ is showing up at user
855 # FIXME. For some strange reason, __builtins__ is showing up at user
852 # level as a dict instead of a module. This is a manual fix, but I
856 # level as a dict instead of a module. This is a manual fix, but I
853 # should really track down where the problem is coming from. Alex
857 # should really track down where the problem is coming from. Alex
854 # Schmolck reported this problem first.
858 # Schmolck reported this problem first.
855
859
856 # A useful post by Alex Martelli on this topic:
860 # A useful post by Alex Martelli on this topic:
857 # Re: inconsistent value from __builtins__
861 # Re: inconsistent value from __builtins__
858 # Von: Alex Martelli <aleaxit@yahoo.com>
862 # Von: Alex Martelli <aleaxit@yahoo.com>
859 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
863 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
860 # Gruppen: comp.lang.python
864 # Gruppen: comp.lang.python
861
865
862 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
866 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
863 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
867 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
864 # > <type 'dict'>
868 # > <type 'dict'>
865 # > >>> print type(__builtins__)
869 # > >>> print type(__builtins__)
866 # > <type 'module'>
870 # > <type 'module'>
867 # > Is this difference in return value intentional?
871 # > Is this difference in return value intentional?
868
872
869 # Well, it's documented that '__builtins__' can be either a dictionary
873 # Well, it's documented that '__builtins__' can be either a dictionary
870 # or a module, and it's been that way for a long time. Whether it's
874 # or a module, and it's been that way for a long time. Whether it's
871 # intentional (or sensible), I don't know. In any case, the idea is
875 # intentional (or sensible), I don't know. In any case, the idea is
872 # that if you need to access the built-in namespace directly, you
876 # that if you need to access the built-in namespace directly, you
873 # should start with "import __builtin__" (note, no 's') which will
877 # should start with "import __builtin__" (note, no 's') which will
874 # definitely give you a module. Yeah, it's somewhat confusing:-(.
878 # definitely give you a module. Yeah, it's somewhat confusing:-(.
875
879
876 # These routines return properly built dicts as needed by the rest of
880 # These routines return properly built dicts as needed by the rest of
877 # the code, and can also be used by extension writers to generate
881 # the code, and can also be used by extension writers to generate
878 # properly initialized namespaces.
882 # properly initialized namespaces.
879 user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns)
883 user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns)
880
884
881 # Assign namespaces
885 # Assign namespaces
882 # This is the namespace where all normal user variables live
886 # This is the namespace where all normal user variables live
883 self.user_ns = user_ns
887 self.user_ns = user_ns
884 self.user_global_ns = user_global_ns
888 self.user_global_ns = user_global_ns
885
889
886 # An auxiliary namespace that checks what parts of the user_ns were
890 # An auxiliary namespace that checks what parts of the user_ns were
887 # loaded at startup, so we can list later only variables defined in
891 # loaded at startup, so we can list later only variables defined in
888 # actual interactive use. Since it is always a subset of user_ns, it
892 # actual interactive use. Since it is always a subset of user_ns, it
889 # doesn't need to be separately tracked in the ns_table.
893 # doesn't need to be separately tracked in the ns_table.
890 self.user_config_ns = {}
894 self.user_config_ns = {}
891
895
892 # A namespace to keep track of internal data structures to prevent
896 # A namespace to keep track of internal data structures to prevent
893 # them from cluttering user-visible stuff. Will be updated later
897 # them from cluttering user-visible stuff. Will be updated later
894 self.internal_ns = {}
898 self.internal_ns = {}
895
899
896 # Now that FakeModule produces a real module, we've run into a nasty
900 # Now that FakeModule produces a real module, we've run into a nasty
897 # problem: after script execution (via %run), the module where the user
901 # problem: after script execution (via %run), the module where the user
898 # code ran is deleted. Now that this object is a true module (needed
902 # code ran is deleted. Now that this object is a true module (needed
899 # so docetst and other tools work correctly), the Python module
903 # so docetst and other tools work correctly), the Python module
900 # teardown mechanism runs over it, and sets to None every variable
904 # teardown mechanism runs over it, and sets to None every variable
901 # present in that module. Top-level references to objects from the
905 # present in that module. Top-level references to objects from the
902 # script survive, because the user_ns is updated with them. However,
906 # script survive, because the user_ns is updated with them. However,
903 # calling functions defined in the script that use other things from
907 # calling functions defined in the script that use other things from
904 # the script will fail, because the function's closure had references
908 # the script will fail, because the function's closure had references
905 # to the original objects, which are now all None. So we must protect
909 # to the original objects, which are now all None. So we must protect
906 # these modules from deletion by keeping a cache.
910 # these modules from deletion by keeping a cache.
907 #
911 #
908 # To avoid keeping stale modules around (we only need the one from the
912 # To avoid keeping stale modules around (we only need the one from the
909 # last run), we use a dict keyed with the full path to the script, so
913 # last run), we use a dict keyed with the full path to the script, so
910 # only the last version of the module is held in the cache. Note,
914 # only the last version of the module is held in the cache. Note,
911 # however, that we must cache the module *namespace contents* (their
915 # however, that we must cache the module *namespace contents* (their
912 # __dict__). Because if we try to cache the actual modules, old ones
916 # __dict__). Because if we try to cache the actual modules, old ones
913 # (uncached) could be destroyed while still holding references (such as
917 # (uncached) could be destroyed while still holding references (such as
914 # those held by GUI objects that tend to be long-lived)>
918 # those held by GUI objects that tend to be long-lived)>
915 #
919 #
916 # The %reset command will flush this cache. See the cache_main_mod()
920 # The %reset command will flush this cache. See the cache_main_mod()
917 # and clear_main_mod_cache() methods for details on use.
921 # and clear_main_mod_cache() methods for details on use.
918
922
919 # This is the cache used for 'main' namespaces
923 # This is the cache used for 'main' namespaces
920 self._main_ns_cache = {}
924 self._main_ns_cache = {}
921 # And this is the single instance of FakeModule whose __dict__ we keep
925 # And this is the single instance of FakeModule whose __dict__ we keep
922 # copying and clearing for reuse on each %run
926 # copying and clearing for reuse on each %run
923 self._user_main_module = FakeModule()
927 self._user_main_module = FakeModule()
924
928
925 # A table holding all the namespaces IPython deals with, so that
929 # A table holding all the namespaces IPython deals with, so that
926 # introspection facilities can search easily.
930 # introspection facilities can search easily.
927 self.ns_table = {'user':user_ns,
931 self.ns_table = {'user':user_ns,
928 'user_global':user_global_ns,
932 'user_global':user_global_ns,
929 'internal':self.internal_ns,
933 'internal':self.internal_ns,
930 'builtin':__builtin__.__dict__
934 'builtin':__builtin__.__dict__
931 }
935 }
932
936
933 # Similarly, track all namespaces where references can be held and that
937 # Similarly, track all namespaces where references can be held and that
934 # we can safely clear (so it can NOT include builtin). This one can be
938 # we can safely clear (so it can NOT include builtin). This one can be
935 # a simple list.
939 # a simple list.
936 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
940 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
937 self.internal_ns, self._main_ns_cache ]
941 self.internal_ns, self._main_ns_cache ]
938
942
939 def init_sys_modules(self):
943 def init_sys_modules(self):
940 # We need to insert into sys.modules something that looks like a
944 # We need to insert into sys.modules something that looks like a
941 # module but which accesses the IPython namespace, for shelve and
945 # module but which accesses the IPython namespace, for shelve and
942 # pickle to work interactively. Normally they rely on getting
946 # pickle to work interactively. Normally they rely on getting
943 # everything out of __main__, but for embedding purposes each IPython
947 # everything out of __main__, but for embedding purposes each IPython
944 # instance has its own private namespace, so we can't go shoving
948 # instance has its own private namespace, so we can't go shoving
945 # everything into __main__.
949 # everything into __main__.
946
950
947 # note, however, that we should only do this for non-embedded
951 # note, however, that we should only do this for non-embedded
948 # ipythons, which really mimic the __main__.__dict__ with their own
952 # ipythons, which really mimic the __main__.__dict__ with their own
949 # namespace. Embedded instances, on the other hand, should not do
953 # namespace. Embedded instances, on the other hand, should not do
950 # this because they need to manage the user local/global namespaces
954 # this because they need to manage the user local/global namespaces
951 # only, but they live within a 'normal' __main__ (meaning, they
955 # only, but they live within a 'normal' __main__ (meaning, they
952 # shouldn't overtake the execution environment of the script they're
956 # shouldn't overtake the execution environment of the script they're
953 # embedded in).
957 # embedded in).
954
958
955 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
959 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
956
960
957 try:
961 try:
958 main_name = self.user_ns['__name__']
962 main_name = self.user_ns['__name__']
959 except KeyError:
963 except KeyError:
960 raise KeyError('user_ns dictionary MUST have a "__name__" key')
964 raise KeyError('user_ns dictionary MUST have a "__name__" key')
961 else:
965 else:
962 sys.modules[main_name] = FakeModule(self.user_ns)
966 sys.modules[main_name] = FakeModule(self.user_ns)
963
967
964 def init_user_ns(self):
968 def init_user_ns(self):
965 """Initialize all user-visible namespaces to their minimum defaults.
969 """Initialize all user-visible namespaces to their minimum defaults.
966
970
967 Certain history lists are also initialized here, as they effectively
971 Certain history lists are also initialized here, as they effectively
968 act as user namespaces.
972 act as user namespaces.
969
973
970 Notes
974 Notes
971 -----
975 -----
972 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
973 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
974 therm.
978 therm.
975 """
979 """
976 # This function works in two parts: first we put a few things in
980 # This function works in two parts: first we put a few things in
977 # user_ns, and we sync that contents into user_config_ns so that these
981 # user_ns, and we sync that contents into user_config_ns so that these
978 # initial variables aren't shown by %who. After the sync, we add the
982 # initial variables aren't shown by %who. After the sync, we add the
979 # rest of what we *do* want the user to see with %who even on a new
983 # rest of what we *do* want the user to see with %who even on a new
980 # session (probably nothing, so theye really only see their own stuff)
984 # session (probably nothing, so theye really only see their own stuff)
981
985
982 # The user dict must *always* have a __builtin__ reference to the
986 # The user dict must *always* have a __builtin__ reference to the
983 # Python standard __builtin__ namespace, which must be imported.
987 # Python standard __builtin__ namespace, which must be imported.
984 # This is so that certain operations in prompt evaluation can be
988 # This is so that certain operations in prompt evaluation can be
985 # reliably executed with builtins. Note that we can NOT use
989 # reliably executed with builtins. Note that we can NOT use
986 # __builtins__ (note the 's'), because that can either be a dict or a
990 # __builtins__ (note the 's'), because that can either be a dict or a
987 # module, and can even mutate at runtime, depending on the context
991 # module, and can even mutate at runtime, depending on the context
988 # (Python makes no guarantees on it). In contrast, __builtin__ is
992 # (Python makes no guarantees on it). In contrast, __builtin__ is
989 # always a module object, though it must be explicitly imported.
993 # always a module object, though it must be explicitly imported.
990
994
991 # For more details:
995 # For more details:
992 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
996 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
993 ns = dict(__builtin__ = __builtin__)
997 ns = dict(__builtin__ = __builtin__)
994
998
995 # Put 'help' in the user namespace
999 # Put 'help' in the user namespace
996 try:
1000 try:
997 from site import _Helper
1001 from site import _Helper
998 ns['help'] = _Helper()
1002 ns['help'] = _Helper()
999 except ImportError:
1003 except ImportError:
1000 warn('help() not available - check site.py')
1004 warn('help() not available - check site.py')
1001
1005
1002 # make global variables for user access to the histories
1006 # make global variables for user access to the histories
1003 ns['_ih'] = self.input_hist
1007 ns['_ih'] = self.input_hist
1004 ns['_oh'] = self.output_hist
1008 ns['_oh'] = self.output_hist
1005 ns['_dh'] = self.dir_hist
1009 ns['_dh'] = self.dir_hist
1006
1010
1007 ns['_sh'] = shadowns
1011 ns['_sh'] = shadowns
1008
1012
1009 # user aliases to input and output histories. These shouldn't show up
1013 # user aliases to input and output histories. These shouldn't show up
1010 # in %who, as they can have very large reprs.
1014 # in %who, as they can have very large reprs.
1011 ns['In'] = self.input_hist
1015 ns['In'] = self.input_hist
1012 ns['Out'] = self.output_hist
1016 ns['Out'] = self.output_hist
1013
1017
1014 # Store myself as the public api!!!
1018 # Store myself as the public api!!!
1015 ns['get_ipython'] = self.get_ipython
1019 ns['get_ipython'] = self.get_ipython
1016
1020
1017 # Sync what we've added so far to user_config_ns so these aren't seen
1021 # Sync what we've added so far to user_config_ns so these aren't seen
1018 # by %who
1022 # by %who
1019 self.user_config_ns.update(ns)
1023 self.user_config_ns.update(ns)
1020
1024
1021 # Anything put into ns now would show up in %who. Think twice before
1025 # Anything put into ns now would show up in %who. Think twice before
1022 # putting anything here, as we really want %who to show the user their
1026 # putting anything here, as we really want %who to show the user their
1023 # stuff, not our variables.
1027 # stuff, not our variables.
1024
1028
1025 # Finally, update the real user's namespace
1029 # Finally, update the real user's namespace
1026 self.user_ns.update(ns)
1030 self.user_ns.update(ns)
1027
1031
1028
1032
1029 def reset(self):
1033 def reset(self):
1030 """Clear all internal namespaces.
1034 """Clear all internal namespaces.
1031
1035
1032 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
1033 fully all namespaces, as well as all input/output lists.
1037 fully all namespaces, as well as all input/output lists.
1034 """
1038 """
1035 for ns in self.ns_refs_table:
1039 for ns in self.ns_refs_table:
1036 ns.clear()
1040 ns.clear()
1037
1041
1038 self.alias_manager.clear_aliases()
1042 self.alias_manager.clear_aliases()
1039
1043
1040 # Clear input and output histories
1044 # Clear input and output histories
1041 self.input_hist[:] = []
1045 self.input_hist[:] = []
1042 self.input_hist_raw[:] = []
1046 self.input_hist_raw[:] = []
1043 self.output_hist.clear()
1047 self.output_hist.clear()
1044
1048
1045 # Restore the user namespaces to minimal usability
1049 # Restore the user namespaces to minimal usability
1046 self.init_user_ns()
1050 self.init_user_ns()
1047
1051
1048 # Restore the default and user aliases
1052 # Restore the default and user aliases
1049 self.alias_manager.init_aliases()
1053 self.alias_manager.init_aliases()
1050
1054
1051 def push(self, variables, interactive=True):
1055 def push(self, variables, interactive=True):
1052 """Inject a group of variables into the IPython user namespace.
1056 """Inject a group of variables into the IPython user namespace.
1053
1057
1054 Parameters
1058 Parameters
1055 ----------
1059 ----------
1056 variables : dict, str or list/tuple of str
1060 variables : dict, str or list/tuple of str
1057 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,
1058 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
1059 have variable names separated by spaces. A list/tuple of str
1063 have variable names separated by spaces. A list/tuple of str
1060 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
1061 names are give (list/tuple/str) then the variable values looked
1065 names are give (list/tuple/str) then the variable values looked
1062 up in the callers frame.
1066 up in the callers frame.
1063 interactive : bool
1067 interactive : bool
1064 If True (default), the variables will be listed with the ``who``
1068 If True (default), the variables will be listed with the ``who``
1065 magic.
1069 magic.
1066 """
1070 """
1067 vdict = None
1071 vdict = None
1068
1072
1069 # 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.
1070 if isinstance(variables, dict):
1074 if isinstance(variables, dict):
1071 vdict = variables
1075 vdict = variables
1072 elif isinstance(variables, (basestring, list, tuple)):
1076 elif isinstance(variables, (basestring, list, tuple)):
1073 if isinstance(variables, basestring):
1077 if isinstance(variables, basestring):
1074 vlist = variables.split()
1078 vlist = variables.split()
1075 else:
1079 else:
1076 vlist = variables
1080 vlist = variables
1077 vdict = {}
1081 vdict = {}
1078 cf = sys._getframe(1)
1082 cf = sys._getframe(1)
1079 for name in vlist:
1083 for name in vlist:
1080 try:
1084 try:
1081 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1085 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1082 except:
1086 except:
1083 print ('Could not get variable %s from %s' %
1087 print ('Could not get variable %s from %s' %
1084 (name,cf.f_code.co_name))
1088 (name,cf.f_code.co_name))
1085 else:
1089 else:
1086 raise ValueError('variables must be a dict/str/list/tuple')
1090 raise ValueError('variables must be a dict/str/list/tuple')
1087
1091
1088 # Propagate variables to user namespace
1092 # Propagate variables to user namespace
1089 self.user_ns.update(vdict)
1093 self.user_ns.update(vdict)
1090
1094
1091 # And configure interactive visibility
1095 # And configure interactive visibility
1092 config_ns = self.user_config_ns
1096 config_ns = self.user_config_ns
1093 if interactive:
1097 if interactive:
1094 for name, val in vdict.iteritems():
1098 for name, val in vdict.iteritems():
1095 config_ns.pop(name, None)
1099 config_ns.pop(name, None)
1096 else:
1100 else:
1097 for name,val in vdict.iteritems():
1101 for name,val in vdict.iteritems():
1098 config_ns[name] = val
1102 config_ns[name] = val
1099
1103
1100 #-------------------------------------------------------------------------
1104 #-------------------------------------------------------------------------
1101 # Things related to history management
1105 # Things related to history management
1102 #-------------------------------------------------------------------------
1106 #-------------------------------------------------------------------------
1103
1107
1104 def init_history(self):
1108 def init_history(self):
1105 # List of input with multi-line handling.
1109 # List of input with multi-line handling.
1106 self.input_hist = InputList()
1110 self.input_hist = InputList()
1107 # This one will hold the 'raw' input history, without any
1111 # This one will hold the 'raw' input history, without any
1108 # 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
1109 # it was exactly typed in by the user, with %hist -r.
1113 # it was exactly typed in by the user, with %hist -r.
1110 self.input_hist_raw = InputList()
1114 self.input_hist_raw = InputList()
1111
1115
1112 # list of visited directories
1116 # list of visited directories
1113 try:
1117 try:
1114 self.dir_hist = [os.getcwd()]
1118 self.dir_hist = [os.getcwd()]
1115 except OSError:
1119 except OSError:
1116 self.dir_hist = []
1120 self.dir_hist = []
1117
1121
1118 # dict of output history
1122 # dict of output history
1119 self.output_hist = {}
1123 self.output_hist = {}
1120
1124
1121 # Now the history file
1125 # Now the history file
1122 if self.profile:
1126 if self.profile:
1123 histfname = 'history-%s' % self.profile
1127 histfname = 'history-%s' % self.profile
1124 else:
1128 else:
1125 histfname = 'history'
1129 histfname = 'history'
1126 self.histfile = os.path.join(self.ipython_dir, histfname)
1130 self.histfile = os.path.join(self.ipython_dir, histfname)
1127
1131
1128 # Fill the history zero entry, user counter starts at 1
1132 # Fill the history zero entry, user counter starts at 1
1129 self.input_hist.append('\n')
1133 self.input_hist.append('\n')
1130 self.input_hist_raw.append('\n')
1134 self.input_hist_raw.append('\n')
1131
1135
1132 def init_shadow_hist(self):
1136 def init_shadow_hist(self):
1133 try:
1137 try:
1134 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1138 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1135 except exceptions.UnicodeDecodeError:
1139 except exceptions.UnicodeDecodeError:
1136 print "Your ipython_dir can't be decoded to unicode!"
1140 print "Your ipython_dir can't be decoded to unicode!"
1137 print "Please set HOME environment variable to something that"
1141 print "Please set HOME environment variable to something that"
1138 print r"only has ASCII characters, e.g. c:\home"
1142 print r"only has ASCII characters, e.g. c:\home"
1139 print "Now it is", self.ipython_dir
1143 print "Now it is", self.ipython_dir
1140 sys.exit()
1144 sys.exit()
1141 self.shadowhist = ipcorehist.ShadowHist(self.db)
1145 self.shadowhist = ipcorehist.ShadowHist(self.db)
1142
1146
1143 def savehist(self):
1147 def savehist(self):
1144 """Save input history to a file (via readline library)."""
1148 """Save input history to a file (via readline library)."""
1145
1149
1146 try:
1150 try:
1147 self.readline.write_history_file(self.histfile)
1151 self.readline.write_history_file(self.histfile)
1148 except:
1152 except:
1149 print 'Unable to save IPython command history to file: ' + \
1153 print 'Unable to save IPython command history to file: ' + \
1150 `self.histfile`
1154 `self.histfile`
1151
1155
1152 def reloadhist(self):
1156 def reloadhist(self):
1153 """Reload the input history from disk file."""
1157 """Reload the input history from disk file."""
1154
1158
1155 try:
1159 try:
1156 self.readline.clear_history()
1160 self.readline.clear_history()
1157 self.readline.read_history_file(self.shell.histfile)
1161 self.readline.read_history_file(self.shell.histfile)
1158 except AttributeError:
1162 except AttributeError:
1159 pass
1163 pass
1160
1164
1161 def history_saving_wrapper(self, func):
1165 def history_saving_wrapper(self, func):
1162 """ Wrap func for readline history saving
1166 """ Wrap func for readline history saving
1163
1167
1164 Convert func into callable that saves & restores
1168 Convert func into callable that saves & restores
1165 history around the call """
1169 history around the call """
1166
1170
1167 if not self.has_readline:
1171 if self.has_readline:
1172 from IPython.utils import rlineimpl as readline
1173 else:
1168 return func
1174 return func
1169
1175
1170 def wrapper():
1176 def wrapper():
1171 self.savehist()
1177 self.savehist()
1172 try:
1178 try:
1173 func()
1179 func()
1174 finally:
1180 finally:
1175 readline.read_history_file(self.histfile)
1181 readline.read_history_file(self.histfile)
1176 return wrapper
1182 return wrapper
1177
1183
1178 #-------------------------------------------------------------------------
1184 #-------------------------------------------------------------------------
1179 # Things related to exception handling and tracebacks (not debugging)
1185 # Things related to exception handling and tracebacks (not debugging)
1180 #-------------------------------------------------------------------------
1186 #-------------------------------------------------------------------------
1181
1187
1182 def init_traceback_handlers(self, custom_exceptions):
1188 def init_traceback_handlers(self, custom_exceptions):
1183 # Syntax error handler.
1189 # Syntax error handler.
1184 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1190 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1185
1191
1186 # The interactive one is initialized with an offset, meaning we always
1192 # The interactive one is initialized with an offset, meaning we always
1187 # 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
1188 # internal code. Valid modes: ['Plain','Context','Verbose']
1194 # internal code. Valid modes: ['Plain','Context','Verbose']
1189 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1195 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1190 color_scheme='NoColor',
1196 color_scheme='NoColor',
1191 tb_offset = 1)
1197 tb_offset = 1)
1192
1198
1193 # The instance will store a pointer to the system-wide exception hook,
1199 # The instance will store a pointer to the system-wide exception hook,
1194 # so that runtime code (such as magics) can access it. This is because
1200 # so that runtime code (such as magics) can access it. This is because
1195 # during the read-eval loop, it may get temporarily overwritten.
1201 # during the read-eval loop, it may get temporarily overwritten.
1196 self.sys_excepthook = sys.excepthook
1202 self.sys_excepthook = sys.excepthook
1197
1203
1198 # and add any custom exception handlers the user may have specified
1204 # and add any custom exception handlers the user may have specified
1199 self.set_custom_exc(*custom_exceptions)
1205 self.set_custom_exc(*custom_exceptions)
1200
1206
1207 # Set the exception mode
1208 self.InteractiveTB.set_mode(mode=self.xmode)
1209
1201 def set_custom_exc(self,exc_tuple,handler):
1210 def set_custom_exc(self,exc_tuple,handler):
1202 """set_custom_exc(exc_tuple,handler)
1211 """set_custom_exc(exc_tuple,handler)
1203
1212
1204 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
1205 exceptions in exc_tuple occur in the mainloop (specifically, in the
1214 exceptions in exc_tuple occur in the mainloop (specifically, in the
1206 runcode() method.
1215 runcode() method.
1207
1216
1208 Inputs:
1217 Inputs:
1209
1218
1210 - exc_tuple: a *tuple* of valid exceptions to call the defined
1219 - exc_tuple: a *tuple* of valid exceptions to call the defined
1211 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
1212 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
1213 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:
1214
1223
1215 exc_tuple == (MyCustomException,)
1224 exc_tuple == (MyCustomException,)
1216
1225
1217 - handler: this must be defined as a function with the following
1226 - handler: this must be defined as a function with the following
1218 basic interface: def my_handler(self,etype,value,tb).
1227 basic interface: def my_handler(self,etype,value,tb).
1219
1228
1220 This will be made into an instance method (via new.instancemethod)
1229 This will be made into an instance method (via new.instancemethod)
1221 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
1222 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
1223 internal basic one is used, which just prints basic info.
1232 internal basic one is used, which just prints basic info.
1224
1233
1225 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
1226 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
1227 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."""
1228
1237
1229 assert type(exc_tuple)==type(()) , \
1238 assert type(exc_tuple)==type(()) , \
1230 "The custom exceptions must be given AS A TUPLE."
1239 "The custom exceptions must be given AS A TUPLE."
1231
1240
1232 def dummy_handler(self,etype,value,tb):
1241 def dummy_handler(self,etype,value,tb):
1233 print '*** Simple custom exception handler ***'
1242 print '*** Simple custom exception handler ***'
1234 print 'Exception type :',etype
1243 print 'Exception type :',etype
1235 print 'Exception value:',value
1244 print 'Exception value:',value
1236 print 'Traceback :',tb
1245 print 'Traceback :',tb
1237 print 'Source code :','\n'.join(self.buffer)
1246 print 'Source code :','\n'.join(self.buffer)
1238
1247
1239 if handler is None: handler = dummy_handler
1248 if handler is None: handler = dummy_handler
1240
1249
1241 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1250 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1242 self.custom_exceptions = exc_tuple
1251 self.custom_exceptions = exc_tuple
1243
1252
1244 def excepthook(self, etype, value, tb):
1253 def excepthook(self, etype, value, tb):
1245 """One more defense for GUI apps that call sys.excepthook.
1254 """One more defense for GUI apps that call sys.excepthook.
1246
1255
1247 GUI frameworks like wxPython trap exceptions and call
1256 GUI frameworks like wxPython trap exceptions and call
1248 sys.excepthook themselves. I guess this is a feature that
1257 sys.excepthook themselves. I guess this is a feature that
1249 enables them to keep running after exceptions that would
1258 enables them to keep running after exceptions that would
1250 otherwise kill their mainloop. This is a bother for IPython
1259 otherwise kill their mainloop. This is a bother for IPython
1251 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:
1252 except: statement.
1261 except: statement.
1253
1262
1254 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1263 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1255 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
1256 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
1257 CrashHandler and replace it with this excepthook instead, which prints a
1266 CrashHandler and replace it with this excepthook instead, which prints a
1258 regular traceback using our InteractiveTB. In this fashion, apps which
1267 regular traceback using our InteractiveTB. In this fashion, apps which
1259 call sys.excepthook will generate a regular-looking exception from
1268 call sys.excepthook will generate a regular-looking exception from
1260 IPython, and the CrashHandler will only be triggered by real IPython
1269 IPython, and the CrashHandler will only be triggered by real IPython
1261 crashes.
1270 crashes.
1262
1271
1263 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
1264 to be true IPython errors.
1273 to be true IPython errors.
1265 """
1274 """
1266 self.showtraceback((etype,value,tb),tb_offset=0)
1275 self.showtraceback((etype,value,tb),tb_offset=0)
1267
1276
1268 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1277 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1269 exception_only=False):
1278 exception_only=False):
1270 """Display the exception that just occurred.
1279 """Display the exception that just occurred.
1271
1280
1272 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
1273 should be used throughout the code for presenting user tracebacks,
1282 should be used throughout the code for presenting user tracebacks,
1274 rather than directly invoking the InteractiveTB object.
1283 rather than directly invoking the InteractiveTB object.
1275
1284
1276 A specific showsyntaxerror() also exists, but this method can take
1285 A specific showsyntaxerror() also exists, but this method can take
1277 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
1278 SyntaxError exception, don't try to analyze the stack manually and
1287 SyntaxError exception, don't try to analyze the stack manually and
1279 simply call this method."""
1288 simply call this method."""
1280
1289
1281 try:
1290 try:
1282 if exc_tuple is None:
1291 if exc_tuple is None:
1283 etype, value, tb = sys.exc_info()
1292 etype, value, tb = sys.exc_info()
1284 else:
1293 else:
1285 etype, value, tb = exc_tuple
1294 etype, value, tb = exc_tuple
1286
1295
1287 if etype is None:
1296 if etype is None:
1288 if hasattr(sys, 'last_type'):
1297 if hasattr(sys, 'last_type'):
1289 etype, value, tb = sys.last_type, sys.last_value, \
1298 etype, value, tb = sys.last_type, sys.last_value, \
1290 sys.last_traceback
1299 sys.last_traceback
1291 else:
1300 else:
1292 self.write('No traceback available to show.\n')
1301 self.write('No traceback available to show.\n')
1293 return
1302 return
1294
1303
1295 if etype is SyntaxError:
1304 if etype is SyntaxError:
1296 # Though this won't be called by syntax errors in the input
1305 # Though this won't be called by syntax errors in the input
1297 # line, there may be SyntaxError cases whith imported code.
1306 # line, there may be SyntaxError cases whith imported code.
1298 self.showsyntaxerror(filename)
1307 self.showsyntaxerror(filename)
1299 elif etype is UsageError:
1308 elif etype is UsageError:
1300 print "UsageError:", value
1309 print "UsageError:", value
1301 else:
1310 else:
1302 # WARNING: these variables are somewhat deprecated and not
1311 # WARNING: these variables are somewhat deprecated and not
1303 # necessarily safe to use in a threaded environment, but tools
1312 # necessarily safe to use in a threaded environment, but tools
1304 # 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
1305 # 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.
1306 sys.last_type = etype
1315 sys.last_type = etype
1307 sys.last_value = value
1316 sys.last_value = value
1308 sys.last_traceback = tb
1317 sys.last_traceback = tb
1309
1318
1310 if etype in self.custom_exceptions:
1319 if etype in self.custom_exceptions:
1311 self.CustomTB(etype,value,tb)
1320 self.CustomTB(etype,value,tb)
1312 else:
1321 else:
1313 if exception_only:
1322 if exception_only:
1314 m = ('An exception has occurred, use %tb to see the '
1323 m = ('An exception has occurred, use %tb to see the '
1315 'full traceback.')
1324 'full traceback.')
1316 print m
1325 print m
1317 self.InteractiveTB.show_exception_only(etype, value)
1326 self.InteractiveTB.show_exception_only(etype, value)
1318 else:
1327 else:
1319 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1328 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1320 if self.InteractiveTB.call_pdb:
1329 if self.InteractiveTB.call_pdb:
1321 # pdb mucks up readline, fix it back
1330 # pdb mucks up readline, fix it back
1322 self.set_completer()
1331 self.set_completer()
1323
1332
1324 except KeyboardInterrupt:
1333 except KeyboardInterrupt:
1325 self.write("\nKeyboardInterrupt\n")
1334 self.write("\nKeyboardInterrupt\n")
1326
1335
1327
1336
1328 def showsyntaxerror(self, filename=None):
1337 def showsyntaxerror(self, filename=None):
1329 """Display the syntax error that just occurred.
1338 """Display the syntax error that just occurred.
1330
1339
1331 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.
1332
1341
1333 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
1334 of what was there before (because Python's parser always uses
1343 of what was there before (because Python's parser always uses
1335 "<string>" when reading from a string).
1344 "<string>" when reading from a string).
1336 """
1345 """
1337 etype, value, last_traceback = sys.exc_info()
1346 etype, value, last_traceback = sys.exc_info()
1338
1347
1339 # See note about these variables in showtraceback() above
1348 # See note about these variables in showtraceback() above
1340 sys.last_type = etype
1349 sys.last_type = etype
1341 sys.last_value = value
1350 sys.last_value = value
1342 sys.last_traceback = last_traceback
1351 sys.last_traceback = last_traceback
1343
1352
1344 if filename and etype is SyntaxError:
1353 if filename and etype is SyntaxError:
1345 # Work hard to stuff the correct filename in the exception
1354 # Work hard to stuff the correct filename in the exception
1346 try:
1355 try:
1347 msg, (dummy_filename, lineno, offset, line) = value
1356 msg, (dummy_filename, lineno, offset, line) = value
1348 except:
1357 except:
1349 # Not the format we expect; leave it alone
1358 # Not the format we expect; leave it alone
1350 pass
1359 pass
1351 else:
1360 else:
1352 # Stuff in the right filename
1361 # Stuff in the right filename
1353 try:
1362 try:
1354 # Assume SyntaxError is a class exception
1363 # Assume SyntaxError is a class exception
1355 value = SyntaxError(msg, (filename, lineno, offset, line))
1364 value = SyntaxError(msg, (filename, lineno, offset, line))
1356 except:
1365 except:
1357 # If that failed, assume SyntaxError is a string
1366 # If that failed, assume SyntaxError is a string
1358 value = msg, (filename, lineno, offset, line)
1367 value = msg, (filename, lineno, offset, line)
1359 self.SyntaxTB(etype,value,[])
1368 self.SyntaxTB(etype,value,[])
1360
1369
1361 def edit_syntax_error(self):
1370 def edit_syntax_error(self):
1362 """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.
1363
1372
1364 Loop until syntax error is fixed or user cancels.
1373 Loop until syntax error is fixed or user cancels.
1365 """
1374 """
1366
1375
1367 while self.SyntaxTB.last_syntax_error:
1376 while self.SyntaxTB.last_syntax_error:
1368 # copy and clear last_syntax_error
1377 # copy and clear last_syntax_error
1369 err = self.SyntaxTB.clear_err_state()
1378 err = self.SyntaxTB.clear_err_state()
1370 if not self._should_recompile(err):
1379 if not self._should_recompile(err):
1371 return
1380 return
1372 try:
1381 try:
1373 # may set last_syntax_error again if a SyntaxError is raised
1382 # may set last_syntax_error again if a SyntaxError is raised
1374 self.safe_execfile(err.filename,self.user_ns)
1383 self.safe_execfile(err.filename,self.user_ns)
1375 except:
1384 except:
1376 self.showtraceback()
1385 self.showtraceback()
1377 else:
1386 else:
1378 try:
1387 try:
1379 f = file(err.filename)
1388 f = file(err.filename)
1380 try:
1389 try:
1381 # This should be inside a display_trap block and I
1390 # This should be inside a display_trap block and I
1382 # think it is.
1391 # think it is.
1383 sys.displayhook(f.read())
1392 sys.displayhook(f.read())
1384 finally:
1393 finally:
1385 f.close()
1394 f.close()
1386 except:
1395 except:
1387 self.showtraceback()
1396 self.showtraceback()
1388
1397
1389 def _should_recompile(self,e):
1398 def _should_recompile(self,e):
1390 """Utility routine for edit_syntax_error"""
1399 """Utility routine for edit_syntax_error"""
1391
1400
1392 if e.filename in ('<ipython console>','<input>','<string>',
1401 if e.filename in ('<ipython console>','<input>','<string>',
1393 '<console>','<BackgroundJob compilation>',
1402 '<console>','<BackgroundJob compilation>',
1394 None):
1403 None):
1395
1404
1396 return False
1405 return False
1397 try:
1406 try:
1398 if (self.autoedit_syntax and
1407 if (self.autoedit_syntax and
1399 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? '
1400 '[Y/n] ','y')):
1409 '[Y/n] ','y')):
1401 return False
1410 return False
1402 except EOFError:
1411 except EOFError:
1403 return False
1412 return False
1404
1413
1405 def int0(x):
1414 def int0(x):
1406 try:
1415 try:
1407 return int(x)
1416 return int(x)
1408 except TypeError:
1417 except TypeError:
1409 return 0
1418 return 0
1410 # always pass integer line and offset values to editor hook
1419 # always pass integer line and offset values to editor hook
1411 try:
1420 try:
1412 self.hooks.fix_error_editor(e.filename,
1421 self.hooks.fix_error_editor(e.filename,
1413 int0(e.lineno),int0(e.offset),e.msg)
1422 int0(e.lineno),int0(e.offset),e.msg)
1414 except TryNext:
1423 except TryNext:
1415 warn('Could not open editor')
1424 warn('Could not open editor')
1416 return False
1425 return False
1417 return True
1426 return True
1418
1427
1419 #-------------------------------------------------------------------------
1428 #-------------------------------------------------------------------------
1420 # Things related to tab completion
1429 # Things related to tab completion
1421 #-------------------------------------------------------------------------
1430 #-------------------------------------------------------------------------
1422
1431
1423 def complete(self, text):
1432 def complete(self, text):
1424 """Return a sorted list of all possible completions on text.
1433 """Return a sorted list of all possible completions on text.
1425
1434
1426 Inputs:
1435 Inputs:
1427
1436
1428 - text: a string of text to be completed on.
1437 - text: a string of text to be completed on.
1429
1438
1430 This is a wrapper around the completion mechanism, similar to what
1439 This is a wrapper around the completion mechanism, similar to what
1431 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
1432 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
1433 environments (such as GUIs) for text completion.
1442 environments (such as GUIs) for text completion.
1434
1443
1435 Simple usage example:
1444 Simple usage example:
1436
1445
1437 In [7]: x = 'hello'
1446 In [7]: x = 'hello'
1438
1447
1439 In [8]: x
1448 In [8]: x
1440 Out[8]: 'hello'
1449 Out[8]: 'hello'
1441
1450
1442 In [9]: print x
1451 In [9]: print x
1443 hello
1452 hello
1444
1453
1445 In [10]: _ip.complete('x.l')
1454 In [10]: _ip.complete('x.l')
1446 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1455 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1447 """
1456 """
1448
1457
1449 # 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.
1450 with self.builtin_trap:
1459 with self.builtin_trap:
1451 complete = self.Completer.complete
1460 complete = self.Completer.complete
1452 state = 0
1461 state = 0
1453 # 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
1454 # completers can return duplicates. When we make 2.4 a requirement,
1463 # completers can return duplicates. When we make 2.4 a requirement,
1455 # start using sets instead, which are faster.
1464 # start using sets instead, which are faster.
1456 comps = {}
1465 comps = {}
1457 while True:
1466 while True:
1458 newcomp = complete(text,state,line_buffer=text)
1467 newcomp = complete(text,state,line_buffer=text)
1459 if newcomp is None:
1468 if newcomp is None:
1460 break
1469 break
1461 comps[newcomp] = 1
1470 comps[newcomp] = 1
1462 state += 1
1471 state += 1
1463 outcomps = comps.keys()
1472 outcomps = comps.keys()
1464 outcomps.sort()
1473 outcomps.sort()
1465 #print "T:",text,"OC:",outcomps # dbg
1474 #print "T:",text,"OC:",outcomps # dbg
1466 #print "vars:",self.user_ns.keys()
1475 #print "vars:",self.user_ns.keys()
1467 return outcomps
1476 return outcomps
1468
1477
1469 def set_custom_completer(self,completer,pos=0):
1478 def set_custom_completer(self,completer,pos=0):
1470 """Adds a new custom completer function.
1479 """Adds a new custom completer function.
1471
1480
1472 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
1473 list where you want the completer to be inserted."""
1482 list where you want the completer to be inserted."""
1474
1483
1475 newcomp = new.instancemethod(completer,self.Completer,
1484 newcomp = new.instancemethod(completer,self.Completer,
1476 self.Completer.__class__)
1485 self.Completer.__class__)
1477 self.Completer.matchers.insert(pos,newcomp)
1486 self.Completer.matchers.insert(pos,newcomp)
1478
1487
1479 def set_completer(self):
1488 def set_completer(self):
1480 """Reset readline's completer to be our own."""
1489 """Reset readline's completer to be our own."""
1481 self.readline.set_completer(self.Completer.complete)
1490 self.readline.set_completer(self.Completer.complete)
1482
1491
1483 def set_completer_frame(self, frame=None):
1492 def set_completer_frame(self, frame=None):
1484 """Set the frame of the completer."""
1493 """Set the frame of the completer."""
1485 if frame:
1494 if frame:
1486 self.Completer.namespace = frame.f_locals
1495 self.Completer.namespace = frame.f_locals
1487 self.Completer.global_namespace = frame.f_globals
1496 self.Completer.global_namespace = frame.f_globals
1488 else:
1497 else:
1489 self.Completer.namespace = self.user_ns
1498 self.Completer.namespace = self.user_ns
1490 self.Completer.global_namespace = self.user_global_ns
1499 self.Completer.global_namespace = self.user_global_ns
1491
1500
1492 #-------------------------------------------------------------------------
1501 #-------------------------------------------------------------------------
1493 # Things related to readline
1502 # Things related to readline
1494 #-------------------------------------------------------------------------
1503 #-------------------------------------------------------------------------
1495
1504
1496 def init_readline(self):
1505 def init_readline(self):
1497 """Command history completion/saving/reloading."""
1506 """Command history completion/saving/reloading."""
1498
1507
1499 if self.readline_use:
1508 if self.readline_use:
1500 import IPython.utils.rlineimpl as readline
1509 import IPython.utils.rlineimpl as readline
1501
1510
1502 self.rl_next_input = None
1511 self.rl_next_input = None
1503 self.rl_do_indent = False
1512 self.rl_do_indent = False
1504
1513
1505 if not self.readline_use or not readline.have_readline:
1514 if not self.readline_use or not readline.have_readline:
1506 self.has_readline = False
1515 self.has_readline = False
1507 self.readline = None
1516 self.readline = None
1508 # Set a number of methods that depend on readline to be no-op
1517 # Set a number of methods that depend on readline to be no-op
1509 self.savehist = no_op
1518 self.savehist = no_op
1510 self.reloadhist = no_op
1519 self.reloadhist = no_op
1511 self.set_completer = no_op
1520 self.set_completer = no_op
1512 self.set_custom_completer = no_op
1521 self.set_custom_completer = no_op
1513 self.set_completer_frame = no_op
1522 self.set_completer_frame = no_op
1514 warn('Readline services not available or not loaded.')
1523 warn('Readline services not available or not loaded.')
1515 else:
1524 else:
1516 self.has_readline = True
1525 self.has_readline = True
1517 self.readline = readline
1526 self.readline = readline
1518 sys.modules['readline'] = readline
1527 sys.modules['readline'] = readline
1519 import atexit
1528 import atexit
1520 from IPython.core.completer import IPCompleter
1529 from IPython.core.completer import IPCompleter
1521 self.Completer = IPCompleter(self,
1530 self.Completer = IPCompleter(self,
1522 self.user_ns,
1531 self.user_ns,
1523 self.user_global_ns,
1532 self.user_global_ns,
1524 self.readline_omit__names,
1533 self.readline_omit__names,
1525 self.alias_manager.alias_table)
1534 self.alias_manager.alias_table)
1526 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1535 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1527 self.strdispatchers['complete_command'] = sdisp
1536 self.strdispatchers['complete_command'] = sdisp
1528 self.Completer.custom_completers = sdisp
1537 self.Completer.custom_completers = sdisp
1529 # Platform-specific configuration
1538 # Platform-specific configuration
1530 if os.name == 'nt':
1539 if os.name == 'nt':
1531 self.readline_startup_hook = readline.set_pre_input_hook
1540 self.readline_startup_hook = readline.set_pre_input_hook
1532 else:
1541 else:
1533 self.readline_startup_hook = readline.set_startup_hook
1542 self.readline_startup_hook = readline.set_startup_hook
1534
1543
1535 # Load user's initrc file (readline config)
1544 # Load user's initrc file (readline config)
1536 # Or if libedit is used, load editrc.
1545 # Or if libedit is used, load editrc.
1537 inputrc_name = os.environ.get('INPUTRC')
1546 inputrc_name = os.environ.get('INPUTRC')
1538 if inputrc_name is None:
1547 if inputrc_name is None:
1539 home_dir = get_home_dir()
1548 home_dir = get_home_dir()
1540 if home_dir is not None:
1549 if home_dir is not None:
1541 inputrc_name = '.inputrc'
1550 inputrc_name = '.inputrc'
1542 if readline.uses_libedit:
1551 if readline.uses_libedit:
1543 inputrc_name = '.editrc'
1552 inputrc_name = '.editrc'
1544 inputrc_name = os.path.join(home_dir, inputrc_name)
1553 inputrc_name = os.path.join(home_dir, inputrc_name)
1545 if os.path.isfile(inputrc_name):
1554 if os.path.isfile(inputrc_name):
1546 try:
1555 try:
1547 readline.read_init_file(inputrc_name)
1556 readline.read_init_file(inputrc_name)
1548 except:
1557 except:
1549 warn('Problems reading readline initialization file <%s>'
1558 warn('Problems reading readline initialization file <%s>'
1550 % inputrc_name)
1559 % inputrc_name)
1551
1560
1552 # save this in sys so embedded copies can restore it properly
1561 # save this in sys so embedded copies can restore it properly
1553 sys.ipcompleter = self.Completer.complete
1562 sys.ipcompleter = self.Completer.complete
1554 self.set_completer()
1563 self.set_completer()
1555
1564
1556 # Configure readline according to user's prefs
1565 # Configure readline according to user's prefs
1557 # 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
1558 # is being used (as on Leopard) the readline config is
1567 # is being used (as on Leopard) the readline config is
1559 # not run as the syntax for libedit is different.
1568 # not run as the syntax for libedit is different.
1560 if not readline.uses_libedit:
1569 if not readline.uses_libedit:
1561 for rlcommand in self.readline_parse_and_bind:
1570 for rlcommand in self.readline_parse_and_bind:
1562 #print "loading rl:",rlcommand # dbg
1571 #print "loading rl:",rlcommand # dbg
1563 readline.parse_and_bind(rlcommand)
1572 readline.parse_and_bind(rlcommand)
1564
1573
1565 # Remove some chars from the delimiters list. If we encounter
1574 # Remove some chars from the delimiters list. If we encounter
1566 # unicode chars, discard them.
1575 # unicode chars, discard them.
1567 delims = readline.get_completer_delims().encode("ascii", "ignore")
1576 delims = readline.get_completer_delims().encode("ascii", "ignore")
1568 delims = delims.translate(string._idmap,
1577 delims = delims.translate(string._idmap,
1569 self.readline_remove_delims)
1578 self.readline_remove_delims)
1570 readline.set_completer_delims(delims)
1579 readline.set_completer_delims(delims)
1571 # otherwise we end up with a monster history after a while:
1580 # otherwise we end up with a monster history after a while:
1572 readline.set_history_length(1000)
1581 readline.set_history_length(1000)
1573 try:
1582 try:
1574 #print '*** Reading readline history' # dbg
1583 #print '*** Reading readline history' # dbg
1575 readline.read_history_file(self.histfile)
1584 readline.read_history_file(self.histfile)
1576 except IOError:
1585 except IOError:
1577 pass # It doesn't exist yet.
1586 pass # It doesn't exist yet.
1578
1587
1579 atexit.register(self.atexit_operations)
1588 atexit.register(self.atexit_operations)
1580 del atexit
1589 del atexit
1581
1590
1582 # Configure auto-indent for all platforms
1591 # Configure auto-indent for all platforms
1583 self.set_autoindent(self.autoindent)
1592 self.set_autoindent(self.autoindent)
1584
1593
1585 def set_next_input(self, s):
1594 def set_next_input(self, s):
1586 """ Sets the 'default' input string for the next command line.
1595 """ Sets the 'default' input string for the next command line.
1587
1596
1588 Requires readline.
1597 Requires readline.
1589
1598
1590 Example:
1599 Example:
1591
1600
1592 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1601 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1593 [D:\ipython]|2> Hello Word_ # cursor is here
1602 [D:\ipython]|2> Hello Word_ # cursor is here
1594 """
1603 """
1595
1604
1596 self.rl_next_input = s
1605 self.rl_next_input = s
1597
1606
1598 def pre_readline(self):
1607 def pre_readline(self):
1599 """readline hook to be used at the start of each line.
1608 """readline hook to be used at the start of each line.
1600
1609
1601 Currently it handles auto-indent only."""
1610 Currently it handles auto-indent only."""
1602
1611
1603 #debugx('self.indent_current_nsp','pre_readline:')
1612 #debugx('self.indent_current_nsp','pre_readline:')
1604
1613
1605 if self.rl_do_indent:
1614 if self.rl_do_indent:
1606 self.readline.insert_text(self._indent_current_str())
1615 self.readline.insert_text(self._indent_current_str())
1607 if self.rl_next_input is not None:
1616 if self.rl_next_input is not None:
1608 self.readline.insert_text(self.rl_next_input)
1617 self.readline.insert_text(self.rl_next_input)
1609 self.rl_next_input = None
1618 self.rl_next_input = None
1610
1619
1611 def _indent_current_str(self):
1620 def _indent_current_str(self):
1612 """return the current level of indentation as a string"""
1621 """return the current level of indentation as a string"""
1613 return self.indent_current_nsp * ' '
1622 return self.indent_current_nsp * ' '
1614
1623
1615 #-------------------------------------------------------------------------
1624 #-------------------------------------------------------------------------
1616 # Things related to magics
1625 # Things related to magics
1617 #-------------------------------------------------------------------------
1626 #-------------------------------------------------------------------------
1618
1627
1619 def init_magics(self):
1628 def init_magics(self):
1620 # 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
1621 # doesn't crash if colors option is invalid)
1630 # doesn't crash if colors option is invalid)
1622 self.magic_colors(self.colors)
1631 self.magic_colors(self.colors)
1623 # History was moved to a separate module
1632 # History was moved to a separate module
1624 from . import history
1633 from . import history
1625 history.init_ipython(self)
1634 history.init_ipython(self)
1626
1635
1627 def magic(self,arg_s):
1636 def magic(self,arg_s):
1628 """Call a magic function by name.
1637 """Call a magic function by name.
1629
1638
1630 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
1631 additional arguments to be passed to the magic.
1640 additional arguments to be passed to the magic.
1632
1641
1633 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
1634 prompt:
1643 prompt:
1635
1644
1636 In[1]: %name -opt foo bar
1645 In[1]: %name -opt foo bar
1637
1646
1638 To call a magic without arguments, simply use magic('name').
1647 To call a magic without arguments, simply use magic('name').
1639
1648
1640 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
1641 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
1642 compound statements.
1651 compound statements.
1643 """
1652 """
1644 args = arg_s.split(' ',1)
1653 args = arg_s.split(' ',1)
1645 magic_name = args[0]
1654 magic_name = args[0]
1646 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1655 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1647
1656
1648 try:
1657 try:
1649 magic_args = args[1]
1658 magic_args = args[1]
1650 except IndexError:
1659 except IndexError:
1651 magic_args = ''
1660 magic_args = ''
1652 fn = getattr(self,'magic_'+magic_name,None)
1661 fn = getattr(self,'magic_'+magic_name,None)
1653 if fn is None:
1662 if fn is None:
1654 error("Magic function `%s` not found." % magic_name)
1663 error("Magic function `%s` not found." % magic_name)
1655 else:
1664 else:
1656 magic_args = self.var_expand(magic_args,1)
1665 magic_args = self.var_expand(magic_args,1)
1657 with nested(self.builtin_trap,):
1666 with nested(self.builtin_trap,):
1658 result = fn(magic_args)
1667 result = fn(magic_args)
1659 return result
1668 return result
1660
1669
1661 def define_magic(self, magicname, func):
1670 def define_magic(self, magicname, func):
1662 """Expose own function as magic function for ipython
1671 """Expose own function as magic function for ipython
1663
1672
1664 def foo_impl(self,parameter_s=''):
1673 def foo_impl(self,parameter_s=''):
1665 'My very own magic!. (Use docstrings, IPython reads them).'
1674 'My very own magic!. (Use docstrings, IPython reads them).'
1666 print 'Magic function. Passed parameter is between < >:'
1675 print 'Magic function. Passed parameter is between < >:'
1667 print '<%s>' % parameter_s
1676 print '<%s>' % parameter_s
1668 print 'The self object is:',self
1677 print 'The self object is:',self
1669
1678
1670 self.define_magic('foo',foo_impl)
1679 self.define_magic('foo',foo_impl)
1671 """
1680 """
1672
1681
1673 import new
1682 import new
1674 im = new.instancemethod(func,self, self.__class__)
1683 im = new.instancemethod(func,self, self.__class__)
1675 old = getattr(self, "magic_" + magicname, None)
1684 old = getattr(self, "magic_" + magicname, None)
1676 setattr(self, "magic_" + magicname, im)
1685 setattr(self, "magic_" + magicname, im)
1677 return old
1686 return old
1678
1687
1679 #-------------------------------------------------------------------------
1688 #-------------------------------------------------------------------------
1680 # Things related to macros
1689 # Things related to macros
1681 #-------------------------------------------------------------------------
1690 #-------------------------------------------------------------------------
1682
1691
1683 def define_macro(self, name, themacro):
1692 def define_macro(self, name, themacro):
1684 """Define a new macro
1693 """Define a new macro
1685
1694
1686 Parameters
1695 Parameters
1687 ----------
1696 ----------
1688 name : str
1697 name : str
1689 The name of the macro.
1698 The name of the macro.
1690 themacro : str or Macro
1699 themacro : str or Macro
1691 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
1692 Macro object is created by passing the string to it.
1701 Macro object is created by passing the string to it.
1693 """
1702 """
1694
1703
1695 from IPython.core import macro
1704 from IPython.core import macro
1696
1705
1697 if isinstance(themacro, basestring):
1706 if isinstance(themacro, basestring):
1698 themacro = macro.Macro(themacro)
1707 themacro = macro.Macro(themacro)
1699 if not isinstance(themacro, macro.Macro):
1708 if not isinstance(themacro, macro.Macro):
1700 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.')
1701 self.user_ns[name] = themacro
1710 self.user_ns[name] = themacro
1702
1711
1703 #-------------------------------------------------------------------------
1712 #-------------------------------------------------------------------------
1704 # Things related to the running of system commands
1713 # Things related to the running of system commands
1705 #-------------------------------------------------------------------------
1714 #-------------------------------------------------------------------------
1706
1715
1707 def system(self, cmd):
1716 def system(self, cmd):
1708 """Make a system call, using IPython."""
1717 """Make a system call, using IPython."""
1709 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1718 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1710
1719
1711 #-------------------------------------------------------------------------
1720 #-------------------------------------------------------------------------
1712 # Things related to aliases
1721 # Things related to aliases
1713 #-------------------------------------------------------------------------
1722 #-------------------------------------------------------------------------
1714
1723
1715 def init_alias(self):
1724 def init_alias(self):
1716 self.alias_manager = AliasManager(self, config=self.config)
1725 self.alias_manager = AliasManager(self, config=self.config)
1717 self.ns_table['alias'] = self.alias_manager.alias_table,
1726 self.ns_table['alias'] = self.alias_manager.alias_table,
1718
1727
1719 #-------------------------------------------------------------------------
1728 #-------------------------------------------------------------------------
1720 # Things related to the running of code
1729 # Things related to the running of code
1721 #-------------------------------------------------------------------------
1730 #-------------------------------------------------------------------------
1722
1731
1723 def ex(self, cmd):
1732 def ex(self, cmd):
1724 """Execute a normal python statement in user namespace."""
1733 """Execute a normal python statement in user namespace."""
1725 with nested(self.builtin_trap,):
1734 with nested(self.builtin_trap,):
1726 exec cmd in self.user_global_ns, self.user_ns
1735 exec cmd in self.user_global_ns, self.user_ns
1727
1736
1728 def ev(self, expr):
1737 def ev(self, expr):
1729 """Evaluate python expression expr in user namespace.
1738 """Evaluate python expression expr in user namespace.
1730
1739
1731 Returns the result of evaluation
1740 Returns the result of evaluation
1732 """
1741 """
1733 with nested(self.builtin_trap,):
1742 with nested(self.builtin_trap,):
1734 return eval(expr, self.user_global_ns, self.user_ns)
1743 return eval(expr, self.user_global_ns, self.user_ns)
1735
1744
1736 def mainloop(self, display_banner=None):
1745 def mainloop(self, display_banner=None):
1737 """Start the mainloop.
1746 """Start the mainloop.
1738
1747
1739 If an optional banner argument is given, it will override the
1748 If an optional banner argument is given, it will override the
1740 internally created default banner.
1749 internally created default banner.
1741 """
1750 """
1742
1751
1743 with nested(self.builtin_trap, self.display_trap):
1752 with nested(self.builtin_trap, self.display_trap):
1744
1753
1745 # 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
1746 # ensure that it's in sync
1755 # ensure that it's in sync
1747 if len(self.input_hist) != len (self.input_hist_raw):
1756 if len(self.input_hist) != len (self.input_hist_raw):
1748 self.input_hist_raw = InputList(self.input_hist)
1757 self.input_hist_raw = InputList(self.input_hist)
1749
1758
1750 while 1:
1759 while 1:
1751 try:
1760 try:
1752 self.interact(display_banner=display_banner)
1761 self.interact(display_banner=display_banner)
1753 #self.interact_with_readline()
1762 #self.interact_with_readline()
1754 # XXX for testing of a readline-decoupled repl loop, call
1763 # XXX for testing of a readline-decoupled repl loop, call
1755 # interact_with_readline above
1764 # interact_with_readline above
1756 break
1765 break
1757 except KeyboardInterrupt:
1766 except KeyboardInterrupt:
1758 # this should not be necessary, but KeyboardInterrupt
1767 # this should not be necessary, but KeyboardInterrupt
1759 # handling seems rather unpredictable...
1768 # handling seems rather unpredictable...
1760 self.write("\nKeyboardInterrupt in interact()\n")
1769 self.write("\nKeyboardInterrupt in interact()\n")
1761
1770
1762 def interact_prompt(self):
1771 def interact_prompt(self):
1763 """ Print the prompt (in read-eval-print loop)
1772 """ Print the prompt (in read-eval-print loop)
1764
1773
1765 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
1766 used in standard IPython flow.
1775 used in standard IPython flow.
1767 """
1776 """
1768 if self.more:
1777 if self.more:
1769 try:
1778 try:
1770 prompt = self.hooks.generate_prompt(True)
1779 prompt = self.hooks.generate_prompt(True)
1771 except:
1780 except:
1772 self.showtraceback()
1781 self.showtraceback()
1773 if self.autoindent:
1782 if self.autoindent:
1774 self.rl_do_indent = True
1783 self.rl_do_indent = True
1775
1784
1776 else:
1785 else:
1777 try:
1786 try:
1778 prompt = self.hooks.generate_prompt(False)
1787 prompt = self.hooks.generate_prompt(False)
1779 except:
1788 except:
1780 self.showtraceback()
1789 self.showtraceback()
1781 self.write(prompt)
1790 self.write(prompt)
1782
1791
1783 def interact_handle_input(self,line):
1792 def interact_handle_input(self,line):
1784 """ Handle the input line (in read-eval-print loop)
1793 """ Handle the input line (in read-eval-print loop)
1785
1794
1786 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
1787 used in standard IPython flow.
1796 used in standard IPython flow.
1788 """
1797 """
1789 if line.lstrip() == line:
1798 if line.lstrip() == line:
1790 self.shadowhist.add(line.strip())
1799 self.shadowhist.add(line.strip())
1791 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1800 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1792
1801
1793 if line.strip():
1802 if line.strip():
1794 if self.more:
1803 if self.more:
1795 self.input_hist_raw[-1] += '%s\n' % line
1804 self.input_hist_raw[-1] += '%s\n' % line
1796 else:
1805 else:
1797 self.input_hist_raw.append('%s\n' % line)
1806 self.input_hist_raw.append('%s\n' % line)
1798
1807
1799
1808
1800 self.more = self.push_line(lineout)
1809 self.more = self.push_line(lineout)
1801 if (self.SyntaxTB.last_syntax_error and
1810 if (self.SyntaxTB.last_syntax_error and
1802 self.autoedit_syntax):
1811 self.autoedit_syntax):
1803 self.edit_syntax_error()
1812 self.edit_syntax_error()
1804
1813
1805 def interact_with_readline(self):
1814 def interact_with_readline(self):
1806 """ Demo of using interact_handle_input, interact_prompt
1815 """ Demo of using interact_handle_input, interact_prompt
1807
1816
1808 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),
1809 it should work like this.
1818 it should work like this.
1810 """
1819 """
1811 self.readline_startup_hook(self.pre_readline)
1820 self.readline_startup_hook(self.pre_readline)
1812 while not self.exit_now:
1821 while not self.exit_now:
1813 self.interact_prompt()
1822 self.interact_prompt()
1814 if self.more:
1823 if self.more:
1815 self.rl_do_indent = True
1824 self.rl_do_indent = True
1816 else:
1825 else:
1817 self.rl_do_indent = False
1826 self.rl_do_indent = False
1818 line = raw_input_original().decode(self.stdin_encoding)
1827 line = raw_input_original().decode(self.stdin_encoding)
1819 self.interact_handle_input(line)
1828 self.interact_handle_input(line)
1820
1829
1821 def interact(self, display_banner=None):
1830 def interact(self, display_banner=None):
1822 """Closely emulate the interactive Python console."""
1831 """Closely emulate the interactive Python console."""
1823
1832
1824 # batch run -> do not interact
1833 # batch run -> do not interact
1825 if self.exit_now:
1834 if self.exit_now:
1826 return
1835 return
1827
1836
1828 if display_banner is None:
1837 if display_banner is None:
1829 display_banner = self.display_banner
1838 display_banner = self.display_banner
1830 if display_banner:
1839 if display_banner:
1831 self.show_banner()
1840 self.show_banner()
1832
1841
1833 more = 0
1842 more = 0
1834
1843
1835 # Mark activity in the builtins
1844 # Mark activity in the builtins
1836 __builtin__.__dict__['__IPYTHON__active'] += 1
1845 __builtin__.__dict__['__IPYTHON__active'] += 1
1837
1846
1838 if self.has_readline:
1847 if self.has_readline:
1839 self.readline_startup_hook(self.pre_readline)
1848 self.readline_startup_hook(self.pre_readline)
1840 # 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
1841 # ask_exit callback.
1850 # ask_exit callback.
1842
1851
1843 while not self.exit_now:
1852 while not self.exit_now:
1844 self.hooks.pre_prompt_hook()
1853 self.hooks.pre_prompt_hook()
1845 if more:
1854 if more:
1846 try:
1855 try:
1847 prompt = self.hooks.generate_prompt(True)
1856 prompt = self.hooks.generate_prompt(True)
1848 except:
1857 except:
1849 self.showtraceback()
1858 self.showtraceback()
1850 if self.autoindent:
1859 if self.autoindent:
1851 self.rl_do_indent = True
1860 self.rl_do_indent = True
1852
1861
1853 else:
1862 else:
1854 try:
1863 try:
1855 prompt = self.hooks.generate_prompt(False)
1864 prompt = self.hooks.generate_prompt(False)
1856 except:
1865 except:
1857 self.showtraceback()
1866 self.showtraceback()
1858 try:
1867 try:
1859 line = self.raw_input(prompt, more)
1868 line = self.raw_input(prompt, more)
1860 if self.exit_now:
1869 if self.exit_now:
1861 # quick exit on sys.std[in|out] close
1870 # quick exit on sys.std[in|out] close
1862 break
1871 break
1863 if self.autoindent:
1872 if self.autoindent:
1864 self.rl_do_indent = False
1873 self.rl_do_indent = False
1865
1874
1866 except KeyboardInterrupt:
1875 except KeyboardInterrupt:
1867 #double-guard against keyboardinterrupts during kbdint handling
1876 #double-guard against keyboardinterrupts during kbdint handling
1868 try:
1877 try:
1869 self.write('\nKeyboardInterrupt\n')
1878 self.write('\nKeyboardInterrupt\n')
1870 self.resetbuffer()
1879 self.resetbuffer()
1871 # keep cache in sync with the prompt counter:
1880 # keep cache in sync with the prompt counter:
1872 self.outputcache.prompt_count -= 1
1881 self.outputcache.prompt_count -= 1
1873
1882
1874 if self.autoindent:
1883 if self.autoindent:
1875 self.indent_current_nsp = 0
1884 self.indent_current_nsp = 0
1876 more = 0
1885 more = 0
1877 except KeyboardInterrupt:
1886 except KeyboardInterrupt:
1878 pass
1887 pass
1879 except EOFError:
1888 except EOFError:
1880 if self.autoindent:
1889 if self.autoindent:
1881 self.rl_do_indent = False
1890 self.rl_do_indent = False
1882 if self.has_readline:
1891 if self.has_readline:
1883 self.readline_startup_hook(None)
1892 self.readline_startup_hook(None)
1884 self.write('\n')
1893 self.write('\n')
1885 self.exit()
1894 self.exit()
1886 except bdb.BdbQuit:
1895 except bdb.BdbQuit:
1887 warn('The Python debugger has exited with a BdbQuit exception.\n'
1896 warn('The Python debugger has exited with a BdbQuit exception.\n'
1888 'Because of how pdb handles the stack, it is impossible\n'
1897 'Because of how pdb handles the stack, it is impossible\n'
1889 'for IPython to properly format this particular exception.\n'
1898 'for IPython to properly format this particular exception.\n'
1890 'IPython will resume normal operation.')
1899 'IPython will resume normal operation.')
1891 except:
1900 except:
1892 # exceptions here are VERY RARE, but they can be triggered
1901 # exceptions here are VERY RARE, but they can be triggered
1893 # asynchronously by signal handlers, for example.
1902 # asynchronously by signal handlers, for example.
1894 self.showtraceback()
1903 self.showtraceback()
1895 else:
1904 else:
1896 more = self.push_line(line)
1905 more = self.push_line(line)
1897 if (self.SyntaxTB.last_syntax_error and
1906 if (self.SyntaxTB.last_syntax_error and
1898 self.autoedit_syntax):
1907 self.autoedit_syntax):
1899 self.edit_syntax_error()
1908 self.edit_syntax_error()
1900
1909
1901 # We are off again...
1910 # We are off again...
1902 __builtin__.__dict__['__IPYTHON__active'] -= 1
1911 __builtin__.__dict__['__IPYTHON__active'] -= 1
1903
1912
1904 # Turn off the exit flag, so the mainloop can be restarted if desired
1913 # Turn off the exit flag, so the mainloop can be restarted if desired
1905 self.exit_now = False
1914 self.exit_now = False
1906
1915
1907 def safe_execfile(self, fname, *where, **kw):
1916 def safe_execfile(self, fname, *where, **kw):
1908 """A safe version of the builtin execfile().
1917 """A safe version of the builtin execfile().
1909
1918
1910 This version will never throw an exception, but instead print
1919 This version will never throw an exception, but instead print
1911 helpful error messages to the screen. This only works on pure
1920 helpful error messages to the screen. This only works on pure
1912 Python files with the .py extension.
1921 Python files with the .py extension.
1913
1922
1914 Parameters
1923 Parameters
1915 ----------
1924 ----------
1916 fname : string
1925 fname : string
1917 The name of the file to be executed.
1926 The name of the file to be executed.
1918 where : tuple
1927 where : tuple
1919 One or two namespaces, passed to execfile() as (globals,locals).
1928 One or two namespaces, passed to execfile() as (globals,locals).
1920 If only one is given, it is passed as both.
1929 If only one is given, it is passed as both.
1921 exit_ignore : bool (False)
1930 exit_ignore : bool (False)
1922 If True, then silence SystemExit for non-zero status (it is always
1931 If True, then silence SystemExit for non-zero status (it is always
1923 silenced for zero status, as it is so common).
1932 silenced for zero status, as it is so common).
1924 """
1933 """
1925 kw.setdefault('exit_ignore', False)
1934 kw.setdefault('exit_ignore', False)
1926
1935
1927 fname = os.path.abspath(os.path.expanduser(fname))
1936 fname = os.path.abspath(os.path.expanduser(fname))
1928
1937
1929 # Make sure we have a .py file
1938 # Make sure we have a .py file
1930 if not fname.endswith('.py'):
1939 if not fname.endswith('.py'):
1931 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)
1932
1941
1933 # Make sure we can open the file
1942 # Make sure we can open the file
1934 try:
1943 try:
1935 with open(fname) as thefile:
1944 with open(fname) as thefile:
1936 pass
1945 pass
1937 except:
1946 except:
1938 warn('Could not open file <%s> for safe execution.' % fname)
1947 warn('Could not open file <%s> for safe execution.' % fname)
1939 return
1948 return
1940
1949
1941 # 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
1942 # behavior of running a script from the system command line, where
1951 # behavior of running a script from the system command line, where
1943 # Python inserts the script's directory into sys.path
1952 # Python inserts the script's directory into sys.path
1944 dname = os.path.dirname(fname)
1953 dname = os.path.dirname(fname)
1945
1954
1946 with prepended_to_syspath(dname):
1955 with prepended_to_syspath(dname):
1947 try:
1956 try:
1948 execfile(fname,*where)
1957 execfile(fname,*where)
1949 except SystemExit, status:
1958 except SystemExit, status:
1950 # If the call was made with 0 or None exit status (sys.exit(0)
1959 # If the call was made with 0 or None exit status (sys.exit(0)
1951 # or sys.exit() ), don't bother showing a traceback, as both of
1960 # or sys.exit() ), don't bother showing a traceback, as both of
1952 # these are considered normal by the OS:
1961 # these are considered normal by the OS:
1953 # > python -c'import sys;sys.exit(0)'; echo $?
1962 # > python -c'import sys;sys.exit(0)'; echo $?
1954 # 0
1963 # 0
1955 # > python -c'import sys;sys.exit()'; echo $?
1964 # > python -c'import sys;sys.exit()'; echo $?
1956 # 0
1965 # 0
1957 # For other exit status, we show the exception unless
1966 # For other exit status, we show the exception unless
1958 # explicitly silenced, but only in short form.
1967 # explicitly silenced, but only in short form.
1959 if status.code not in (0, None) and not kw['exit_ignore']:
1968 if status.code not in (0, None) and not kw['exit_ignore']:
1960 self.showtraceback(exception_only=True)
1969 self.showtraceback(exception_only=True)
1961 except:
1970 except:
1962 self.showtraceback()
1971 self.showtraceback()
1963
1972
1964 def safe_execfile_ipy(self, fname):
1973 def safe_execfile_ipy(self, fname):
1965 """Like safe_execfile, but for .ipy files with IPython syntax.
1974 """Like safe_execfile, but for .ipy files with IPython syntax.
1966
1975
1967 Parameters
1976 Parameters
1968 ----------
1977 ----------
1969 fname : str
1978 fname : str
1970 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
1971 .ipy extension.
1980 .ipy extension.
1972 """
1981 """
1973 fname = os.path.abspath(os.path.expanduser(fname))
1982 fname = os.path.abspath(os.path.expanduser(fname))
1974
1983
1975 # Make sure we have a .py file
1984 # Make sure we have a .py file
1976 if not fname.endswith('.ipy'):
1985 if not fname.endswith('.ipy'):
1977 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)
1978
1987
1979 # Make sure we can open the file
1988 # Make sure we can open the file
1980 try:
1989 try:
1981 with open(fname) as thefile:
1990 with open(fname) as thefile:
1982 pass
1991 pass
1983 except:
1992 except:
1984 warn('Could not open file <%s> for safe execution.' % fname)
1993 warn('Could not open file <%s> for safe execution.' % fname)
1985 return
1994 return
1986
1995
1987 # 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
1988 # behavior of running a script from the system command line, where
1997 # behavior of running a script from the system command line, where
1989 # Python inserts the script's directory into sys.path
1998 # Python inserts the script's directory into sys.path
1990 dname = os.path.dirname(fname)
1999 dname = os.path.dirname(fname)
1991
2000
1992 with prepended_to_syspath(dname):
2001 with prepended_to_syspath(dname):
1993 try:
2002 try:
1994 with open(fname) as thefile:
2003 with open(fname) as thefile:
1995 script = thefile.read()
2004 script = thefile.read()
1996 # self.runlines currently captures all exceptions
2005 # self.runlines currently captures all exceptions
1997 # raise in user code. It would be nice if there were
2006 # raise in user code. It would be nice if there were
1998 # versions of runlines, execfile that did raise, so
2007 # versions of runlines, execfile that did raise, so
1999 # we could catch the errors.
2008 # we could catch the errors.
2000 self.runlines(script, clean=True)
2009 self.runlines(script, clean=True)
2001 except:
2010 except:
2002 self.showtraceback()
2011 self.showtraceback()
2003 warn('Unknown failure executing file: <%s>' % fname)
2012 warn('Unknown failure executing file: <%s>' % fname)
2004
2013
2005 def _is_secondary_block_start(self, s):
2014 def _is_secondary_block_start(self, s):
2006 if not s.endswith(':'):
2015 if not s.endswith(':'):
2007 return False
2016 return False
2008 if (s.startswith('elif') or
2017 if (s.startswith('elif') or
2009 s.startswith('else') or
2018 s.startswith('else') or
2010 s.startswith('except') or
2019 s.startswith('except') or
2011 s.startswith('finally')):
2020 s.startswith('finally')):
2012 return True
2021 return True
2013
2022
2014 def cleanup_ipy_script(self, script):
2023 def cleanup_ipy_script(self, script):
2015 """Make a script safe for self.runlines()
2024 """Make a script safe for self.runlines()
2016
2025
2017 Currently, IPython is lines based, with blocks being detected by
2026 Currently, IPython is lines based, with blocks being detected by
2018 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
2019 not have empty lines after blocks. This script adds those empty
2028 not have empty lines after blocks. This script adds those empty
2020 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
2021 IPython.
2030 IPython.
2022 """
2031 """
2023 res = []
2032 res = []
2024 lines = script.splitlines()
2033 lines = script.splitlines()
2025 level = 0
2034 level = 0
2026
2035
2027 for l in lines:
2036 for l in lines:
2028 lstripped = l.lstrip()
2037 lstripped = l.lstrip()
2029 stripped = l.strip()
2038 stripped = l.strip()
2030 if not stripped:
2039 if not stripped:
2031 continue
2040 continue
2032 newlevel = len(l) - len(lstripped)
2041 newlevel = len(l) - len(lstripped)
2033 if level > 0 and newlevel == 0 and \
2042 if level > 0 and newlevel == 0 and \
2034 not self._is_secondary_block_start(stripped):
2043 not self._is_secondary_block_start(stripped):
2035 # add empty line
2044 # add empty line
2036 res.append('')
2045 res.append('')
2037 res.append(l)
2046 res.append(l)
2038 level = newlevel
2047 level = newlevel
2039
2048
2040 return '\n'.join(res) + '\n'
2049 return '\n'.join(res) + '\n'
2041
2050
2042 def runlines(self, lines, clean=False):
2051 def runlines(self, lines, clean=False):
2043 """Run a string of one or more lines of source.
2052 """Run a string of one or more lines of source.
2044
2053
2045 This method is capable of running a string containing multiple source
2054 This method is capable of running a string containing multiple source
2046 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
2047 exposes IPython's processing machinery, the given strings can contain
2056 exposes IPython's processing machinery, the given strings can contain
2048 magic calls (%magic), special shell access (!cmd), etc.
2057 magic calls (%magic), special shell access (!cmd), etc.
2049 """
2058 """
2050
2059
2051 if isinstance(lines, (list, tuple)):
2060 if isinstance(lines, (list, tuple)):
2052 lines = '\n'.join(lines)
2061 lines = '\n'.join(lines)
2053
2062
2054 if clean:
2063 if clean:
2055 lines = self.cleanup_ipy_script(lines)
2064 lines = self.cleanup_ipy_script(lines)
2056
2065
2057 # 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
2058 # interactive IPython session (via a magic, for example).
2067 # interactive IPython session (via a magic, for example).
2059 self.resetbuffer()
2068 self.resetbuffer()
2060 lines = lines.splitlines()
2069 lines = lines.splitlines()
2061 more = 0
2070 more = 0
2062
2071
2063 with nested(self.builtin_trap, self.display_trap):
2072 with nested(self.builtin_trap, self.display_trap):
2064 for line in lines:
2073 for line in lines:
2065 # 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
2066 # 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
2067 # true)
2076 # true)
2068
2077
2069 if line or more:
2078 if line or more:
2070 # push to raw history, so hist line numbers stay in sync
2079 # push to raw history, so hist line numbers stay in sync
2071 self.input_hist_raw.append("# " + line + "\n")
2080 self.input_hist_raw.append("# " + line + "\n")
2072 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2081 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2073 more = self.push_line(prefiltered)
2082 more = self.push_line(prefiltered)
2074 # IPython's runsource returns None if there was an error
2083 # IPython's runsource returns None if there was an error
2075 # compiling the code. This allows us to stop processing right
2084 # compiling the code. This allows us to stop processing right
2076 # 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.
2077 if more is None:
2086 if more is None:
2078 break
2087 break
2079 else:
2088 else:
2080 self.input_hist_raw.append("\n")
2089 self.input_hist_raw.append("\n")
2081 # 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
2082 # actually does get executed
2091 # actually does get executed
2083 if more:
2092 if more:
2084 self.push_line('\n')
2093 self.push_line('\n')
2085
2094
2086 def runsource(self, source, filename='<input>', symbol='single'):
2095 def runsource(self, source, filename='<input>', symbol='single'):
2087 """Compile and run some source in the interpreter.
2096 """Compile and run some source in the interpreter.
2088
2097
2089 Arguments are as for compile_command().
2098 Arguments are as for compile_command().
2090
2099
2091 One several things can happen:
2100 One several things can happen:
2092
2101
2093 1) The input is incorrect; compile_command() raised an
2102 1) The input is incorrect; compile_command() raised an
2094 exception (SyntaxError or OverflowError). A syntax traceback
2103 exception (SyntaxError or OverflowError). A syntax traceback
2095 will be printed by calling the showsyntaxerror() method.
2104 will be printed by calling the showsyntaxerror() method.
2096
2105
2097 2) The input is incomplete, and more input is required;
2106 2) The input is incomplete, and more input is required;
2098 compile_command() returned None. Nothing happens.
2107 compile_command() returned None. Nothing happens.
2099
2108
2100 3) The input is complete; compile_command() returned a code
2109 3) The input is complete; compile_command() returned a code
2101 object. The code is executed by calling self.runcode() (which
2110 object. The code is executed by calling self.runcode() (which
2102 also handles run-time exceptions, except for SystemExit).
2111 also handles run-time exceptions, except for SystemExit).
2103
2112
2104 The return value is:
2113 The return value is:
2105
2114
2106 - True in case 2
2115 - True in case 2
2107
2116
2108 - False in the other cases, unless an exception is raised, where
2117 - False in the other cases, unless an exception is raised, where
2109 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
2110 know whether to continue feeding input or not.
2119 know whether to continue feeding input or not.
2111
2120
2112 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
2113 sys.ps2 to prompt the next line."""
2122 sys.ps2 to prompt the next line."""
2114
2123
2115 # 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
2116 # this allows execution of indented pasted code. It is tempting
2125 # this allows execution of indented pasted code. It is tempting
2117 # 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'
2118 # directly, but this fails for more complicated scenarios
2127 # directly, but this fails for more complicated scenarios
2119 source=source.encode(self.stdin_encoding)
2128 source=source.encode(self.stdin_encoding)
2120 if source[:1] in [' ', '\t']:
2129 if source[:1] in [' ', '\t']:
2121 source = 'if 1:\n%s' % source
2130 source = 'if 1:\n%s' % source
2122
2131
2123 try:
2132 try:
2124 code = self.compile(source,filename,symbol)
2133 code = self.compile(source,filename,symbol)
2125 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2134 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2126 # Case 1
2135 # Case 1
2127 self.showsyntaxerror(filename)
2136 self.showsyntaxerror(filename)
2128 return None
2137 return None
2129
2138
2130 if code is None:
2139 if code is None:
2131 # Case 2
2140 # Case 2
2132 return True
2141 return True
2133
2142
2134 # Case 3
2143 # Case 3
2135 # We store the code object so that threaded shells and
2144 # We store the code object so that threaded shells and
2136 # custom exception handlers can access all this info if needed.
2145 # custom exception handlers can access all this info if needed.
2137 # The source corresponding to this can be obtained from the
2146 # The source corresponding to this can be obtained from the
2138 # buffer attribute as '\n'.join(self.buffer).
2147 # buffer attribute as '\n'.join(self.buffer).
2139 self.code_to_run = code
2148 self.code_to_run = code
2140 # now actually execute the code object
2149 # now actually execute the code object
2141 if self.runcode(code) == 0:
2150 if self.runcode(code) == 0:
2142 return False
2151 return False
2143 else:
2152 else:
2144 return None
2153 return None
2145
2154
2146 def runcode(self,code_obj):
2155 def runcode(self,code_obj):
2147 """Execute a code object.
2156 """Execute a code object.
2148
2157
2149 When an exception occurs, self.showtraceback() is called to display a
2158 When an exception occurs, self.showtraceback() is called to display a
2150 traceback.
2159 traceback.
2151
2160
2152 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
2153 successfully:
2162 successfully:
2154
2163
2155 - 0: successful execution.
2164 - 0: successful execution.
2156 - 1: an error occurred.
2165 - 1: an error occurred.
2157 """
2166 """
2158
2167
2159 # 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
2160 # directly, so that the IPython crash handler doesn't get triggered
2169 # directly, so that the IPython crash handler doesn't get triggered
2161 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2170 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2162
2171
2163 # 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
2164 # code (such as magics) needs access to it.
2173 # code (such as magics) needs access to it.
2165 self.sys_excepthook = old_excepthook
2174 self.sys_excepthook = old_excepthook
2166 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
2167 try:
2176 try:
2168 try:
2177 try:
2169 self.hooks.pre_runcode_hook()
2178 self.hooks.pre_runcode_hook()
2170 exec code_obj in self.user_global_ns, self.user_ns
2179 exec code_obj in self.user_global_ns, self.user_ns
2171 finally:
2180 finally:
2172 # Reset our crash handler in place
2181 # Reset our crash handler in place
2173 sys.excepthook = old_excepthook
2182 sys.excepthook = old_excepthook
2174 except SystemExit:
2183 except SystemExit:
2175 self.resetbuffer()
2184 self.resetbuffer()
2176 self.showtraceback(exception_only=True)
2185 self.showtraceback(exception_only=True)
2177 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2186 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2178 except self.custom_exceptions:
2187 except self.custom_exceptions:
2179 etype,value,tb = sys.exc_info()
2188 etype,value,tb = sys.exc_info()
2180 self.CustomTB(etype,value,tb)
2189 self.CustomTB(etype,value,tb)
2181 except:
2190 except:
2182 self.showtraceback()
2191 self.showtraceback()
2183 else:
2192 else:
2184 outflag = 0
2193 outflag = 0
2185 if softspace(sys.stdout, 0):
2194 if softspace(sys.stdout, 0):
2186 print
2195 print
2187 # Flush out code object which has been run (and source)
2196 # Flush out code object which has been run (and source)
2188 self.code_to_run = None
2197 self.code_to_run = None
2189 return outflag
2198 return outflag
2190
2199
2191 def push_line(self, line):
2200 def push_line(self, line):
2192 """Push a line to the interpreter.
2201 """Push a line to the interpreter.
2193
2202
2194 The line should not have a trailing newline; it may have
2203 The line should not have a trailing newline; it may have
2195 internal newlines. The line is appended to a buffer and the
2204 internal newlines. The line is appended to a buffer and the
2196 interpreter's runsource() method is called with the
2205 interpreter's runsource() method is called with the
2197 concatenated contents of the buffer as source. If this
2206 concatenated contents of the buffer as source. If this
2198 indicates that the command was executed or invalid, the buffer
2207 indicates that the command was executed or invalid, the buffer
2199 is reset; otherwise, the command is incomplete, and the buffer
2208 is reset; otherwise, the command is incomplete, and the buffer
2200 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
2201 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
2202 with in some way (this is the same as runsource()).
2211 with in some way (this is the same as runsource()).
2203 """
2212 """
2204
2213
2205 # autoindent management should be done here, and not in the
2214 # autoindent management should be done here, and not in the
2206 # 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
2207 # 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
2208 # push).
2217 # push).
2209
2218
2210 #print 'push line: <%s>' % line # dbg
2219 #print 'push line: <%s>' % line # dbg
2211 for subline in line.splitlines():
2220 for subline in line.splitlines():
2212 self._autoindent_update(subline)
2221 self._autoindent_update(subline)
2213 self.buffer.append(line)
2222 self.buffer.append(line)
2214 more = self.runsource('\n'.join(self.buffer), self.filename)
2223 more = self.runsource('\n'.join(self.buffer), self.filename)
2215 if not more:
2224 if not more:
2216 self.resetbuffer()
2225 self.resetbuffer()
2217 return more
2226 return more
2218
2227
2219 def _autoindent_update(self,line):
2228 def _autoindent_update(self,line):
2220 """Keep track of the indent level."""
2229 """Keep track of the indent level."""
2221
2230
2222 #debugx('line')
2231 #debugx('line')
2223 #debugx('self.indent_current_nsp')
2232 #debugx('self.indent_current_nsp')
2224 if self.autoindent:
2233 if self.autoindent:
2225 if line:
2234 if line:
2226 inisp = num_ini_spaces(line)
2235 inisp = num_ini_spaces(line)
2227 if inisp < self.indent_current_nsp:
2236 if inisp < self.indent_current_nsp:
2228 self.indent_current_nsp = inisp
2237 self.indent_current_nsp = inisp
2229
2238
2230 if line[-1] == ':':
2239 if line[-1] == ':':
2231 self.indent_current_nsp += 4
2240 self.indent_current_nsp += 4
2232 elif dedent_re.match(line):
2241 elif dedent_re.match(line):
2233 self.indent_current_nsp -= 4
2242 self.indent_current_nsp -= 4
2234 else:
2243 else:
2235 self.indent_current_nsp = 0
2244 self.indent_current_nsp = 0
2236
2245
2237 def resetbuffer(self):
2246 def resetbuffer(self):
2238 """Reset the input buffer."""
2247 """Reset the input buffer."""
2239 self.buffer[:] = []
2248 self.buffer[:] = []
2240
2249
2241 def raw_input(self,prompt='',continue_prompt=False):
2250 def raw_input(self,prompt='',continue_prompt=False):
2242 """Write a prompt and read a line.
2251 """Write a prompt and read a line.
2243
2252
2244 The returned line does not include the trailing newline.
2253 The returned line does not include the trailing newline.
2245 When the user enters the EOF key sequence, EOFError is raised.
2254 When the user enters the EOF key sequence, EOFError is raised.
2246
2255
2247 Optional inputs:
2256 Optional inputs:
2248
2257
2249 - prompt(''): a string to be printed to prompt the user.
2258 - prompt(''): a string to be printed to prompt the user.
2250
2259
2251 - 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
2252 continuation in a sequence of inputs.
2261 continuation in a sequence of inputs.
2253 """
2262 """
2254 # 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))
2255
2264
2256 # 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.
2257 # We must ensure that our completer is back in place.
2266 # We must ensure that our completer is back in place.
2258
2267
2259 if self.has_readline:
2268 if self.has_readline:
2260 self.set_completer()
2269 self.set_completer()
2261
2270
2262 try:
2271 try:
2263 line = raw_input_original(prompt).decode(self.stdin_encoding)
2272 line = raw_input_original(prompt).decode(self.stdin_encoding)
2264 except ValueError:
2273 except ValueError:
2265 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()"
2266 " or sys.stdout.close()!\nExiting IPython!")
2275 " or sys.stdout.close()!\nExiting IPython!")
2267 self.ask_exit()
2276 self.ask_exit()
2268 return ""
2277 return ""
2269
2278
2270 # 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
2271 # 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
2272 # spaces, if the user's actual input started itself with whitespace.
2281 # spaces, if the user's actual input started itself with whitespace.
2273 #debugx('self.buffer[-1]')
2282 #debugx('self.buffer[-1]')
2274
2283
2275 if self.autoindent:
2284 if self.autoindent:
2276 if num_ini_spaces(line) > self.indent_current_nsp:
2285 if num_ini_spaces(line) > self.indent_current_nsp:
2277 line = line[self.indent_current_nsp:]
2286 line = line[self.indent_current_nsp:]
2278 self.indent_current_nsp = 0
2287 self.indent_current_nsp = 0
2279
2288
2280 # 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
2281 # it.
2290 # it.
2282 if line.strip():
2291 if line.strip():
2283 if continue_prompt:
2292 if continue_prompt:
2284 self.input_hist_raw[-1] += '%s\n' % line
2293 self.input_hist_raw[-1] += '%s\n' % line
2285 if self.has_readline and self.readline_use:
2294 if self.has_readline and self.readline_use:
2286 try:
2295 try:
2287 histlen = self.readline.get_current_history_length()
2296 histlen = self.readline.get_current_history_length()
2288 if histlen > 1:
2297 if histlen > 1:
2289 newhist = self.input_hist_raw[-1].rstrip()
2298 newhist = self.input_hist_raw[-1].rstrip()
2290 self.readline.remove_history_item(histlen-1)
2299 self.readline.remove_history_item(histlen-1)
2291 self.readline.replace_history_item(histlen-2,
2300 self.readline.replace_history_item(histlen-2,
2292 newhist.encode(self.stdin_encoding))
2301 newhist.encode(self.stdin_encoding))
2293 except AttributeError:
2302 except AttributeError:
2294 pass # re{move,place}_history_item are new in 2.4.
2303 pass # re{move,place}_history_item are new in 2.4.
2295 else:
2304 else:
2296 self.input_hist_raw.append('%s\n' % line)
2305 self.input_hist_raw.append('%s\n' % line)
2297 # only entries starting at first column go to shadow history
2306 # only entries starting at first column go to shadow history
2298 if line.lstrip() == line:
2307 if line.lstrip() == line:
2299 self.shadowhist.add(line.strip())
2308 self.shadowhist.add(line.strip())
2300 elif not continue_prompt:
2309 elif not continue_prompt:
2301 self.input_hist_raw.append('\n')
2310 self.input_hist_raw.append('\n')
2302 try:
2311 try:
2303 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2312 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2304 except:
2313 except:
2305 # blanket except, in case a user-defined prefilter crashes, so it
2314 # blanket except, in case a user-defined prefilter crashes, so it
2306 # can't take all of ipython with it.
2315 # can't take all of ipython with it.
2307 self.showtraceback()
2316 self.showtraceback()
2308 return ''
2317 return ''
2309 else:
2318 else:
2310 return lineout
2319 return lineout
2311
2320
2312 #-------------------------------------------------------------------------
2321 #-------------------------------------------------------------------------
2313 # Working with components
2322 # Working with components
2314 #-------------------------------------------------------------------------
2323 #-------------------------------------------------------------------------
2315
2324
2316 def get_component(self, name=None, klass=None):
2325 def get_component(self, name=None, klass=None):
2317 """Fetch a component by name and klass in my tree."""
2326 """Fetch a component by name and klass in my tree."""
2318 c = Component.get_instances(root=self, name=name, klass=klass)
2327 c = Component.get_instances(root=self, name=name, klass=klass)
2319 if len(c) == 0:
2328 if len(c) == 0:
2320 return None
2329 return None
2321 if len(c) == 1:
2330 if len(c) == 1:
2322 return c[0]
2331 return c[0]
2323 else:
2332 else:
2324 return c
2333 return c
2325
2334
2326 #-------------------------------------------------------------------------
2335 #-------------------------------------------------------------------------
2327 # IPython extensions
2336 # IPython extensions
2328 #-------------------------------------------------------------------------
2337 #-------------------------------------------------------------------------
2329
2338
2330 def load_extension(self, module_str):
2339 def load_extension(self, module_str):
2331 """Load an IPython extension by its module name.
2340 """Load an IPython extension by its module name.
2332
2341
2333 An IPython extension is an importable Python module that has
2342 An IPython extension is an importable Python module that has
2334 a function with the signature::
2343 a function with the signature::
2335
2344
2336 def load_ipython_extension(ipython):
2345 def load_ipython_extension(ipython):
2337 # Do things with ipython
2346 # Do things with ipython
2338
2347
2339 This function is called after your extension is imported and the
2348 This function is called after your extension is imported and the
2340 currently active :class:`InteractiveShell` instance is passed as
2349 currently active :class:`InteractiveShell` instance is passed as
2341 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
2342 that point, including defining new magic and aliases, adding new
2351 that point, including defining new magic and aliases, adding new
2343 components, etc.
2352 components, etc.
2344
2353
2345 The :func:`load_ipython_extension` will be called again is you
2354 The :func:`load_ipython_extension` will be called again is you
2346 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
2347 author to add code to manage that.
2356 author to add code to manage that.
2348
2357
2349 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
2350 they can be imported by Python's standard import mechanism. However,
2359 they can be imported by Python's standard import mechanism. However,
2351 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
2352 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2361 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2353 is added to ``sys.path`` automatically.
2362 is added to ``sys.path`` automatically.
2354 """
2363 """
2355 from IPython.utils.syspathcontext import prepended_to_syspath
2364 from IPython.utils.syspathcontext import prepended_to_syspath
2356
2365
2357 if module_str not in sys.modules:
2366 if module_str not in sys.modules:
2358 with prepended_to_syspath(self.ipython_extension_dir):
2367 with prepended_to_syspath(self.ipython_extension_dir):
2359 __import__(module_str)
2368 __import__(module_str)
2360 mod = sys.modules[module_str]
2369 mod = sys.modules[module_str]
2361 return self._call_load_ipython_extension(mod)
2370 return self._call_load_ipython_extension(mod)
2362
2371
2363 def unload_extension(self, module_str):
2372 def unload_extension(self, module_str):
2364 """Unload an IPython extension by its module name.
2373 """Unload an IPython extension by its module name.
2365
2374
2366 This function looks up the extension's name in ``sys.modules`` and
2375 This function looks up the extension's name in ``sys.modules`` and
2367 simply calls ``mod.unload_ipython_extension(self)``.
2376 simply calls ``mod.unload_ipython_extension(self)``.
2368 """
2377 """
2369 if module_str in sys.modules:
2378 if module_str in sys.modules:
2370 mod = sys.modules[module_str]
2379 mod = sys.modules[module_str]
2371 self._call_unload_ipython_extension(mod)
2380 self._call_unload_ipython_extension(mod)
2372
2381
2373 def reload_extension(self, module_str):
2382 def reload_extension(self, module_str):
2374 """Reload an IPython extension by calling reload.
2383 """Reload an IPython extension by calling reload.
2375
2384
2376 If the module has not been loaded before,
2385 If the module has not been loaded before,
2377 :meth:`InteractiveShell.load_extension` is called. Otherwise
2386 :meth:`InteractiveShell.load_extension` is called. Otherwise
2378 :func:`reload` is called and then the :func:`load_ipython_extension`
2387 :func:`reload` is called and then the :func:`load_ipython_extension`
2379 function of the module, if it exists is called.
2388 function of the module, if it exists is called.
2380 """
2389 """
2381 from IPython.utils.syspathcontext import prepended_to_syspath
2390 from IPython.utils.syspathcontext import prepended_to_syspath
2382
2391
2383 with prepended_to_syspath(self.ipython_extension_dir):
2392 with prepended_to_syspath(self.ipython_extension_dir):
2384 if module_str in sys.modules:
2393 if module_str in sys.modules:
2385 mod = sys.modules[module_str]
2394 mod = sys.modules[module_str]
2386 reload(mod)
2395 reload(mod)
2387 self._call_load_ipython_extension(mod)
2396 self._call_load_ipython_extension(mod)
2388 else:
2397 else:
2389 self.load_extension(module_str)
2398 self.load_extension(module_str)
2390
2399
2391 def _call_load_ipython_extension(self, mod):
2400 def _call_load_ipython_extension(self, mod):
2392 if hasattr(mod, 'load_ipython_extension'):
2401 if hasattr(mod, 'load_ipython_extension'):
2393 return mod.load_ipython_extension(self)
2402 return mod.load_ipython_extension(self)
2394
2403
2395 def _call_unload_ipython_extension(self, mod):
2404 def _call_unload_ipython_extension(self, mod):
2396 if hasattr(mod, 'unload_ipython_extension'):
2405 if hasattr(mod, 'unload_ipython_extension'):
2397 return mod.unload_ipython_extension(self)
2406 return mod.unload_ipython_extension(self)
2398
2407
2399 #-------------------------------------------------------------------------
2408 #-------------------------------------------------------------------------
2400 # Things related to the prefilter
2409 # Things related to the prefilter
2401 #-------------------------------------------------------------------------
2410 #-------------------------------------------------------------------------
2402
2411
2403 def init_prefilter(self):
2412 def init_prefilter(self):
2404 self.prefilter_manager = PrefilterManager(self, config=self.config)
2413 self.prefilter_manager = PrefilterManager(self, config=self.config)
2405 # Ultimately this will be refactored in the new interpreter code, but
2414 # Ultimately this will be refactored in the new interpreter code, but
2406 # for now, we should expose the main prefilter method (there's legacy
2415 # for now, we should expose the main prefilter method (there's legacy
2407 # code out there that may rely on this).
2416 # code out there that may rely on this).
2408 self.prefilter = self.prefilter_manager.prefilter_lines
2417 self.prefilter = self.prefilter_manager.prefilter_lines
2409
2418
2410 #-------------------------------------------------------------------------
2419 #-------------------------------------------------------------------------
2411 # Utilities
2420 # Utilities
2412 #-------------------------------------------------------------------------
2421 #-------------------------------------------------------------------------
2413
2422
2414 def getoutput(self, cmd):
2423 def getoutput(self, cmd):
2415 return getoutput(self.var_expand(cmd,depth=2),
2424 return getoutput(self.var_expand(cmd,depth=2),
2416 header=self.system_header,
2425 header=self.system_header,
2417 verbose=self.system_verbose)
2426 verbose=self.system_verbose)
2418
2427
2419 def getoutputerror(self, cmd):
2428 def getoutputerror(self, cmd):
2420 return getoutputerror(self.var_expand(cmd,depth=2),
2429 return getoutputerror(self.var_expand(cmd,depth=2),
2421 header=self.system_header,
2430 header=self.system_header,
2422 verbose=self.system_verbose)
2431 verbose=self.system_verbose)
2423
2432
2424 def var_expand(self,cmd,depth=0):
2433 def var_expand(self,cmd,depth=0):
2425 """Expand python variables in a string.
2434 """Expand python variables in a string.
2426
2435
2427 The depth argument indicates how many frames above the caller should
2436 The depth argument indicates how many frames above the caller should
2428 be walked to look for the local namespace where to expand variables.
2437 be walked to look for the local namespace where to expand variables.
2429
2438
2430 The global namespace for expansion is always the user's interactive
2439 The global namespace for expansion is always the user's interactive
2431 namespace.
2440 namespace.
2432 """
2441 """
2433
2442
2434 return str(ItplNS(cmd,
2443 return str(ItplNS(cmd,
2435 self.user_ns, # globals
2444 self.user_ns, # globals
2436 # Skip our own frame in searching for locals:
2445 # Skip our own frame in searching for locals:
2437 sys._getframe(depth+1).f_locals # locals
2446 sys._getframe(depth+1).f_locals # locals
2438 ))
2447 ))
2439
2448
2440 def mktempfile(self,data=None):
2449 def mktempfile(self,data=None):
2441 """Make a new tempfile and return its filename.
2450 """Make a new tempfile and return its filename.
2442
2451
2443 This makes a call to tempfile.mktemp, but it registers the created
2452 This makes a call to tempfile.mktemp, but it registers the created
2444 filename internally so ipython cleans it up at exit time.
2453 filename internally so ipython cleans it up at exit time.
2445
2454
2446 Optional inputs:
2455 Optional inputs:
2447
2456
2448 - data(None): if data is given, it gets written out to the temp file
2457 - data(None): if data is given, it gets written out to the temp file
2449 immediately, and the file is closed again."""
2458 immediately, and the file is closed again."""
2450
2459
2451 filename = tempfile.mktemp('.py','ipython_edit_')
2460 filename = tempfile.mktemp('.py','ipython_edit_')
2452 self.tempfiles.append(filename)
2461 self.tempfiles.append(filename)
2453
2462
2454 if data:
2463 if data:
2455 tmp_file = open(filename,'w')
2464 tmp_file = open(filename,'w')
2456 tmp_file.write(data)
2465 tmp_file.write(data)
2457 tmp_file.close()
2466 tmp_file.close()
2458 return filename
2467 return filename
2459
2468
2460 def write(self,data):
2469 def write(self,data):
2461 """Write a string to the default output"""
2470 """Write a string to the default output"""
2462 Term.cout.write(data)
2471 Term.cout.write(data)
2463
2472
2464 def write_err(self,data):
2473 def write_err(self,data):
2465 """Write a string to the default error output"""
2474 """Write a string to the default error output"""
2466 Term.cerr.write(data)
2475 Term.cerr.write(data)
2467
2476
2468 def ask_yes_no(self,prompt,default=True):
2477 def ask_yes_no(self,prompt,default=True):
2469 if self.quiet:
2478 if self.quiet:
2470 return True
2479 return True
2471 return ask_yes_no(prompt,default)
2480 return ask_yes_no(prompt,default)
2472
2481
2473 #-------------------------------------------------------------------------
2482 #-------------------------------------------------------------------------
2474 # Things related to GUI support and pylab
2483 # Things related to GUI support and pylab
2475 #-------------------------------------------------------------------------
2484 #-------------------------------------------------------------------------
2476
2485
2477 def enable_pylab(self, gui=None):
2486 def enable_pylab(self, gui=None):
2478 """Activate pylab support at runtime.
2487 """Activate pylab support at runtime.
2479
2488
2480 This turns on support for matplotlib, preloads into the interactive
2489 This turns on support for matplotlib, preloads into the interactive
2481 namespace all of numpy and pylab, and configures IPython to correcdtly
2490 namespace all of numpy and pylab, and configures IPython to correcdtly
2482 interact with the GUI event loop. The GUI backend to be used can be
2491 interact with the GUI event loop. The GUI backend to be used can be
2483 optionally selected with the optional :param:`gui` argument.
2492 optionally selected with the optional :param:`gui` argument.
2484
2493
2485 Parameters
2494 Parameters
2486 ----------
2495 ----------
2487 gui : optional, string
2496 gui : optional, string
2488
2497
2489 If given, dictates the choice of matplotlib GUI backend to use
2498 If given, dictates the choice of matplotlib GUI backend to use
2490 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2499 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2491 'gtk'), otherwise we use the default chosen by matplotlib (as
2500 'gtk'), otherwise we use the default chosen by matplotlib (as
2492 dictated by the matplotlib build-time options plus the user's
2501 dictated by the matplotlib build-time options plus the user's
2493 matplotlibrc configuration file).
2502 matplotlibrc configuration file).
2494 """
2503 """
2495 # We want to prevent the loading of pylab to pollute the user's
2504 # We want to prevent the loading of pylab to pollute the user's
2496 # namespace as shown by the %who* magics, so we execute the activation
2505 # namespace as shown by the %who* magics, so we execute the activation
2497 # code in an empty namespace, and we update *both* user_ns and
2506 # code in an empty namespace, and we update *both* user_ns and
2498 # user_config_ns with this information.
2507 # user_config_ns with this information.
2499 ns = {}
2508 ns = {}
2500 gui = pylab_activate(ns, gui)
2509 gui = pylab_activate(ns, gui)
2501 self.user_ns.update(ns)
2510 self.user_ns.update(ns)
2502 self.user_config_ns.update(ns)
2511 self.user_config_ns.update(ns)
2503 # Now we must activate the gui pylab wants to use, and fix %run to take
2512 # Now we must activate the gui pylab wants to use, and fix %run to take
2504 # plot updates into account
2513 # plot updates into account
2505 enable_gui(gui)
2514 enable_gui(gui)
2506 self.magic_run = self._pylab_magic_run
2515 self.magic_run = self._pylab_magic_run
2507
2516
2508 #-------------------------------------------------------------------------
2517 #-------------------------------------------------------------------------
2509 # Things related to IPython exiting
2518 # Things related to IPython exiting
2510 #-------------------------------------------------------------------------
2519 #-------------------------------------------------------------------------
2511
2520
2512 def ask_exit(self):
2521 def ask_exit(self):
2513 """ Ask the shell to exit. Can be overiden and used as a callback. """
2522 """ Ask the shell to exit. Can be overiden and used as a callback. """
2514 self.exit_now = True
2523 self.exit_now = True
2515
2524
2516 def exit(self):
2525 def exit(self):
2517 """Handle interactive exit.
2526 """Handle interactive exit.
2518
2527
2519 This method calls the ask_exit callback."""
2528 This method calls the ask_exit callback."""
2520 if self.confirm_exit:
2529 if self.confirm_exit:
2521 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2530 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2522 self.ask_exit()
2531 self.ask_exit()
2523 else:
2532 else:
2524 self.ask_exit()
2533 self.ask_exit()
2525
2534
2526 def atexit_operations(self):
2535 def atexit_operations(self):
2527 """This will be executed at the time of exit.
2536 """This will be executed at the time of exit.
2528
2537
2529 Saving of persistent data should be performed here.
2538 Saving of persistent data should be performed here.
2530 """
2539 """
2531 self.savehist()
2540 self.savehist()
2532
2541
2533 # Cleanup all tempfiles left around
2542 # Cleanup all tempfiles left around
2534 for tfile in self.tempfiles:
2543 for tfile in self.tempfiles:
2535 try:
2544 try:
2536 os.unlink(tfile)
2545 os.unlink(tfile)
2537 except OSError:
2546 except OSError:
2538 pass
2547 pass
2539
2548
2540 # Clear all user namespaces to release all references cleanly.
2549 # Clear all user namespaces to release all references cleanly.
2541 self.reset()
2550 self.reset()
2542
2551
2543 # Run user hooks
2552 # Run user hooks
2544 self.hooks.shutdown_hook()
2553 self.hooks.shutdown_hook()
2545
2554
2546 def cleanup(self):
2555 def cleanup(self):
2547 self.restore_sys_module_state()
2556 self.restore_sys_module_state()
2548
2557
2549
2558
@@ -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,3616 +1,3618 b''
1 # -*- coding: utf-8 -*-
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 #
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12 #-----------------------------------------------------------------------------
12
13
13 #****************************************************************************
14 #-----------------------------------------------------------------------------
14 # Modules and globals
15 # Imports
16 #-----------------------------------------------------------------------------
15
17
16 # Python standard modules
17 import __builtin__
18 import __builtin__
18 import bdb
19 import bdb
19 import inspect
20 import inspect
20 import os
21 import os
21 import pdb
22 import pydoc
23 import sys
22 import sys
24 import shutil
23 import shutil
25 import re
24 import re
26 import tempfile
27 import time
25 import time
28 import cPickle as pickle
29 import textwrap
26 import textwrap
27 import types
30 from cStringIO import StringIO
28 from cStringIO import StringIO
31 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
32 from pprint import pprint, pformat
30 from pprint import pformat
33
31
34 # cProfile was added in Python2.5
32 # cProfile was added in Python2.5
35 try:
33 try:
36 import cProfile as profile
34 import cProfile as profile
37 import pstats
35 import pstats
38 except ImportError:
36 except ImportError:
39 # profile isn't bundled by default in Debian for license reasons
37 # profile isn't bundled by default in Debian for license reasons
40 try:
38 try:
41 import profile,pstats
39 import profile,pstats
42 except ImportError:
40 except ImportError:
43 profile = pstats = None
41 profile = pstats = None
44
42
45 # Homebrewed
46 import IPython
43 import IPython
47 import IPython.utils.generics
48
49 from IPython.core import debugger, oinspect
44 from IPython.core import debugger, oinspect
50 from IPython.core.error import TryNext
45 from IPython.core.error import TryNext
51 from IPython.core.error import UsageError
46 from IPython.core.error import UsageError
52 from IPython.core.fakemodule import FakeModule
47 from IPython.core.fakemodule import FakeModule
53 from IPython.core.macro import Macro
48 from IPython.core.macro import Macro
54 from IPython.core.page import page
49 from IPython.core.page import page
55 from IPython.core.prefilter import ESC_MAGIC
50 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.pylabtools import mpl_runner
51 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.inputhook import enable_gui
52 from IPython.lib.inputhook import enable_gui
58 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
53 from IPython.external.Itpl import itpl, printpl
59 from IPython.testing import decorators as testdec
54 from IPython.testing import decorators as testdec
60 from IPython.utils import platutils
55 from IPython.utils.io import Term, file_read, nlprint
61 from IPython.utils import wildcard
56 from IPython.utils.path import get_py_filename
62 from IPython.utils.PyColorize import Parser
57 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.terminal import set_term_title
59 from IPython.utils.text import LSString, SList, StringTypes
60 from IPython.utils.timing import clock, clock2
61 from IPython.utils.warn import warn, error
63 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
63 import IPython.utils.generics
64
64
65 # XXX - We need to switch to explicit imports here with genutils
65 #-----------------------------------------------------------------------------
66 from IPython.utils.genutils import *
67
68 #***************************************************************************
69 # Utility functions
66 # Utility functions
67 #-----------------------------------------------------------------------------
68
70 def on_off(tag):
69 def on_off(tag):
71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
72 return ['OFF','ON'][tag]
71 return ['OFF','ON'][tag]
73
72
74 class Bunch: pass
73 class Bunch: pass
75
74
76 def compress_dhist(dh):
75 def compress_dhist(dh):
77 head, tail = dh[:-10], dh[-10:]
76 head, tail = dh[:-10], dh[-10:]
78
77
79 newhead = []
78 newhead = []
80 done = set()
79 done = set()
81 for h in head:
80 for h in head:
82 if h in done:
81 if h in done:
83 continue
82 continue
84 newhead.append(h)
83 newhead.append(h)
85 done.add(h)
84 done.add(h)
86
85
87 return newhead + tail
86 return newhead + tail
88
87
89
88
90 #***************************************************************************
89 #***************************************************************************
91 # Main class implementing Magic functionality
90 # Main class implementing Magic functionality
92
91
93 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
92 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
94 # on construction of the main InteractiveShell object. Something odd is going
93 # on construction of the main InteractiveShell object. Something odd is going
95 # on with super() calls, Component and the MRO... For now leave it as-is, but
94 # on with super() calls, Component and the MRO... For now leave it as-is, but
96 # eventually this needs to be clarified.
95 # eventually this needs to be clarified.
96 # BG: This is because InteractiveShell inherits from this, but is itself a
97 # Component. This messes up the MRO in some way. The fix is that we need to
98 # make Magic a component that InteractiveShell does not subclass.
97
99
98 class Magic:
100 class Magic:
99 """Magic functions for InteractiveShell.
101 """Magic functions for InteractiveShell.
100
102
101 Shell functions which can be reached as %function_name. All magic
103 Shell functions which can be reached as %function_name. All magic
102 functions should accept a string, which they can parse for their own
104 functions should accept a string, which they can parse for their own
103 needs. This can make some functions easier to type, eg `%cd ../`
105 needs. This can make some functions easier to type, eg `%cd ../`
104 vs. `%cd("../")`
106 vs. `%cd("../")`
105
107
106 ALL definitions MUST begin with the prefix magic_. The user won't need it
108 ALL definitions MUST begin with the prefix magic_. The user won't need it
107 at the command line, but it is is needed in the definition. """
109 at the command line, but it is is needed in the definition. """
108
110
109 # class globals
111 # class globals
110 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
112 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
111 'Automagic is ON, % prefix NOT needed for magic functions.']
113 'Automagic is ON, % prefix NOT needed for magic functions.']
112
114
113 #......................................................................
115 #......................................................................
114 # some utility functions
116 # some utility functions
115
117
116 def __init__(self,shell):
118 def __init__(self,shell):
117
119
118 self.options_table = {}
120 self.options_table = {}
119 if profile is None:
121 if profile is None:
120 self.magic_prun = self.profile_missing_notice
122 self.magic_prun = self.profile_missing_notice
121 self.shell = shell
123 self.shell = shell
122
124
123 # namespace for holding state we may need
125 # namespace for holding state we may need
124 self._magic_state = Bunch()
126 self._magic_state = Bunch()
125
127
126 def profile_missing_notice(self, *args, **kwargs):
128 def profile_missing_notice(self, *args, **kwargs):
127 error("""\
129 error("""\
128 The profile module could not be found. It has been removed from the standard
130 The profile module could not be found. It has been removed from the standard
129 python packages because of its non-free license. To use profiling, install the
131 python packages because of its non-free license. To use profiling, install the
130 python-profiler package from non-free.""")
132 python-profiler package from non-free.""")
131
133
132 def default_option(self,fn,optstr):
134 def default_option(self,fn,optstr):
133 """Make an entry in the options_table for fn, with value optstr"""
135 """Make an entry in the options_table for fn, with value optstr"""
134
136
135 if fn not in self.lsmagic():
137 if fn not in self.lsmagic():
136 error("%s is not a magic function" % fn)
138 error("%s is not a magic function" % fn)
137 self.options_table[fn] = optstr
139 self.options_table[fn] = optstr
138
140
139 def lsmagic(self):
141 def lsmagic(self):
140 """Return a list of currently available magic functions.
142 """Return a list of currently available magic functions.
141
143
142 Gives a list of the bare names after mangling (['ls','cd', ...], not
144 Gives a list of the bare names after mangling (['ls','cd', ...], not
143 ['magic_ls','magic_cd',...]"""
145 ['magic_ls','magic_cd',...]"""
144
146
145 # FIXME. This needs a cleanup, in the way the magics list is built.
147 # FIXME. This needs a cleanup, in the way the magics list is built.
146
148
147 # magics in class definition
149 # magics in class definition
148 class_magic = lambda fn: fn.startswith('magic_') and \
150 class_magic = lambda fn: fn.startswith('magic_') and \
149 callable(Magic.__dict__[fn])
151 callable(Magic.__dict__[fn])
150 # in instance namespace (run-time user additions)
152 # in instance namespace (run-time user additions)
151 inst_magic = lambda fn: fn.startswith('magic_') and \
153 inst_magic = lambda fn: fn.startswith('magic_') and \
152 callable(self.__dict__[fn])
154 callable(self.__dict__[fn])
153 # and bound magics by user (so they can access self):
155 # and bound magics by user (so they can access self):
154 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
156 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
155 callable(self.__class__.__dict__[fn])
157 callable(self.__class__.__dict__[fn])
156 magics = filter(class_magic,Magic.__dict__.keys()) + \
158 magics = filter(class_magic,Magic.__dict__.keys()) + \
157 filter(inst_magic,self.__dict__.keys()) + \
159 filter(inst_magic,self.__dict__.keys()) + \
158 filter(inst_bound_magic,self.__class__.__dict__.keys())
160 filter(inst_bound_magic,self.__class__.__dict__.keys())
159 out = []
161 out = []
160 for fn in set(magics):
162 for fn in set(magics):
161 out.append(fn.replace('magic_','',1))
163 out.append(fn.replace('magic_','',1))
162 out.sort()
164 out.sort()
163 return out
165 return out
164
166
165 def extract_input_slices(self,slices,raw=False):
167 def extract_input_slices(self,slices,raw=False):
166 """Return as a string a set of input history slices.
168 """Return as a string a set of input history slices.
167
169
168 Inputs:
170 Inputs:
169
171
170 - slices: the set of slices is given as a list of strings (like
172 - slices: the set of slices is given as a list of strings (like
171 ['1','4:8','9'], since this function is for use by magic functions
173 ['1','4:8','9'], since this function is for use by magic functions
172 which get their arguments as strings.
174 which get their arguments as strings.
173
175
174 Optional inputs:
176 Optional inputs:
175
177
176 - raw(False): by default, the processed input is used. If this is
178 - raw(False): by default, the processed input is used. If this is
177 true, the raw input history is used instead.
179 true, the raw input history is used instead.
178
180
179 Note that slices can be called with two notations:
181 Note that slices can be called with two notations:
180
182
181 N:M -> standard python form, means including items N...(M-1).
183 N:M -> standard python form, means including items N...(M-1).
182
184
183 N-M -> include items N..M (closed endpoint)."""
185 N-M -> include items N..M (closed endpoint)."""
184
186
185 if raw:
187 if raw:
186 hist = self.shell.input_hist_raw
188 hist = self.shell.input_hist_raw
187 else:
189 else:
188 hist = self.shell.input_hist
190 hist = self.shell.input_hist
189
191
190 cmds = []
192 cmds = []
191 for chunk in slices:
193 for chunk in slices:
192 if ':' in chunk:
194 if ':' in chunk:
193 ini,fin = map(int,chunk.split(':'))
195 ini,fin = map(int,chunk.split(':'))
194 elif '-' in chunk:
196 elif '-' in chunk:
195 ini,fin = map(int,chunk.split('-'))
197 ini,fin = map(int,chunk.split('-'))
196 fin += 1
198 fin += 1
197 else:
199 else:
198 ini = int(chunk)
200 ini = int(chunk)
199 fin = ini+1
201 fin = ini+1
200 cmds.append(hist[ini:fin])
202 cmds.append(hist[ini:fin])
201 return cmds
203 return cmds
202
204
203 def _ofind(self, oname, namespaces=None):
205 def _ofind(self, oname, namespaces=None):
204 """Find an object in the available namespaces.
206 """Find an object in the available namespaces.
205
207
206 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
208 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
207
209
208 Has special code to detect magic functions.
210 Has special code to detect magic functions.
209 """
211 """
210
212
211 oname = oname.strip()
213 oname = oname.strip()
212
214
213 alias_ns = None
215 alias_ns = None
214 if namespaces is None:
216 if namespaces is None:
215 # Namespaces to search in:
217 # Namespaces to search in:
216 # Put them in a list. The order is important so that we
218 # Put them in a list. The order is important so that we
217 # find things in the same order that Python finds them.
219 # find things in the same order that Python finds them.
218 namespaces = [ ('Interactive', self.shell.user_ns),
220 namespaces = [ ('Interactive', self.shell.user_ns),
219 ('IPython internal', self.shell.internal_ns),
221 ('IPython internal', self.shell.internal_ns),
220 ('Python builtin', __builtin__.__dict__),
222 ('Python builtin', __builtin__.__dict__),
221 ('Alias', self.shell.alias_manager.alias_table),
223 ('Alias', self.shell.alias_manager.alias_table),
222 ]
224 ]
223 alias_ns = self.shell.alias_manager.alias_table
225 alias_ns = self.shell.alias_manager.alias_table
224
226
225 # initialize results to 'null'
227 # initialize results to 'null'
226 found = 0; obj = None; ospace = None; ds = None;
228 found = 0; obj = None; ospace = None; ds = None;
227 ismagic = 0; isalias = 0; parent = None
229 ismagic = 0; isalias = 0; parent = None
228
230
229 # Look for the given name by splitting it in parts. If the head is
231 # Look for the given name by splitting it in parts. If the head is
230 # found, then we look for all the remaining parts as members, and only
232 # found, then we look for all the remaining parts as members, and only
231 # declare success if we can find them all.
233 # declare success if we can find them all.
232 oname_parts = oname.split('.')
234 oname_parts = oname.split('.')
233 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
235 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
234 for nsname,ns in namespaces:
236 for nsname,ns in namespaces:
235 try:
237 try:
236 obj = ns[oname_head]
238 obj = ns[oname_head]
237 except KeyError:
239 except KeyError:
238 continue
240 continue
239 else:
241 else:
240 #print 'oname_rest:', oname_rest # dbg
242 #print 'oname_rest:', oname_rest # dbg
241 for part in oname_rest:
243 for part in oname_rest:
242 try:
244 try:
243 parent = obj
245 parent = obj
244 obj = getattr(obj,part)
246 obj = getattr(obj,part)
245 except:
247 except:
246 # Blanket except b/c some badly implemented objects
248 # Blanket except b/c some badly implemented objects
247 # allow __getattr__ to raise exceptions other than
249 # allow __getattr__ to raise exceptions other than
248 # AttributeError, which then crashes IPython.
250 # AttributeError, which then crashes IPython.
249 break
251 break
250 else:
252 else:
251 # If we finish the for loop (no break), we got all members
253 # If we finish the for loop (no break), we got all members
252 found = 1
254 found = 1
253 ospace = nsname
255 ospace = nsname
254 if ns == alias_ns:
256 if ns == alias_ns:
255 isalias = 1
257 isalias = 1
256 break # namespace loop
258 break # namespace loop
257
259
258 # Try to see if it's magic
260 # Try to see if it's magic
259 if not found:
261 if not found:
260 if oname.startswith(ESC_MAGIC):
262 if oname.startswith(ESC_MAGIC):
261 oname = oname[1:]
263 oname = oname[1:]
262 obj = getattr(self,'magic_'+oname,None)
264 obj = getattr(self,'magic_'+oname,None)
263 if obj is not None:
265 if obj is not None:
264 found = 1
266 found = 1
265 ospace = 'IPython internal'
267 ospace = 'IPython internal'
266 ismagic = 1
268 ismagic = 1
267
269
268 # Last try: special-case some literals like '', [], {}, etc:
270 # Last try: special-case some literals like '', [], {}, etc:
269 if not found and oname_head in ["''",'""','[]','{}','()']:
271 if not found and oname_head in ["''",'""','[]','{}','()']:
270 obj = eval(oname_head)
272 obj = eval(oname_head)
271 found = 1
273 found = 1
272 ospace = 'Interactive'
274 ospace = 'Interactive'
273
275
274 return {'found':found, 'obj':obj, 'namespace':ospace,
276 return {'found':found, 'obj':obj, 'namespace':ospace,
275 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
277 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
276
278
277 def arg_err(self,func):
279 def arg_err(self,func):
278 """Print docstring if incorrect arguments were passed"""
280 """Print docstring if incorrect arguments were passed"""
279 print 'Error in arguments:'
281 print 'Error in arguments:'
280 print OInspect.getdoc(func)
282 print oinspect.getdoc(func)
281
283
282 def format_latex(self,strng):
284 def format_latex(self,strng):
283 """Format a string for latex inclusion."""
285 """Format a string for latex inclusion."""
284
286
285 # Characters that need to be escaped for latex:
287 # Characters that need to be escaped for latex:
286 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
288 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
287 # Magic command names as headers:
289 # Magic command names as headers:
288 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
290 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
289 re.MULTILINE)
291 re.MULTILINE)
290 # Magic commands
292 # Magic commands
291 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
293 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
292 re.MULTILINE)
294 re.MULTILINE)
293 # Paragraph continue
295 # Paragraph continue
294 par_re = re.compile(r'\\$',re.MULTILINE)
296 par_re = re.compile(r'\\$',re.MULTILINE)
295
297
296 # The "\n" symbol
298 # The "\n" symbol
297 newline_re = re.compile(r'\\n')
299 newline_re = re.compile(r'\\n')
298
300
299 # Now build the string for output:
301 # Now build the string for output:
300 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
302 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
301 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
303 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
302 strng)
304 strng)
303 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
305 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
304 strng = par_re.sub(r'\\\\',strng)
306 strng = par_re.sub(r'\\\\',strng)
305 strng = escape_re.sub(r'\\\1',strng)
307 strng = escape_re.sub(r'\\\1',strng)
306 strng = newline_re.sub(r'\\textbackslash{}n',strng)
308 strng = newline_re.sub(r'\\textbackslash{}n',strng)
307 return strng
309 return strng
308
310
309 def format_screen(self,strng):
311 def format_screen(self,strng):
310 """Format a string for screen printing.
312 """Format a string for screen printing.
311
313
312 This removes some latex-type format codes."""
314 This removes some latex-type format codes."""
313 # Paragraph continue
315 # Paragraph continue
314 par_re = re.compile(r'\\$',re.MULTILINE)
316 par_re = re.compile(r'\\$',re.MULTILINE)
315 strng = par_re.sub('',strng)
317 strng = par_re.sub('',strng)
316 return strng
318 return strng
317
319
318 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
320 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
319 """Parse options passed to an argument string.
321 """Parse options passed to an argument string.
320
322
321 The interface is similar to that of getopt(), but it returns back a
323 The interface is similar to that of getopt(), but it returns back a
322 Struct with the options as keys and the stripped argument string still
324 Struct with the options as keys and the stripped argument string still
323 as a string.
325 as a string.
324
326
325 arg_str is quoted as a true sys.argv vector by using shlex.split.
327 arg_str is quoted as a true sys.argv vector by using shlex.split.
326 This allows us to easily expand variables, glob files, quote
328 This allows us to easily expand variables, glob files, quote
327 arguments, etc.
329 arguments, etc.
328
330
329 Options:
331 Options:
330 -mode: default 'string'. If given as 'list', the argument string is
332 -mode: default 'string'. If given as 'list', the argument string is
331 returned as a list (split on whitespace) instead of a string.
333 returned as a list (split on whitespace) instead of a string.
332
334
333 -list_all: put all option values in lists. Normally only options
335 -list_all: put all option values in lists. Normally only options
334 appearing more than once are put in a list.
336 appearing more than once are put in a list.
335
337
336 -posix (True): whether to split the input line in POSIX mode or not,
338 -posix (True): whether to split the input line in POSIX mode or not,
337 as per the conventions outlined in the shlex module from the
339 as per the conventions outlined in the shlex module from the
338 standard library."""
340 standard library."""
339
341
340 # inject default options at the beginning of the input line
342 # inject default options at the beginning of the input line
341 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
343 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
342 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
344 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
343
345
344 mode = kw.get('mode','string')
346 mode = kw.get('mode','string')
345 if mode not in ['string','list']:
347 if mode not in ['string','list']:
346 raise ValueError,'incorrect mode given: %s' % mode
348 raise ValueError,'incorrect mode given: %s' % mode
347 # Get options
349 # Get options
348 list_all = kw.get('list_all',0)
350 list_all = kw.get('list_all',0)
349 posix = kw.get('posix', os.name == 'posix')
351 posix = kw.get('posix', os.name == 'posix')
350
352
351 # Check if we have more than one argument to warrant extra processing:
353 # Check if we have more than one argument to warrant extra processing:
352 odict = {} # Dictionary with options
354 odict = {} # Dictionary with options
353 args = arg_str.split()
355 args = arg_str.split()
354 if len(args) >= 1:
356 if len(args) >= 1:
355 # If the list of inputs only has 0 or 1 thing in it, there's no
357 # If the list of inputs only has 0 or 1 thing in it, there's no
356 # need to look for options
358 # need to look for options
357 argv = arg_split(arg_str,posix)
359 argv = arg_split(arg_str,posix)
358 # Do regular option processing
360 # Do regular option processing
359 try:
361 try:
360 opts,args = getopt(argv,opt_str,*long_opts)
362 opts,args = getopt(argv,opt_str,*long_opts)
361 except GetoptError,e:
363 except GetoptError,e:
362 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
364 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
363 " ".join(long_opts)))
365 " ".join(long_opts)))
364 for o,a in opts:
366 for o,a in opts:
365 if o.startswith('--'):
367 if o.startswith('--'):
366 o = o[2:]
368 o = o[2:]
367 else:
369 else:
368 o = o[1:]
370 o = o[1:]
369 try:
371 try:
370 odict[o].append(a)
372 odict[o].append(a)
371 except AttributeError:
373 except AttributeError:
372 odict[o] = [odict[o],a]
374 odict[o] = [odict[o],a]
373 except KeyError:
375 except KeyError:
374 if list_all:
376 if list_all:
375 odict[o] = [a]
377 odict[o] = [a]
376 else:
378 else:
377 odict[o] = a
379 odict[o] = a
378
380
379 # Prepare opts,args for return
381 # Prepare opts,args for return
380 opts = Struct(odict)
382 opts = Struct(odict)
381 if mode == 'string':
383 if mode == 'string':
382 args = ' '.join(args)
384 args = ' '.join(args)
383
385
384 return opts,args
386 return opts,args
385
387
386 #......................................................................
388 #......................................................................
387 # And now the actual magic functions
389 # And now the actual magic functions
388
390
389 # Functions for IPython shell work (vars,funcs, config, etc)
391 # Functions for IPython shell work (vars,funcs, config, etc)
390 def magic_lsmagic(self, parameter_s = ''):
392 def magic_lsmagic(self, parameter_s = ''):
391 """List currently available magic functions."""
393 """List currently available magic functions."""
392 mesc = ESC_MAGIC
394 mesc = ESC_MAGIC
393 print 'Available magic functions:\n'+mesc+\
395 print 'Available magic functions:\n'+mesc+\
394 (' '+mesc).join(self.lsmagic())
396 (' '+mesc).join(self.lsmagic())
395 print '\n' + Magic.auto_status[self.shell.automagic]
397 print '\n' + Magic.auto_status[self.shell.automagic]
396 return None
398 return None
397
399
398 def magic_magic(self, parameter_s = ''):
400 def magic_magic(self, parameter_s = ''):
399 """Print information about the magic function system.
401 """Print information about the magic function system.
400
402
401 Supported formats: -latex, -brief, -rest
403 Supported formats: -latex, -brief, -rest
402 """
404 """
403
405
404 mode = ''
406 mode = ''
405 try:
407 try:
406 if parameter_s.split()[0] == '-latex':
408 if parameter_s.split()[0] == '-latex':
407 mode = 'latex'
409 mode = 'latex'
408 if parameter_s.split()[0] == '-brief':
410 if parameter_s.split()[0] == '-brief':
409 mode = 'brief'
411 mode = 'brief'
410 if parameter_s.split()[0] == '-rest':
412 if parameter_s.split()[0] == '-rest':
411 mode = 'rest'
413 mode = 'rest'
412 rest_docs = []
414 rest_docs = []
413 except:
415 except:
414 pass
416 pass
415
417
416 magic_docs = []
418 magic_docs = []
417 for fname in self.lsmagic():
419 for fname in self.lsmagic():
418 mname = 'magic_' + fname
420 mname = 'magic_' + fname
419 for space in (Magic,self,self.__class__):
421 for space in (Magic,self,self.__class__):
420 try:
422 try:
421 fn = space.__dict__[mname]
423 fn = space.__dict__[mname]
422 except KeyError:
424 except KeyError:
423 pass
425 pass
424 else:
426 else:
425 break
427 break
426 if mode == 'brief':
428 if mode == 'brief':
427 # only first line
429 # only first line
428 if fn.__doc__:
430 if fn.__doc__:
429 fndoc = fn.__doc__.split('\n',1)[0]
431 fndoc = fn.__doc__.split('\n',1)[0]
430 else:
432 else:
431 fndoc = 'No documentation'
433 fndoc = 'No documentation'
432 else:
434 else:
433 if fn.__doc__:
435 if fn.__doc__:
434 fndoc = fn.__doc__.rstrip()
436 fndoc = fn.__doc__.rstrip()
435 else:
437 else:
436 fndoc = 'No documentation'
438 fndoc = 'No documentation'
437
439
438
440
439 if mode == 'rest':
441 if mode == 'rest':
440 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
442 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
441 fname,fndoc))
443 fname,fndoc))
442
444
443 else:
445 else:
444 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
446 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
445 fname,fndoc))
447 fname,fndoc))
446
448
447 magic_docs = ''.join(magic_docs)
449 magic_docs = ''.join(magic_docs)
448
450
449 if mode == 'rest':
451 if mode == 'rest':
450 return "".join(rest_docs)
452 return "".join(rest_docs)
451
453
452 if mode == 'latex':
454 if mode == 'latex':
453 print self.format_latex(magic_docs)
455 print self.format_latex(magic_docs)
454 return
456 return
455 else:
457 else:
456 magic_docs = self.format_screen(magic_docs)
458 magic_docs = self.format_screen(magic_docs)
457 if mode == 'brief':
459 if mode == 'brief':
458 return magic_docs
460 return magic_docs
459
461
460 outmsg = """
462 outmsg = """
461 IPython's 'magic' functions
463 IPython's 'magic' functions
462 ===========================
464 ===========================
463
465
464 The magic function system provides a series of functions which allow you to
466 The magic function system provides a series of functions which allow you to
465 control the behavior of IPython itself, plus a lot of system-type
467 control the behavior of IPython itself, plus a lot of system-type
466 features. All these functions are prefixed with a % character, but parameters
468 features. All these functions are prefixed with a % character, but parameters
467 are given without parentheses or quotes.
469 are given without parentheses or quotes.
468
470
469 NOTE: If you have 'automagic' enabled (via the command line option or with the
471 NOTE: If you have 'automagic' enabled (via the command line option or with the
470 %automagic function), you don't need to type in the % explicitly. By default,
472 %automagic function), you don't need to type in the % explicitly. By default,
471 IPython ships with automagic on, so you should only rarely need the % escape.
473 IPython ships with automagic on, so you should only rarely need the % escape.
472
474
473 Example: typing '%cd mydir' (without the quotes) changes you working directory
475 Example: typing '%cd mydir' (without the quotes) changes you working directory
474 to 'mydir', if it exists.
476 to 'mydir', if it exists.
475
477
476 You can define your own magic functions to extend the system. See the supplied
478 You can define your own magic functions to extend the system. See the supplied
477 ipythonrc and example-magic.py files for details (in your ipython
479 ipythonrc and example-magic.py files for details (in your ipython
478 configuration directory, typically $HOME/.ipython/).
480 configuration directory, typically $HOME/.ipython/).
479
481
480 You can also define your own aliased names for magic functions. In your
482 You can also define your own aliased names for magic functions. In your
481 ipythonrc file, placing a line like:
483 ipythonrc file, placing a line like:
482
484
483 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
485 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
484
486
485 will define %pf as a new name for %profile.
487 will define %pf as a new name for %profile.
486
488
487 You can also call magics in code using the magic() function, which IPython
489 You can also call magics in code using the magic() function, which IPython
488 automatically adds to the builtin namespace. Type 'magic?' for details.
490 automatically adds to the builtin namespace. Type 'magic?' for details.
489
491
490 For a list of the available magic functions, use %lsmagic. For a description
492 For a list of the available magic functions, use %lsmagic. For a description
491 of any of them, type %magic_name?, e.g. '%cd?'.
493 of any of them, type %magic_name?, e.g. '%cd?'.
492
494
493 Currently the magic system has the following functions:\n"""
495 Currently the magic system has the following functions:\n"""
494
496
495 mesc = ESC_MAGIC
497 mesc = ESC_MAGIC
496 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
498 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
497 "\n\n%s%s\n\n%s" % (outmsg,
499 "\n\n%s%s\n\n%s" % (outmsg,
498 magic_docs,mesc,mesc,
500 magic_docs,mesc,mesc,
499 (' '+mesc).join(self.lsmagic()),
501 (' '+mesc).join(self.lsmagic()),
500 Magic.auto_status[self.shell.automagic] ) )
502 Magic.auto_status[self.shell.automagic] ) )
501
503
502 page(outmsg,screen_lines=self.shell.usable_screen_length)
504 page(outmsg,screen_lines=self.shell.usable_screen_length)
503
505
504
506
505 def magic_autoindent(self, parameter_s = ''):
507 def magic_autoindent(self, parameter_s = ''):
506 """Toggle autoindent on/off (if available)."""
508 """Toggle autoindent on/off (if available)."""
507
509
508 self.shell.set_autoindent()
510 self.shell.set_autoindent()
509 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
511 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
510
512
511
513
512 def magic_automagic(self, parameter_s = ''):
514 def magic_automagic(self, parameter_s = ''):
513 """Make magic functions callable without having to type the initial %.
515 """Make magic functions callable without having to type the initial %.
514
516
515 Without argumentsl toggles on/off (when off, you must call it as
517 Without argumentsl toggles on/off (when off, you must call it as
516 %automagic, of course). With arguments it sets the value, and you can
518 %automagic, of course). With arguments it sets the value, and you can
517 use any of (case insensitive):
519 use any of (case insensitive):
518
520
519 - on,1,True: to activate
521 - on,1,True: to activate
520
522
521 - off,0,False: to deactivate.
523 - off,0,False: to deactivate.
522
524
523 Note that magic functions have lowest priority, so if there's a
525 Note that magic functions have lowest priority, so if there's a
524 variable whose name collides with that of a magic fn, automagic won't
526 variable whose name collides with that of a magic fn, automagic won't
525 work for that function (you get the variable instead). However, if you
527 work for that function (you get the variable instead). However, if you
526 delete the variable (del var), the previously shadowed magic function
528 delete the variable (del var), the previously shadowed magic function
527 becomes visible to automagic again."""
529 becomes visible to automagic again."""
528
530
529 arg = parameter_s.lower()
531 arg = parameter_s.lower()
530 if parameter_s in ('on','1','true'):
532 if parameter_s in ('on','1','true'):
531 self.shell.automagic = True
533 self.shell.automagic = True
532 elif parameter_s in ('off','0','false'):
534 elif parameter_s in ('off','0','false'):
533 self.shell.automagic = False
535 self.shell.automagic = False
534 else:
536 else:
535 self.shell.automagic = not self.shell.automagic
537 self.shell.automagic = not self.shell.automagic
536 print '\n' + Magic.auto_status[self.shell.automagic]
538 print '\n' + Magic.auto_status[self.shell.automagic]
537
539
538 @testdec.skip_doctest
540 @testdec.skip_doctest
539 def magic_autocall(self, parameter_s = ''):
541 def magic_autocall(self, parameter_s = ''):
540 """Make functions callable without having to type parentheses.
542 """Make functions callable without having to type parentheses.
541
543
542 Usage:
544 Usage:
543
545
544 %autocall [mode]
546 %autocall [mode]
545
547
546 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
548 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
547 value is toggled on and off (remembering the previous state).
549 value is toggled on and off (remembering the previous state).
548
550
549 In more detail, these values mean:
551 In more detail, these values mean:
550
552
551 0 -> fully disabled
553 0 -> fully disabled
552
554
553 1 -> active, but do not apply if there are no arguments on the line.
555 1 -> active, but do not apply if there are no arguments on the line.
554
556
555 In this mode, you get:
557 In this mode, you get:
556
558
557 In [1]: callable
559 In [1]: callable
558 Out[1]: <built-in function callable>
560 Out[1]: <built-in function callable>
559
561
560 In [2]: callable 'hello'
562 In [2]: callable 'hello'
561 ------> callable('hello')
563 ------> callable('hello')
562 Out[2]: False
564 Out[2]: False
563
565
564 2 -> Active always. Even if no arguments are present, the callable
566 2 -> Active always. Even if no arguments are present, the callable
565 object is called:
567 object is called:
566
568
567 In [2]: float
569 In [2]: float
568 ------> float()
570 ------> float()
569 Out[2]: 0.0
571 Out[2]: 0.0
570
572
571 Note that even with autocall off, you can still use '/' at the start of
573 Note that even with autocall off, you can still use '/' at the start of
572 a line to treat the first argument on the command line as a function
574 a line to treat the first argument on the command line as a function
573 and add parentheses to it:
575 and add parentheses to it:
574
576
575 In [8]: /str 43
577 In [8]: /str 43
576 ------> str(43)
578 ------> str(43)
577 Out[8]: '43'
579 Out[8]: '43'
578
580
579 # all-random (note for auto-testing)
581 # all-random (note for auto-testing)
580 """
582 """
581
583
582 if parameter_s:
584 if parameter_s:
583 arg = int(parameter_s)
585 arg = int(parameter_s)
584 else:
586 else:
585 arg = 'toggle'
587 arg = 'toggle'
586
588
587 if not arg in (0,1,2,'toggle'):
589 if not arg in (0,1,2,'toggle'):
588 error('Valid modes: (0->Off, 1->Smart, 2->Full')
590 error('Valid modes: (0->Off, 1->Smart, 2->Full')
589 return
591 return
590
592
591 if arg in (0,1,2):
593 if arg in (0,1,2):
592 self.shell.autocall = arg
594 self.shell.autocall = arg
593 else: # toggle
595 else: # toggle
594 if self.shell.autocall:
596 if self.shell.autocall:
595 self._magic_state.autocall_save = self.shell.autocall
597 self._magic_state.autocall_save = self.shell.autocall
596 self.shell.autocall = 0
598 self.shell.autocall = 0
597 else:
599 else:
598 try:
600 try:
599 self.shell.autocall = self._magic_state.autocall_save
601 self.shell.autocall = self._magic_state.autocall_save
600 except AttributeError:
602 except AttributeError:
601 self.shell.autocall = self._magic_state.autocall_save = 1
603 self.shell.autocall = self._magic_state.autocall_save = 1
602
604
603 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
605 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
604
606
605 def magic_system_verbose(self, parameter_s = ''):
607 def magic_system_verbose(self, parameter_s = ''):
606 """Set verbose printing of system calls.
608 """Set verbose printing of system calls.
607
609
608 If called without an argument, act as a toggle"""
610 If called without an argument, act as a toggle"""
609
611
610 if parameter_s:
612 if parameter_s:
611 val = bool(eval(parameter_s))
613 val = bool(eval(parameter_s))
612 else:
614 else:
613 val = None
615 val = None
614
616
615 if self.shell.system_verbose:
617 if self.shell.system_verbose:
616 self.shell.system_verbose = False
618 self.shell.system_verbose = False
617 else:
619 else:
618 self.shell.system_verbose = True
620 self.shell.system_verbose = True
619 print "System verbose printing is:",\
621 print "System verbose printing is:",\
620 ['OFF','ON'][self.shell.system_verbose]
622 ['OFF','ON'][self.shell.system_verbose]
621
623
622
624
623 def magic_page(self, parameter_s=''):
625 def magic_page(self, parameter_s=''):
624 """Pretty print the object and display it through a pager.
626 """Pretty print the object and display it through a pager.
625
627
626 %page [options] OBJECT
628 %page [options] OBJECT
627
629
628 If no object is given, use _ (last output).
630 If no object is given, use _ (last output).
629
631
630 Options:
632 Options:
631
633
632 -r: page str(object), don't pretty-print it."""
634 -r: page str(object), don't pretty-print it."""
633
635
634 # After a function contributed by Olivier Aubert, slightly modified.
636 # After a function contributed by Olivier Aubert, slightly modified.
635
637
636 # Process options/args
638 # Process options/args
637 opts,args = self.parse_options(parameter_s,'r')
639 opts,args = self.parse_options(parameter_s,'r')
638 raw = 'r' in opts
640 raw = 'r' in opts
639
641
640 oname = args and args or '_'
642 oname = args and args or '_'
641 info = self._ofind(oname)
643 info = self._ofind(oname)
642 if info['found']:
644 if info['found']:
643 txt = (raw and str or pformat)( info['obj'] )
645 txt = (raw and str or pformat)( info['obj'] )
644 page(txt)
646 page(txt)
645 else:
647 else:
646 print 'Object `%s` not found' % oname
648 print 'Object `%s` not found' % oname
647
649
648 def magic_profile(self, parameter_s=''):
650 def magic_profile(self, parameter_s=''):
649 """Print your currently active IPyhton profile."""
651 """Print your currently active IPyhton profile."""
650 if self.shell.profile:
652 if self.shell.profile:
651 printpl('Current IPython profile: $self.shell.profile.')
653 printpl('Current IPython profile: $self.shell.profile.')
652 else:
654 else:
653 print 'No profile active.'
655 print 'No profile active.'
654
656
655 def magic_pinfo(self, parameter_s='', namespaces=None):
657 def magic_pinfo(self, parameter_s='', namespaces=None):
656 """Provide detailed information about an object.
658 """Provide detailed information about an object.
657
659
658 '%pinfo object' is just a synonym for object? or ?object."""
660 '%pinfo object' is just a synonym for object? or ?object."""
659
661
660 #print 'pinfo par: <%s>' % parameter_s # dbg
662 #print 'pinfo par: <%s>' % parameter_s # dbg
661
663
662
664
663 # detail_level: 0 -> obj? , 1 -> obj??
665 # detail_level: 0 -> obj? , 1 -> obj??
664 detail_level = 0
666 detail_level = 0
665 # We need to detect if we got called as 'pinfo pinfo foo', which can
667 # We need to detect if we got called as 'pinfo pinfo foo', which can
666 # happen if the user types 'pinfo foo?' at the cmd line.
668 # happen if the user types 'pinfo foo?' at the cmd line.
667 pinfo,qmark1,oname,qmark2 = \
669 pinfo,qmark1,oname,qmark2 = \
668 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
670 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
669 if pinfo or qmark1 or qmark2:
671 if pinfo or qmark1 or qmark2:
670 detail_level = 1
672 detail_level = 1
671 if "*" in oname:
673 if "*" in oname:
672 self.magic_psearch(oname)
674 self.magic_psearch(oname)
673 else:
675 else:
674 self._inspect('pinfo', oname, detail_level=detail_level,
676 self._inspect('pinfo', oname, detail_level=detail_level,
675 namespaces=namespaces)
677 namespaces=namespaces)
676
678
677 def magic_pdef(self, parameter_s='', namespaces=None):
679 def magic_pdef(self, parameter_s='', namespaces=None):
678 """Print the definition header for any callable object.
680 """Print the definition header for any callable object.
679
681
680 If the object is a class, print the constructor information."""
682 If the object is a class, print the constructor information."""
681 self._inspect('pdef',parameter_s, namespaces)
683 self._inspect('pdef',parameter_s, namespaces)
682
684
683 def magic_pdoc(self, parameter_s='', namespaces=None):
685 def magic_pdoc(self, parameter_s='', namespaces=None):
684 """Print the docstring for an object.
686 """Print the docstring for an object.
685
687
686 If the given object is a class, it will print both the class and the
688 If the given object is a class, it will print both the class and the
687 constructor docstrings."""
689 constructor docstrings."""
688 self._inspect('pdoc',parameter_s, namespaces)
690 self._inspect('pdoc',parameter_s, namespaces)
689
691
690 def magic_psource(self, parameter_s='', namespaces=None):
692 def magic_psource(self, parameter_s='', namespaces=None):
691 """Print (or run through pager) the source code for an object."""
693 """Print (or run through pager) the source code for an object."""
692 self._inspect('psource',parameter_s, namespaces)
694 self._inspect('psource',parameter_s, namespaces)
693
695
694 def magic_pfile(self, parameter_s=''):
696 def magic_pfile(self, parameter_s=''):
695 """Print (or run through pager) the file where an object is defined.
697 """Print (or run through pager) the file where an object is defined.
696
698
697 The file opens at the line where the object definition begins. IPython
699 The file opens at the line where the object definition begins. IPython
698 will honor the environment variable PAGER if set, and otherwise will
700 will honor the environment variable PAGER if set, and otherwise will
699 do its best to print the file in a convenient form.
701 do its best to print the file in a convenient form.
700
702
701 If the given argument is not an object currently defined, IPython will
703 If the given argument is not an object currently defined, IPython will
702 try to interpret it as a filename (automatically adding a .py extension
704 try to interpret it as a filename (automatically adding a .py extension
703 if needed). You can thus use %pfile as a syntax highlighting code
705 if needed). You can thus use %pfile as a syntax highlighting code
704 viewer."""
706 viewer."""
705
707
706 # first interpret argument as an object name
708 # first interpret argument as an object name
707 out = self._inspect('pfile',parameter_s)
709 out = self._inspect('pfile',parameter_s)
708 # if not, try the input as a filename
710 # if not, try the input as a filename
709 if out == 'not found':
711 if out == 'not found':
710 try:
712 try:
711 filename = get_py_filename(parameter_s)
713 filename = get_py_filename(parameter_s)
712 except IOError,msg:
714 except IOError,msg:
713 print msg
715 print msg
714 return
716 return
715 page(self.shell.inspector.format(file(filename).read()))
717 page(self.shell.inspector.format(file(filename).read()))
716
718
717 def _inspect(self,meth,oname,namespaces=None,**kw):
719 def _inspect(self,meth,oname,namespaces=None,**kw):
718 """Generic interface to the inspector system.
720 """Generic interface to the inspector system.
719
721
720 This function is meant to be called by pdef, pdoc & friends."""
722 This function is meant to be called by pdef, pdoc & friends."""
721
723
722 #oname = oname.strip()
724 #oname = oname.strip()
723 #print '1- oname: <%r>' % oname # dbg
725 #print '1- oname: <%r>' % oname # dbg
724 try:
726 try:
725 oname = oname.strip().encode('ascii')
727 oname = oname.strip().encode('ascii')
726 #print '2- oname: <%r>' % oname # dbg
728 #print '2- oname: <%r>' % oname # dbg
727 except UnicodeEncodeError:
729 except UnicodeEncodeError:
728 print 'Python identifiers can only contain ascii characters.'
730 print 'Python identifiers can only contain ascii characters.'
729 return 'not found'
731 return 'not found'
730
732
731 info = Struct(self._ofind(oname, namespaces))
733 info = Struct(self._ofind(oname, namespaces))
732
734
733 if info.found:
735 if info.found:
734 try:
736 try:
735 IPython.utils.generics.inspect_object(info.obj)
737 IPython.utils.generics.inspect_object(info.obj)
736 return
738 return
737 except TryNext:
739 except TryNext:
738 pass
740 pass
739 # Get the docstring of the class property if it exists.
741 # Get the docstring of the class property if it exists.
740 path = oname.split('.')
742 path = oname.split('.')
741 root = '.'.join(path[:-1])
743 root = '.'.join(path[:-1])
742 if info.parent is not None:
744 if info.parent is not None:
743 try:
745 try:
744 target = getattr(info.parent, '__class__')
746 target = getattr(info.parent, '__class__')
745 # The object belongs to a class instance.
747 # The object belongs to a class instance.
746 try:
748 try:
747 target = getattr(target, path[-1])
749 target = getattr(target, path[-1])
748 # The class defines the object.
750 # The class defines the object.
749 if isinstance(target, property):
751 if isinstance(target, property):
750 oname = root + '.__class__.' + path[-1]
752 oname = root + '.__class__.' + path[-1]
751 info = Struct(self._ofind(oname))
753 info = Struct(self._ofind(oname))
752 except AttributeError: pass
754 except AttributeError: pass
753 except AttributeError: pass
755 except AttributeError: pass
754
756
755 pmethod = getattr(self.shell.inspector,meth)
757 pmethod = getattr(self.shell.inspector,meth)
756 formatter = info.ismagic and self.format_screen or None
758 formatter = info.ismagic and self.format_screen or None
757 if meth == 'pdoc':
759 if meth == 'pdoc':
758 pmethod(info.obj,oname,formatter)
760 pmethod(info.obj,oname,formatter)
759 elif meth == 'pinfo':
761 elif meth == 'pinfo':
760 pmethod(info.obj,oname,formatter,info,**kw)
762 pmethod(info.obj,oname,formatter,info,**kw)
761 else:
763 else:
762 pmethod(info.obj,oname)
764 pmethod(info.obj,oname)
763 else:
765 else:
764 print 'Object `%s` not found.' % oname
766 print 'Object `%s` not found.' % oname
765 return 'not found' # so callers can take other action
767 return 'not found' # so callers can take other action
766
768
767 def magic_psearch(self, parameter_s=''):
769 def magic_psearch(self, parameter_s=''):
768 """Search for object in namespaces by wildcard.
770 """Search for object in namespaces by wildcard.
769
771
770 %psearch [options] PATTERN [OBJECT TYPE]
772 %psearch [options] PATTERN [OBJECT TYPE]
771
773
772 Note: ? can be used as a synonym for %psearch, at the beginning or at
774 Note: ? can be used as a synonym for %psearch, at the beginning or at
773 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
775 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
774 rest of the command line must be unchanged (options come first), so
776 rest of the command line must be unchanged (options come first), so
775 for example the following forms are equivalent
777 for example the following forms are equivalent
776
778
777 %psearch -i a* function
779 %psearch -i a* function
778 -i a* function?
780 -i a* function?
779 ?-i a* function
781 ?-i a* function
780
782
781 Arguments:
783 Arguments:
782
784
783 PATTERN
785 PATTERN
784
786
785 where PATTERN is a string containing * as a wildcard similar to its
787 where PATTERN is a string containing * as a wildcard similar to its
786 use in a shell. The pattern is matched in all namespaces on the
788 use in a shell. The pattern is matched in all namespaces on the
787 search path. By default objects starting with a single _ are not
789 search path. By default objects starting with a single _ are not
788 matched, many IPython generated objects have a single
790 matched, many IPython generated objects have a single
789 underscore. The default is case insensitive matching. Matching is
791 underscore. The default is case insensitive matching. Matching is
790 also done on the attributes of objects and not only on the objects
792 also done on the attributes of objects and not only on the objects
791 in a module.
793 in a module.
792
794
793 [OBJECT TYPE]
795 [OBJECT TYPE]
794
796
795 Is the name of a python type from the types module. The name is
797 Is the name of a python type from the types module. The name is
796 given in lowercase without the ending type, ex. StringType is
798 given in lowercase without the ending type, ex. StringType is
797 written string. By adding a type here only objects matching the
799 written string. By adding a type here only objects matching the
798 given type are matched. Using all here makes the pattern match all
800 given type are matched. Using all here makes the pattern match all
799 types (this is the default).
801 types (this is the default).
800
802
801 Options:
803 Options:
802
804
803 -a: makes the pattern match even objects whose names start with a
805 -a: makes the pattern match even objects whose names start with a
804 single underscore. These names are normally ommitted from the
806 single underscore. These names are normally ommitted from the
805 search.
807 search.
806
808
807 -i/-c: make the pattern case insensitive/sensitive. If neither of
809 -i/-c: make the pattern case insensitive/sensitive. If neither of
808 these options is given, the default is read from your ipythonrc
810 these options is given, the default is read from your ipythonrc
809 file. The option name which sets this value is
811 file. The option name which sets this value is
810 'wildcards_case_sensitive'. If this option is not specified in your
812 'wildcards_case_sensitive'. If this option is not specified in your
811 ipythonrc file, IPython's internal default is to do a case sensitive
813 ipythonrc file, IPython's internal default is to do a case sensitive
812 search.
814 search.
813
815
814 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
816 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
815 specifiy can be searched in any of the following namespaces:
817 specifiy can be searched in any of the following namespaces:
816 'builtin', 'user', 'user_global','internal', 'alias', where
818 'builtin', 'user', 'user_global','internal', 'alias', where
817 'builtin' and 'user' are the search defaults. Note that you should
819 'builtin' and 'user' are the search defaults. Note that you should
818 not use quotes when specifying namespaces.
820 not use quotes when specifying namespaces.
819
821
820 'Builtin' contains the python module builtin, 'user' contains all
822 'Builtin' contains the python module builtin, 'user' contains all
821 user data, 'alias' only contain the shell aliases and no python
823 user data, 'alias' only contain the shell aliases and no python
822 objects, 'internal' contains objects used by IPython. The
824 objects, 'internal' contains objects used by IPython. The
823 'user_global' namespace is only used by embedded IPython instances,
825 'user_global' namespace is only used by embedded IPython instances,
824 and it contains module-level globals. You can add namespaces to the
826 and it contains module-level globals. You can add namespaces to the
825 search with -s or exclude them with -e (these options can be given
827 search with -s or exclude them with -e (these options can be given
826 more than once).
828 more than once).
827
829
828 Examples:
830 Examples:
829
831
830 %psearch a* -> objects beginning with an a
832 %psearch a* -> objects beginning with an a
831 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
833 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
832 %psearch a* function -> all functions beginning with an a
834 %psearch a* function -> all functions beginning with an a
833 %psearch re.e* -> objects beginning with an e in module re
835 %psearch re.e* -> objects beginning with an e in module re
834 %psearch r*.e* -> objects that start with e in modules starting in r
836 %psearch r*.e* -> objects that start with e in modules starting in r
835 %psearch r*.* string -> all strings in modules beginning with r
837 %psearch r*.* string -> all strings in modules beginning with r
836
838
837 Case sensitve search:
839 Case sensitve search:
838
840
839 %psearch -c a* list all object beginning with lower case a
841 %psearch -c a* list all object beginning with lower case a
840
842
841 Show objects beginning with a single _:
843 Show objects beginning with a single _:
842
844
843 %psearch -a _* list objects beginning with a single underscore"""
845 %psearch -a _* list objects beginning with a single underscore"""
844 try:
846 try:
845 parameter_s = parameter_s.encode('ascii')
847 parameter_s = parameter_s.encode('ascii')
846 except UnicodeEncodeError:
848 except UnicodeEncodeError:
847 print 'Python identifiers can only contain ascii characters.'
849 print 'Python identifiers can only contain ascii characters.'
848 return
850 return
849
851
850 # default namespaces to be searched
852 # default namespaces to be searched
851 def_search = ['user','builtin']
853 def_search = ['user','builtin']
852
854
853 # Process options/args
855 # Process options/args
854 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
856 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
855 opt = opts.get
857 opt = opts.get
856 shell = self.shell
858 shell = self.shell
857 psearch = shell.inspector.psearch
859 psearch = shell.inspector.psearch
858
860
859 # select case options
861 # select case options
860 if opts.has_key('i'):
862 if opts.has_key('i'):
861 ignore_case = True
863 ignore_case = True
862 elif opts.has_key('c'):
864 elif opts.has_key('c'):
863 ignore_case = False
865 ignore_case = False
864 else:
866 else:
865 ignore_case = not shell.wildcards_case_sensitive
867 ignore_case = not shell.wildcards_case_sensitive
866
868
867 # Build list of namespaces to search from user options
869 # Build list of namespaces to search from user options
868 def_search.extend(opt('s',[]))
870 def_search.extend(opt('s',[]))
869 ns_exclude = ns_exclude=opt('e',[])
871 ns_exclude = ns_exclude=opt('e',[])
870 ns_search = [nm for nm in def_search if nm not in ns_exclude]
872 ns_search = [nm for nm in def_search if nm not in ns_exclude]
871
873
872 # Call the actual search
874 # Call the actual search
873 try:
875 try:
874 psearch(args,shell.ns_table,ns_search,
876 psearch(args,shell.ns_table,ns_search,
875 show_all=opt('a'),ignore_case=ignore_case)
877 show_all=opt('a'),ignore_case=ignore_case)
876 except:
878 except:
877 shell.showtraceback()
879 shell.showtraceback()
878
880
879 def magic_who_ls(self, parameter_s=''):
881 def magic_who_ls(self, parameter_s=''):
880 """Return a sorted list of all interactive variables.
882 """Return a sorted list of all interactive variables.
881
883
882 If arguments are given, only variables of types matching these
884 If arguments are given, only variables of types matching these
883 arguments are returned."""
885 arguments are returned."""
884
886
885 user_ns = self.shell.user_ns
887 user_ns = self.shell.user_ns
886 internal_ns = self.shell.internal_ns
888 internal_ns = self.shell.internal_ns
887 user_config_ns = self.shell.user_config_ns
889 user_config_ns = self.shell.user_config_ns
888 out = [ i for i in user_ns
890 out = [ i for i in user_ns
889 if not i.startswith('_') \
891 if not i.startswith('_') \
890 and not (i in internal_ns or i in user_config_ns) ]
892 and not (i in internal_ns or i in user_config_ns) ]
891
893
892 typelist = parameter_s.split()
894 typelist = parameter_s.split()
893 if typelist:
895 if typelist:
894 typeset = set(typelist)
896 typeset = set(typelist)
895 out = [i for i in out if type(i).__name__ in typeset]
897 out = [i for i in out if type(i).__name__ in typeset]
896
898
897 out.sort()
899 out.sort()
898 return out
900 return out
899
901
900 def magic_who(self, parameter_s=''):
902 def magic_who(self, parameter_s=''):
901 """Print all interactive variables, with some minimal formatting.
903 """Print all interactive variables, with some minimal formatting.
902
904
903 If any arguments are given, only variables whose type matches one of
905 If any arguments are given, only variables whose type matches one of
904 these are printed. For example:
906 these are printed. For example:
905
907
906 %who function str
908 %who function str
907
909
908 will only list functions and strings, excluding all other types of
910 will only list functions and strings, excluding all other types of
909 variables. To find the proper type names, simply use type(var) at a
911 variables. To find the proper type names, simply use type(var) at a
910 command line to see how python prints type names. For example:
912 command line to see how python prints type names. For example:
911
913
912 In [1]: type('hello')\\
914 In [1]: type('hello')\\
913 Out[1]: <type 'str'>
915 Out[1]: <type 'str'>
914
916
915 indicates that the type name for strings is 'str'.
917 indicates that the type name for strings is 'str'.
916
918
917 %who always excludes executed names loaded through your configuration
919 %who always excludes executed names loaded through your configuration
918 file and things which are internal to IPython.
920 file and things which are internal to IPython.
919
921
920 This is deliberate, as typically you may load many modules and the
922 This is deliberate, as typically you may load many modules and the
921 purpose of %who is to show you only what you've manually defined."""
923 purpose of %who is to show you only what you've manually defined."""
922
924
923 varlist = self.magic_who_ls(parameter_s)
925 varlist = self.magic_who_ls(parameter_s)
924 if not varlist:
926 if not varlist:
925 if parameter_s:
927 if parameter_s:
926 print 'No variables match your requested type.'
928 print 'No variables match your requested type.'
927 else:
929 else:
928 print 'Interactive namespace is empty.'
930 print 'Interactive namespace is empty.'
929 return
931 return
930
932
931 # if we have variables, move on...
933 # if we have variables, move on...
932 count = 0
934 count = 0
933 for i in varlist:
935 for i in varlist:
934 print i+'\t',
936 print i+'\t',
935 count += 1
937 count += 1
936 if count > 8:
938 if count > 8:
937 count = 0
939 count = 0
938 print
940 print
939 print
941 print
940
942
941 def magic_whos(self, parameter_s=''):
943 def magic_whos(self, parameter_s=''):
942 """Like %who, but gives some extra information about each variable.
944 """Like %who, but gives some extra information about each variable.
943
945
944 The same type filtering of %who can be applied here.
946 The same type filtering of %who can be applied here.
945
947
946 For all variables, the type is printed. Additionally it prints:
948 For all variables, the type is printed. Additionally it prints:
947
949
948 - For {},[],(): their length.
950 - For {},[],(): their length.
949
951
950 - For numpy and Numeric arrays, a summary with shape, number of
952 - For numpy and Numeric arrays, a summary with shape, number of
951 elements, typecode and size in memory.
953 elements, typecode and size in memory.
952
954
953 - Everything else: a string representation, snipping their middle if
955 - Everything else: a string representation, snipping their middle if
954 too long."""
956 too long."""
955
957
956 varnames = self.magic_who_ls(parameter_s)
958 varnames = self.magic_who_ls(parameter_s)
957 if not varnames:
959 if not varnames:
958 if parameter_s:
960 if parameter_s:
959 print 'No variables match your requested type.'
961 print 'No variables match your requested type.'
960 else:
962 else:
961 print 'Interactive namespace is empty.'
963 print 'Interactive namespace is empty.'
962 return
964 return
963
965
964 # if we have variables, move on...
966 # if we have variables, move on...
965
967
966 # for these types, show len() instead of data:
968 # for these types, show len() instead of data:
967 seq_types = [types.DictType,types.ListType,types.TupleType]
969 seq_types = [types.DictType,types.ListType,types.TupleType]
968
970
969 # for numpy/Numeric arrays, display summary info
971 # for numpy/Numeric arrays, display summary info
970 try:
972 try:
971 import numpy
973 import numpy
972 except ImportError:
974 except ImportError:
973 ndarray_type = None
975 ndarray_type = None
974 else:
976 else:
975 ndarray_type = numpy.ndarray.__name__
977 ndarray_type = numpy.ndarray.__name__
976 try:
978 try:
977 import Numeric
979 import Numeric
978 except ImportError:
980 except ImportError:
979 array_type = None
981 array_type = None
980 else:
982 else:
981 array_type = Numeric.ArrayType.__name__
983 array_type = Numeric.ArrayType.__name__
982
984
983 # Find all variable names and types so we can figure out column sizes
985 # Find all variable names and types so we can figure out column sizes
984 def get_vars(i):
986 def get_vars(i):
985 return self.shell.user_ns[i]
987 return self.shell.user_ns[i]
986
988
987 # some types are well known and can be shorter
989 # some types are well known and can be shorter
988 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
990 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
989 def type_name(v):
991 def type_name(v):
990 tn = type(v).__name__
992 tn = type(v).__name__
991 return abbrevs.get(tn,tn)
993 return abbrevs.get(tn,tn)
992
994
993 varlist = map(get_vars,varnames)
995 varlist = map(get_vars,varnames)
994
996
995 typelist = []
997 typelist = []
996 for vv in varlist:
998 for vv in varlist:
997 tt = type_name(vv)
999 tt = type_name(vv)
998
1000
999 if tt=='instance':
1001 if tt=='instance':
1000 typelist.append( abbrevs.get(str(vv.__class__),
1002 typelist.append( abbrevs.get(str(vv.__class__),
1001 str(vv.__class__)))
1003 str(vv.__class__)))
1002 else:
1004 else:
1003 typelist.append(tt)
1005 typelist.append(tt)
1004
1006
1005 # column labels and # of spaces as separator
1007 # column labels and # of spaces as separator
1006 varlabel = 'Variable'
1008 varlabel = 'Variable'
1007 typelabel = 'Type'
1009 typelabel = 'Type'
1008 datalabel = 'Data/Info'
1010 datalabel = 'Data/Info'
1009 colsep = 3
1011 colsep = 3
1010 # variable format strings
1012 # variable format strings
1011 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1013 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1012 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1014 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1013 aformat = "%s: %s elems, type `%s`, %s bytes"
1015 aformat = "%s: %s elems, type `%s`, %s bytes"
1014 # find the size of the columns to format the output nicely
1016 # find the size of the columns to format the output nicely
1015 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1017 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1016 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1018 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1017 # table header
1019 # table header
1018 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1020 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1019 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1021 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1020 # and the table itself
1022 # and the table itself
1021 kb = 1024
1023 kb = 1024
1022 Mb = 1048576 # kb**2
1024 Mb = 1048576 # kb**2
1023 for vname,var,vtype in zip(varnames,varlist,typelist):
1025 for vname,var,vtype in zip(varnames,varlist,typelist):
1024 print itpl(vformat),
1026 print itpl(vformat),
1025 if vtype in seq_types:
1027 if vtype in seq_types:
1026 print len(var)
1028 print len(var)
1027 elif vtype in [array_type,ndarray_type]:
1029 elif vtype in [array_type,ndarray_type]:
1028 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1030 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1029 if vtype==ndarray_type:
1031 if vtype==ndarray_type:
1030 # numpy
1032 # numpy
1031 vsize = var.size
1033 vsize = var.size
1032 vbytes = vsize*var.itemsize
1034 vbytes = vsize*var.itemsize
1033 vdtype = var.dtype
1035 vdtype = var.dtype
1034 else:
1036 else:
1035 # Numeric
1037 # Numeric
1036 vsize = Numeric.size(var)
1038 vsize = Numeric.size(var)
1037 vbytes = vsize*var.itemsize()
1039 vbytes = vsize*var.itemsize()
1038 vdtype = var.typecode()
1040 vdtype = var.typecode()
1039
1041
1040 if vbytes < 100000:
1042 if vbytes < 100000:
1041 print aformat % (vshape,vsize,vdtype,vbytes)
1043 print aformat % (vshape,vsize,vdtype,vbytes)
1042 else:
1044 else:
1043 print aformat % (vshape,vsize,vdtype,vbytes),
1045 print aformat % (vshape,vsize,vdtype,vbytes),
1044 if vbytes < Mb:
1046 if vbytes < Mb:
1045 print '(%s kb)' % (vbytes/kb,)
1047 print '(%s kb)' % (vbytes/kb,)
1046 else:
1048 else:
1047 print '(%s Mb)' % (vbytes/Mb,)
1049 print '(%s Mb)' % (vbytes/Mb,)
1048 else:
1050 else:
1049 try:
1051 try:
1050 vstr = str(var)
1052 vstr = str(var)
1051 except UnicodeEncodeError:
1053 except UnicodeEncodeError:
1052 vstr = unicode(var).encode(sys.getdefaultencoding(),
1054 vstr = unicode(var).encode(sys.getdefaultencoding(),
1053 'backslashreplace')
1055 'backslashreplace')
1054 vstr = vstr.replace('\n','\\n')
1056 vstr = vstr.replace('\n','\\n')
1055 if len(vstr) < 50:
1057 if len(vstr) < 50:
1056 print vstr
1058 print vstr
1057 else:
1059 else:
1058 printpl(vfmt_short)
1060 printpl(vfmt_short)
1059
1061
1060 def magic_reset(self, parameter_s=''):
1062 def magic_reset(self, parameter_s=''):
1061 """Resets the namespace by removing all names defined by the user.
1063 """Resets the namespace by removing all names defined by the user.
1062
1064
1063 Input/Output history are left around in case you need them.
1065 Input/Output history are left around in case you need them.
1064
1066
1065 Parameters
1067 Parameters
1066 ----------
1068 ----------
1067 -y : force reset without asking for confirmation.
1069 -y : force reset without asking for confirmation.
1068
1070
1069 Examples
1071 Examples
1070 --------
1072 --------
1071 In [6]: a = 1
1073 In [6]: a = 1
1072
1074
1073 In [7]: a
1075 In [7]: a
1074 Out[7]: 1
1076 Out[7]: 1
1075
1077
1076 In [8]: 'a' in _ip.user_ns
1078 In [8]: 'a' in _ip.user_ns
1077 Out[8]: True
1079 Out[8]: True
1078
1080
1079 In [9]: %reset -f
1081 In [9]: %reset -f
1080
1082
1081 In [10]: 'a' in _ip.user_ns
1083 In [10]: 'a' in _ip.user_ns
1082 Out[10]: False
1084 Out[10]: False
1083 """
1085 """
1084
1086
1085 if parameter_s == '-f':
1087 if parameter_s == '-f':
1086 ans = True
1088 ans = True
1087 else:
1089 else:
1088 ans = self.shell.ask_yes_no(
1090 ans = self.shell.ask_yes_no(
1089 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1091 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1090 if not ans:
1092 if not ans:
1091 print 'Nothing done.'
1093 print 'Nothing done.'
1092 return
1094 return
1093 user_ns = self.shell.user_ns
1095 user_ns = self.shell.user_ns
1094 for i in self.magic_who_ls():
1096 for i in self.magic_who_ls():
1095 del(user_ns[i])
1097 del(user_ns[i])
1096
1098
1097 # Also flush the private list of module references kept for script
1099 # Also flush the private list of module references kept for script
1098 # execution protection
1100 # execution protection
1099 self.shell.clear_main_mod_cache()
1101 self.shell.clear_main_mod_cache()
1100
1102
1101 def magic_logstart(self,parameter_s=''):
1103 def magic_logstart(self,parameter_s=''):
1102 """Start logging anywhere in a session.
1104 """Start logging anywhere in a session.
1103
1105
1104 %logstart [-o|-r|-t] [log_name [log_mode]]
1106 %logstart [-o|-r|-t] [log_name [log_mode]]
1105
1107
1106 If no name is given, it defaults to a file named 'ipython_log.py' in your
1108 If no name is given, it defaults to a file named 'ipython_log.py' in your
1107 current directory, in 'rotate' mode (see below).
1109 current directory, in 'rotate' mode (see below).
1108
1110
1109 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1111 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1110 history up to that point and then continues logging.
1112 history up to that point and then continues logging.
1111
1113
1112 %logstart takes a second optional parameter: logging mode. This can be one
1114 %logstart takes a second optional parameter: logging mode. This can be one
1113 of (note that the modes are given unquoted):\\
1115 of (note that the modes are given unquoted):\\
1114 append: well, that says it.\\
1116 append: well, that says it.\\
1115 backup: rename (if exists) to name~ and start name.\\
1117 backup: rename (if exists) to name~ and start name.\\
1116 global: single logfile in your home dir, appended to.\\
1118 global: single logfile in your home dir, appended to.\\
1117 over : overwrite existing log.\\
1119 over : overwrite existing log.\\
1118 rotate: create rotating logs name.1~, name.2~, etc.
1120 rotate: create rotating logs name.1~, name.2~, etc.
1119
1121
1120 Options:
1122 Options:
1121
1123
1122 -o: log also IPython's output. In this mode, all commands which
1124 -o: log also IPython's output. In this mode, all commands which
1123 generate an Out[NN] prompt are recorded to the logfile, right after
1125 generate an Out[NN] prompt are recorded to the logfile, right after
1124 their corresponding input line. The output lines are always
1126 their corresponding input line. The output lines are always
1125 prepended with a '#[Out]# ' marker, so that the log remains valid
1127 prepended with a '#[Out]# ' marker, so that the log remains valid
1126 Python code.
1128 Python code.
1127
1129
1128 Since this marker is always the same, filtering only the output from
1130 Since this marker is always the same, filtering only the output from
1129 a log is very easy, using for example a simple awk call:
1131 a log is very easy, using for example a simple awk call:
1130
1132
1131 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1133 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1132
1134
1133 -r: log 'raw' input. Normally, IPython's logs contain the processed
1135 -r: log 'raw' input. Normally, IPython's logs contain the processed
1134 input, so that user lines are logged in their final form, converted
1136 input, so that user lines are logged in their final form, converted
1135 into valid Python. For example, %Exit is logged as
1137 into valid Python. For example, %Exit is logged as
1136 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1138 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1137 exactly as typed, with no transformations applied.
1139 exactly as typed, with no transformations applied.
1138
1140
1139 -t: put timestamps before each input line logged (these are put in
1141 -t: put timestamps before each input line logged (these are put in
1140 comments)."""
1142 comments)."""
1141
1143
1142 opts,par = self.parse_options(parameter_s,'ort')
1144 opts,par = self.parse_options(parameter_s,'ort')
1143 log_output = 'o' in opts
1145 log_output = 'o' in opts
1144 log_raw_input = 'r' in opts
1146 log_raw_input = 'r' in opts
1145 timestamp = 't' in opts
1147 timestamp = 't' in opts
1146
1148
1147 logger = self.shell.logger
1149 logger = self.shell.logger
1148
1150
1149 # if no args are given, the defaults set in the logger constructor by
1151 # if no args are given, the defaults set in the logger constructor by
1150 # ipytohn remain valid
1152 # ipytohn remain valid
1151 if par:
1153 if par:
1152 try:
1154 try:
1153 logfname,logmode = par.split()
1155 logfname,logmode = par.split()
1154 except:
1156 except:
1155 logfname = par
1157 logfname = par
1156 logmode = 'backup'
1158 logmode = 'backup'
1157 else:
1159 else:
1158 logfname = logger.logfname
1160 logfname = logger.logfname
1159 logmode = logger.logmode
1161 logmode = logger.logmode
1160 # put logfname into rc struct as if it had been called on the command
1162 # put logfname into rc struct as if it had been called on the command
1161 # line, so it ends up saved in the log header Save it in case we need
1163 # line, so it ends up saved in the log header Save it in case we need
1162 # to restore it...
1164 # to restore it...
1163 old_logfile = self.shell.logfile
1165 old_logfile = self.shell.logfile
1164 if logfname:
1166 if logfname:
1165 logfname = os.path.expanduser(logfname)
1167 logfname = os.path.expanduser(logfname)
1166 self.shell.logfile = logfname
1168 self.shell.logfile = logfname
1167
1169
1168 loghead = '# IPython log file\n\n'
1170 loghead = '# IPython log file\n\n'
1169 try:
1171 try:
1170 started = logger.logstart(logfname,loghead,logmode,
1172 started = logger.logstart(logfname,loghead,logmode,
1171 log_output,timestamp,log_raw_input)
1173 log_output,timestamp,log_raw_input)
1172 except:
1174 except:
1173 rc.opts.logfile = old_logfile
1175 self.shell.logfile = old_logfile
1174 warn("Couldn't start log: %s" % sys.exc_info()[1])
1176 warn("Couldn't start log: %s" % sys.exc_info()[1])
1175 else:
1177 else:
1176 # log input history up to this point, optionally interleaving
1178 # log input history up to this point, optionally interleaving
1177 # output if requested
1179 # output if requested
1178
1180
1179 if timestamp:
1181 if timestamp:
1180 # disable timestamping for the previous history, since we've
1182 # disable timestamping for the previous history, since we've
1181 # lost those already (no time machine here).
1183 # lost those already (no time machine here).
1182 logger.timestamp = False
1184 logger.timestamp = False
1183
1185
1184 if log_raw_input:
1186 if log_raw_input:
1185 input_hist = self.shell.input_hist_raw
1187 input_hist = self.shell.input_hist_raw
1186 else:
1188 else:
1187 input_hist = self.shell.input_hist
1189 input_hist = self.shell.input_hist
1188
1190
1189 if log_output:
1191 if log_output:
1190 log_write = logger.log_write
1192 log_write = logger.log_write
1191 output_hist = self.shell.output_hist
1193 output_hist = self.shell.output_hist
1192 for n in range(1,len(input_hist)-1):
1194 for n in range(1,len(input_hist)-1):
1193 log_write(input_hist[n].rstrip())
1195 log_write(input_hist[n].rstrip())
1194 if n in output_hist:
1196 if n in output_hist:
1195 log_write(repr(output_hist[n]),'output')
1197 log_write(repr(output_hist[n]),'output')
1196 else:
1198 else:
1197 logger.log_write(input_hist[1:])
1199 logger.log_write(input_hist[1:])
1198 if timestamp:
1200 if timestamp:
1199 # re-enable timestamping
1201 # re-enable timestamping
1200 logger.timestamp = True
1202 logger.timestamp = True
1201
1203
1202 print ('Activating auto-logging. '
1204 print ('Activating auto-logging. '
1203 'Current session state plus future input saved.')
1205 'Current session state plus future input saved.')
1204 logger.logstate()
1206 logger.logstate()
1205
1207
1206 def magic_logstop(self,parameter_s=''):
1208 def magic_logstop(self,parameter_s=''):
1207 """Fully stop logging and close log file.
1209 """Fully stop logging and close log file.
1208
1210
1209 In order to start logging again, a new %logstart call needs to be made,
1211 In order to start logging again, a new %logstart call needs to be made,
1210 possibly (though not necessarily) with a new filename, mode and other
1212 possibly (though not necessarily) with a new filename, mode and other
1211 options."""
1213 options."""
1212 self.logger.logstop()
1214 self.logger.logstop()
1213
1215
1214 def magic_logoff(self,parameter_s=''):
1216 def magic_logoff(self,parameter_s=''):
1215 """Temporarily stop logging.
1217 """Temporarily stop logging.
1216
1218
1217 You must have previously started logging."""
1219 You must have previously started logging."""
1218 self.shell.logger.switch_log(0)
1220 self.shell.logger.switch_log(0)
1219
1221
1220 def magic_logon(self,parameter_s=''):
1222 def magic_logon(self,parameter_s=''):
1221 """Restart logging.
1223 """Restart logging.
1222
1224
1223 This function is for restarting logging which you've temporarily
1225 This function is for restarting logging which you've temporarily
1224 stopped with %logoff. For starting logging for the first time, you
1226 stopped with %logoff. For starting logging for the first time, you
1225 must use the %logstart function, which allows you to specify an
1227 must use the %logstart function, which allows you to specify an
1226 optional log filename."""
1228 optional log filename."""
1227
1229
1228 self.shell.logger.switch_log(1)
1230 self.shell.logger.switch_log(1)
1229
1231
1230 def magic_logstate(self,parameter_s=''):
1232 def magic_logstate(self,parameter_s=''):
1231 """Print the status of the logging system."""
1233 """Print the status of the logging system."""
1232
1234
1233 self.shell.logger.logstate()
1235 self.shell.logger.logstate()
1234
1236
1235 def magic_pdb(self, parameter_s=''):
1237 def magic_pdb(self, parameter_s=''):
1236 """Control the automatic calling of the pdb interactive debugger.
1238 """Control the automatic calling of the pdb interactive debugger.
1237
1239
1238 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1240 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1239 argument it works as a toggle.
1241 argument it works as a toggle.
1240
1242
1241 When an exception is triggered, IPython can optionally call the
1243 When an exception is triggered, IPython can optionally call the
1242 interactive pdb debugger after the traceback printout. %pdb toggles
1244 interactive pdb debugger after the traceback printout. %pdb toggles
1243 this feature on and off.
1245 this feature on and off.
1244
1246
1245 The initial state of this feature is set in your ipythonrc
1247 The initial state of this feature is set in your ipythonrc
1246 configuration file (the variable is called 'pdb').
1248 configuration file (the variable is called 'pdb').
1247
1249
1248 If you want to just activate the debugger AFTER an exception has fired,
1250 If you want to just activate the debugger AFTER an exception has fired,
1249 without having to type '%pdb on' and rerunning your code, you can use
1251 without having to type '%pdb on' and rerunning your code, you can use
1250 the %debug magic."""
1252 the %debug magic."""
1251
1253
1252 par = parameter_s.strip().lower()
1254 par = parameter_s.strip().lower()
1253
1255
1254 if par:
1256 if par:
1255 try:
1257 try:
1256 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1258 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1257 except KeyError:
1259 except KeyError:
1258 print ('Incorrect argument. Use on/1, off/0, '
1260 print ('Incorrect argument. Use on/1, off/0, '
1259 'or nothing for a toggle.')
1261 'or nothing for a toggle.')
1260 return
1262 return
1261 else:
1263 else:
1262 # toggle
1264 # toggle
1263 new_pdb = not self.shell.call_pdb
1265 new_pdb = not self.shell.call_pdb
1264
1266
1265 # set on the shell
1267 # set on the shell
1266 self.shell.call_pdb = new_pdb
1268 self.shell.call_pdb = new_pdb
1267 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1269 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1268
1270
1269 def magic_debug(self, parameter_s=''):
1271 def magic_debug(self, parameter_s=''):
1270 """Activate the interactive debugger in post-mortem mode.
1272 """Activate the interactive debugger in post-mortem mode.
1271
1273
1272 If an exception has just occurred, this lets you inspect its stack
1274 If an exception has just occurred, this lets you inspect its stack
1273 frames interactively. Note that this will always work only on the last
1275 frames interactively. Note that this will always work only on the last
1274 traceback that occurred, so you must call this quickly after an
1276 traceback that occurred, so you must call this quickly after an
1275 exception that you wish to inspect has fired, because if another one
1277 exception that you wish to inspect has fired, because if another one
1276 occurs, it clobbers the previous one.
1278 occurs, it clobbers the previous one.
1277
1279
1278 If you want IPython to automatically do this on every exception, see
1280 If you want IPython to automatically do this on every exception, see
1279 the %pdb magic for more details.
1281 the %pdb magic for more details.
1280 """
1282 """
1281 self.shell.debugger(force=True)
1283 self.shell.debugger(force=True)
1282
1284
1283 @testdec.skip_doctest
1285 @testdec.skip_doctest
1284 def magic_prun(self, parameter_s ='',user_mode=1,
1286 def magic_prun(self, parameter_s ='',user_mode=1,
1285 opts=None,arg_lst=None,prog_ns=None):
1287 opts=None,arg_lst=None,prog_ns=None):
1286
1288
1287 """Run a statement through the python code profiler.
1289 """Run a statement through the python code profiler.
1288
1290
1289 Usage:
1291 Usage:
1290 %prun [options] statement
1292 %prun [options] statement
1291
1293
1292 The given statement (which doesn't require quote marks) is run via the
1294 The given statement (which doesn't require quote marks) is run via the
1293 python profiler in a manner similar to the profile.run() function.
1295 python profiler in a manner similar to the profile.run() function.
1294 Namespaces are internally managed to work correctly; profile.run
1296 Namespaces are internally managed to work correctly; profile.run
1295 cannot be used in IPython because it makes certain assumptions about
1297 cannot be used in IPython because it makes certain assumptions about
1296 namespaces which do not hold under IPython.
1298 namespaces which do not hold under IPython.
1297
1299
1298 Options:
1300 Options:
1299
1301
1300 -l <limit>: you can place restrictions on what or how much of the
1302 -l <limit>: you can place restrictions on what or how much of the
1301 profile gets printed. The limit value can be:
1303 profile gets printed. The limit value can be:
1302
1304
1303 * A string: only information for function names containing this string
1305 * A string: only information for function names containing this string
1304 is printed.
1306 is printed.
1305
1307
1306 * An integer: only these many lines are printed.
1308 * An integer: only these many lines are printed.
1307
1309
1308 * A float (between 0 and 1): this fraction of the report is printed
1310 * A float (between 0 and 1): this fraction of the report is printed
1309 (for example, use a limit of 0.4 to see the topmost 40% only).
1311 (for example, use a limit of 0.4 to see the topmost 40% only).
1310
1312
1311 You can combine several limits with repeated use of the option. For
1313 You can combine several limits with repeated use of the option. For
1312 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1314 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1313 information about class constructors.
1315 information about class constructors.
1314
1316
1315 -r: return the pstats.Stats object generated by the profiling. This
1317 -r: return the pstats.Stats object generated by the profiling. This
1316 object has all the information about the profile in it, and you can
1318 object has all the information about the profile in it, and you can
1317 later use it for further analysis or in other functions.
1319 later use it for further analysis or in other functions.
1318
1320
1319 -s <key>: sort profile by given key. You can provide more than one key
1321 -s <key>: sort profile by given key. You can provide more than one key
1320 by using the option several times: '-s key1 -s key2 -s key3...'. The
1322 by using the option several times: '-s key1 -s key2 -s key3...'. The
1321 default sorting key is 'time'.
1323 default sorting key is 'time'.
1322
1324
1323 The following is copied verbatim from the profile documentation
1325 The following is copied verbatim from the profile documentation
1324 referenced below:
1326 referenced below:
1325
1327
1326 When more than one key is provided, additional keys are used as
1328 When more than one key is provided, additional keys are used as
1327 secondary criteria when the there is equality in all keys selected
1329 secondary criteria when the there is equality in all keys selected
1328 before them.
1330 before them.
1329
1331
1330 Abbreviations can be used for any key names, as long as the
1332 Abbreviations can be used for any key names, as long as the
1331 abbreviation is unambiguous. The following are the keys currently
1333 abbreviation is unambiguous. The following are the keys currently
1332 defined:
1334 defined:
1333
1335
1334 Valid Arg Meaning
1336 Valid Arg Meaning
1335 "calls" call count
1337 "calls" call count
1336 "cumulative" cumulative time
1338 "cumulative" cumulative time
1337 "file" file name
1339 "file" file name
1338 "module" file name
1340 "module" file name
1339 "pcalls" primitive call count
1341 "pcalls" primitive call count
1340 "line" line number
1342 "line" line number
1341 "name" function name
1343 "name" function name
1342 "nfl" name/file/line
1344 "nfl" name/file/line
1343 "stdname" standard name
1345 "stdname" standard name
1344 "time" internal time
1346 "time" internal time
1345
1347
1346 Note that all sorts on statistics are in descending order (placing
1348 Note that all sorts on statistics are in descending order (placing
1347 most time consuming items first), where as name, file, and line number
1349 most time consuming items first), where as name, file, and line number
1348 searches are in ascending order (i.e., alphabetical). The subtle
1350 searches are in ascending order (i.e., alphabetical). The subtle
1349 distinction between "nfl" and "stdname" is that the standard name is a
1351 distinction between "nfl" and "stdname" is that the standard name is a
1350 sort of the name as printed, which means that the embedded line
1352 sort of the name as printed, which means that the embedded line
1351 numbers get compared in an odd way. For example, lines 3, 20, and 40
1353 numbers get compared in an odd way. For example, lines 3, 20, and 40
1352 would (if the file names were the same) appear in the string order
1354 would (if the file names were the same) appear in the string order
1353 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1355 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1354 line numbers. In fact, sort_stats("nfl") is the same as
1356 line numbers. In fact, sort_stats("nfl") is the same as
1355 sort_stats("name", "file", "line").
1357 sort_stats("name", "file", "line").
1356
1358
1357 -T <filename>: save profile results as shown on screen to a text
1359 -T <filename>: save profile results as shown on screen to a text
1358 file. The profile is still shown on screen.
1360 file. The profile is still shown on screen.
1359
1361
1360 -D <filename>: save (via dump_stats) profile statistics to given
1362 -D <filename>: save (via dump_stats) profile statistics to given
1361 filename. This data is in a format understod by the pstats module, and
1363 filename. This data is in a format understod by the pstats module, and
1362 is generated by a call to the dump_stats() method of profile
1364 is generated by a call to the dump_stats() method of profile
1363 objects. The profile is still shown on screen.
1365 objects. The profile is still shown on screen.
1364
1366
1365 If you want to run complete programs under the profiler's control, use
1367 If you want to run complete programs under the profiler's control, use
1366 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1368 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1367 contains profiler specific options as described here.
1369 contains profiler specific options as described here.
1368
1370
1369 You can read the complete documentation for the profile module with::
1371 You can read the complete documentation for the profile module with::
1370
1372
1371 In [1]: import profile; profile.help()
1373 In [1]: import profile; profile.help()
1372 """
1374 """
1373
1375
1374 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1376 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1375 # protect user quote marks
1377 # protect user quote marks
1376 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1378 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1377
1379
1378 if user_mode: # regular user call
1380 if user_mode: # regular user call
1379 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1381 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1380 list_all=1)
1382 list_all=1)
1381 namespace = self.shell.user_ns
1383 namespace = self.shell.user_ns
1382 else: # called to run a program by %run -p
1384 else: # called to run a program by %run -p
1383 try:
1385 try:
1384 filename = get_py_filename(arg_lst[0])
1386 filename = get_py_filename(arg_lst[0])
1385 except IOError,msg:
1387 except IOError,msg:
1386 error(msg)
1388 error(msg)
1387 return
1389 return
1388
1390
1389 arg_str = 'execfile(filename,prog_ns)'
1391 arg_str = 'execfile(filename,prog_ns)'
1390 namespace = locals()
1392 namespace = locals()
1391
1393
1392 opts.merge(opts_def)
1394 opts.merge(opts_def)
1393
1395
1394 prof = profile.Profile()
1396 prof = profile.Profile()
1395 try:
1397 try:
1396 prof = prof.runctx(arg_str,namespace,namespace)
1398 prof = prof.runctx(arg_str,namespace,namespace)
1397 sys_exit = ''
1399 sys_exit = ''
1398 except SystemExit:
1400 except SystemExit:
1399 sys_exit = """*** SystemExit exception caught in code being profiled."""
1401 sys_exit = """*** SystemExit exception caught in code being profiled."""
1400
1402
1401 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1403 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1402
1404
1403 lims = opts.l
1405 lims = opts.l
1404 if lims:
1406 if lims:
1405 lims = [] # rebuild lims with ints/floats/strings
1407 lims = [] # rebuild lims with ints/floats/strings
1406 for lim in opts.l:
1408 for lim in opts.l:
1407 try:
1409 try:
1408 lims.append(int(lim))
1410 lims.append(int(lim))
1409 except ValueError:
1411 except ValueError:
1410 try:
1412 try:
1411 lims.append(float(lim))
1413 lims.append(float(lim))
1412 except ValueError:
1414 except ValueError:
1413 lims.append(lim)
1415 lims.append(lim)
1414
1416
1415 # Trap output.
1417 # Trap output.
1416 stdout_trap = StringIO()
1418 stdout_trap = StringIO()
1417
1419
1418 if hasattr(stats,'stream'):
1420 if hasattr(stats,'stream'):
1419 # In newer versions of python, the stats object has a 'stream'
1421 # In newer versions of python, the stats object has a 'stream'
1420 # attribute to write into.
1422 # attribute to write into.
1421 stats.stream = stdout_trap
1423 stats.stream = stdout_trap
1422 stats.print_stats(*lims)
1424 stats.print_stats(*lims)
1423 else:
1425 else:
1424 # For older versions, we manually redirect stdout during printing
1426 # For older versions, we manually redirect stdout during printing
1425 sys_stdout = sys.stdout
1427 sys_stdout = sys.stdout
1426 try:
1428 try:
1427 sys.stdout = stdout_trap
1429 sys.stdout = stdout_trap
1428 stats.print_stats(*lims)
1430 stats.print_stats(*lims)
1429 finally:
1431 finally:
1430 sys.stdout = sys_stdout
1432 sys.stdout = sys_stdout
1431
1433
1432 output = stdout_trap.getvalue()
1434 output = stdout_trap.getvalue()
1433 output = output.rstrip()
1435 output = output.rstrip()
1434
1436
1435 page(output,screen_lines=self.shell.usable_screen_length)
1437 page(output,screen_lines=self.shell.usable_screen_length)
1436 print sys_exit,
1438 print sys_exit,
1437
1439
1438 dump_file = opts.D[0]
1440 dump_file = opts.D[0]
1439 text_file = opts.T[0]
1441 text_file = opts.T[0]
1440 if dump_file:
1442 if dump_file:
1441 prof.dump_stats(dump_file)
1443 prof.dump_stats(dump_file)
1442 print '\n*** Profile stats marshalled to file',\
1444 print '\n*** Profile stats marshalled to file',\
1443 `dump_file`+'.',sys_exit
1445 `dump_file`+'.',sys_exit
1444 if text_file:
1446 if text_file:
1445 pfile = file(text_file,'w')
1447 pfile = file(text_file,'w')
1446 pfile.write(output)
1448 pfile.write(output)
1447 pfile.close()
1449 pfile.close()
1448 print '\n*** Profile printout saved to text file',\
1450 print '\n*** Profile printout saved to text file',\
1449 `text_file`+'.',sys_exit
1451 `text_file`+'.',sys_exit
1450
1452
1451 if opts.has_key('r'):
1453 if opts.has_key('r'):
1452 return stats
1454 return stats
1453 else:
1455 else:
1454 return None
1456 return None
1455
1457
1456 @testdec.skip_doctest
1458 @testdec.skip_doctest
1457 def magic_run(self, parameter_s ='',runner=None,
1459 def magic_run(self, parameter_s ='',runner=None,
1458 file_finder=get_py_filename):
1460 file_finder=get_py_filename):
1459 """Run the named file inside IPython as a program.
1461 """Run the named file inside IPython as a program.
1460
1462
1461 Usage:\\
1463 Usage:\\
1462 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1464 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1463
1465
1464 Parameters after the filename are passed as command-line arguments to
1466 Parameters after the filename are passed as command-line arguments to
1465 the program (put in sys.argv). Then, control returns to IPython's
1467 the program (put in sys.argv). Then, control returns to IPython's
1466 prompt.
1468 prompt.
1467
1469
1468 This is similar to running at a system prompt:\\
1470 This is similar to running at a system prompt:\\
1469 $ python file args\\
1471 $ python file args\\
1470 but with the advantage of giving you IPython's tracebacks, and of
1472 but with the advantage of giving you IPython's tracebacks, and of
1471 loading all variables into your interactive namespace for further use
1473 loading all variables into your interactive namespace for further use
1472 (unless -p is used, see below).
1474 (unless -p is used, see below).
1473
1475
1474 The file is executed in a namespace initially consisting only of
1476 The file is executed in a namespace initially consisting only of
1475 __name__=='__main__' and sys.argv constructed as indicated. It thus
1477 __name__=='__main__' and sys.argv constructed as indicated. It thus
1476 sees its environment as if it were being run as a stand-alone program
1478 sees its environment as if it were being run as a stand-alone program
1477 (except for sharing global objects such as previously imported
1479 (except for sharing global objects such as previously imported
1478 modules). But after execution, the IPython interactive namespace gets
1480 modules). But after execution, the IPython interactive namespace gets
1479 updated with all variables defined in the program (except for __name__
1481 updated with all variables defined in the program (except for __name__
1480 and sys.argv). This allows for very convenient loading of code for
1482 and sys.argv). This allows for very convenient loading of code for
1481 interactive work, while giving each program a 'clean sheet' to run in.
1483 interactive work, while giving each program a 'clean sheet' to run in.
1482
1484
1483 Options:
1485 Options:
1484
1486
1485 -n: __name__ is NOT set to '__main__', but to the running file's name
1487 -n: __name__ is NOT set to '__main__', but to the running file's name
1486 without extension (as python does under import). This allows running
1488 without extension (as python does under import). This allows running
1487 scripts and reloading the definitions in them without calling code
1489 scripts and reloading the definitions in them without calling code
1488 protected by an ' if __name__ == "__main__" ' clause.
1490 protected by an ' if __name__ == "__main__" ' clause.
1489
1491
1490 -i: run the file in IPython's namespace instead of an empty one. This
1492 -i: run the file in IPython's namespace instead of an empty one. This
1491 is useful if you are experimenting with code written in a text editor
1493 is useful if you are experimenting with code written in a text editor
1492 which depends on variables defined interactively.
1494 which depends on variables defined interactively.
1493
1495
1494 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1496 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1495 being run. This is particularly useful if IPython is being used to
1497 being run. This is particularly useful if IPython is being used to
1496 run unittests, which always exit with a sys.exit() call. In such
1498 run unittests, which always exit with a sys.exit() call. In such
1497 cases you are interested in the output of the test results, not in
1499 cases you are interested in the output of the test results, not in
1498 seeing a traceback of the unittest module.
1500 seeing a traceback of the unittest module.
1499
1501
1500 -t: print timing information at the end of the run. IPython will give
1502 -t: print timing information at the end of the run. IPython will give
1501 you an estimated CPU time consumption for your script, which under
1503 you an estimated CPU time consumption for your script, which under
1502 Unix uses the resource module to avoid the wraparound problems of
1504 Unix uses the resource module to avoid the wraparound problems of
1503 time.clock(). Under Unix, an estimate of time spent on system tasks
1505 time.clock(). Under Unix, an estimate of time spent on system tasks
1504 is also given (for Windows platforms this is reported as 0.0).
1506 is also given (for Windows platforms this is reported as 0.0).
1505
1507
1506 If -t is given, an additional -N<N> option can be given, where <N>
1508 If -t is given, an additional -N<N> option can be given, where <N>
1507 must be an integer indicating how many times you want the script to
1509 must be an integer indicating how many times you want the script to
1508 run. The final timing report will include total and per run results.
1510 run. The final timing report will include total and per run results.
1509
1511
1510 For example (testing the script uniq_stable.py):
1512 For example (testing the script uniq_stable.py):
1511
1513
1512 In [1]: run -t uniq_stable
1514 In [1]: run -t uniq_stable
1513
1515
1514 IPython CPU timings (estimated):\\
1516 IPython CPU timings (estimated):\\
1515 User : 0.19597 s.\\
1517 User : 0.19597 s.\\
1516 System: 0.0 s.\\
1518 System: 0.0 s.\\
1517
1519
1518 In [2]: run -t -N5 uniq_stable
1520 In [2]: run -t -N5 uniq_stable
1519
1521
1520 IPython CPU timings (estimated):\\
1522 IPython CPU timings (estimated):\\
1521 Total runs performed: 5\\
1523 Total runs performed: 5\\
1522 Times : Total Per run\\
1524 Times : Total Per run\\
1523 User : 0.910862 s, 0.1821724 s.\\
1525 User : 0.910862 s, 0.1821724 s.\\
1524 System: 0.0 s, 0.0 s.
1526 System: 0.0 s, 0.0 s.
1525
1527
1526 -d: run your program under the control of pdb, the Python debugger.
1528 -d: run your program under the control of pdb, the Python debugger.
1527 This allows you to execute your program step by step, watch variables,
1529 This allows you to execute your program step by step, watch variables,
1528 etc. Internally, what IPython does is similar to calling:
1530 etc. Internally, what IPython does is similar to calling:
1529
1531
1530 pdb.run('execfile("YOURFILENAME")')
1532 pdb.run('execfile("YOURFILENAME")')
1531
1533
1532 with a breakpoint set on line 1 of your file. You can change the line
1534 with a breakpoint set on line 1 of your file. You can change the line
1533 number for this automatic breakpoint to be <N> by using the -bN option
1535 number for this automatic breakpoint to be <N> by using the -bN option
1534 (where N must be an integer). For example:
1536 (where N must be an integer). For example:
1535
1537
1536 %run -d -b40 myscript
1538 %run -d -b40 myscript
1537
1539
1538 will set the first breakpoint at line 40 in myscript.py. Note that
1540 will set the first breakpoint at line 40 in myscript.py. Note that
1539 the first breakpoint must be set on a line which actually does
1541 the first breakpoint must be set on a line which actually does
1540 something (not a comment or docstring) for it to stop execution.
1542 something (not a comment or docstring) for it to stop execution.
1541
1543
1542 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1544 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1543 first enter 'c' (without qoutes) to start execution up to the first
1545 first enter 'c' (without qoutes) to start execution up to the first
1544 breakpoint.
1546 breakpoint.
1545
1547
1546 Entering 'help' gives information about the use of the debugger. You
1548 Entering 'help' gives information about the use of the debugger. You
1547 can easily see pdb's full documentation with "import pdb;pdb.help()"
1549 can easily see pdb's full documentation with "import pdb;pdb.help()"
1548 at a prompt.
1550 at a prompt.
1549
1551
1550 -p: run program under the control of the Python profiler module (which
1552 -p: run program under the control of the Python profiler module (which
1551 prints a detailed report of execution times, function calls, etc).
1553 prints a detailed report of execution times, function calls, etc).
1552
1554
1553 You can pass other options after -p which affect the behavior of the
1555 You can pass other options after -p which affect the behavior of the
1554 profiler itself. See the docs for %prun for details.
1556 profiler itself. See the docs for %prun for details.
1555
1557
1556 In this mode, the program's variables do NOT propagate back to the
1558 In this mode, the program's variables do NOT propagate back to the
1557 IPython interactive namespace (because they remain in the namespace
1559 IPython interactive namespace (because they remain in the namespace
1558 where the profiler executes them).
1560 where the profiler executes them).
1559
1561
1560 Internally this triggers a call to %prun, see its documentation for
1562 Internally this triggers a call to %prun, see its documentation for
1561 details on the options available specifically for profiling.
1563 details on the options available specifically for profiling.
1562
1564
1563 There is one special usage for which the text above doesn't apply:
1565 There is one special usage for which the text above doesn't apply:
1564 if the filename ends with .ipy, the file is run as ipython script,
1566 if the filename ends with .ipy, the file is run as ipython script,
1565 just as if the commands were written on IPython prompt.
1567 just as if the commands were written on IPython prompt.
1566 """
1568 """
1567
1569
1568 # get arguments and set sys.argv for program to be run.
1570 # get arguments and set sys.argv for program to be run.
1569 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1571 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1570 mode='list',list_all=1)
1572 mode='list',list_all=1)
1571
1573
1572 try:
1574 try:
1573 filename = file_finder(arg_lst[0])
1575 filename = file_finder(arg_lst[0])
1574 except IndexError:
1576 except IndexError:
1575 warn('you must provide at least a filename.')
1577 warn('you must provide at least a filename.')
1576 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1578 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1577 return
1579 return
1578 except IOError,msg:
1580 except IOError,msg:
1579 error(msg)
1581 error(msg)
1580 return
1582 return
1581
1583
1582 if filename.lower().endswith('.ipy'):
1584 if filename.lower().endswith('.ipy'):
1583 self.shell.safe_execfile_ipy(filename)
1585 self.shell.safe_execfile_ipy(filename)
1584 return
1586 return
1585
1587
1586 # Control the response to exit() calls made by the script being run
1588 # Control the response to exit() calls made by the script being run
1587 exit_ignore = opts.has_key('e')
1589 exit_ignore = opts.has_key('e')
1588
1590
1589 # Make sure that the running script gets a proper sys.argv as if it
1591 # Make sure that the running script gets a proper sys.argv as if it
1590 # were run from a system shell.
1592 # were run from a system shell.
1591 save_argv = sys.argv # save it for later restoring
1593 save_argv = sys.argv # save it for later restoring
1592 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1594 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1593
1595
1594 if opts.has_key('i'):
1596 if opts.has_key('i'):
1595 # Run in user's interactive namespace
1597 # Run in user's interactive namespace
1596 prog_ns = self.shell.user_ns
1598 prog_ns = self.shell.user_ns
1597 __name__save = self.shell.user_ns['__name__']
1599 __name__save = self.shell.user_ns['__name__']
1598 prog_ns['__name__'] = '__main__'
1600 prog_ns['__name__'] = '__main__'
1599 main_mod = self.shell.new_main_mod(prog_ns)
1601 main_mod = self.shell.new_main_mod(prog_ns)
1600 else:
1602 else:
1601 # Run in a fresh, empty namespace
1603 # Run in a fresh, empty namespace
1602 if opts.has_key('n'):
1604 if opts.has_key('n'):
1603 name = os.path.splitext(os.path.basename(filename))[0]
1605 name = os.path.splitext(os.path.basename(filename))[0]
1604 else:
1606 else:
1605 name = '__main__'
1607 name = '__main__'
1606
1608
1607 main_mod = self.shell.new_main_mod()
1609 main_mod = self.shell.new_main_mod()
1608 prog_ns = main_mod.__dict__
1610 prog_ns = main_mod.__dict__
1609 prog_ns['__name__'] = name
1611 prog_ns['__name__'] = name
1610
1612
1611 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1613 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1612 # set the __file__ global in the script's namespace
1614 # set the __file__ global in the script's namespace
1613 prog_ns['__file__'] = filename
1615 prog_ns['__file__'] = filename
1614
1616
1615 # pickle fix. See iplib for an explanation. But we need to make sure
1617 # pickle fix. See iplib for an explanation. But we need to make sure
1616 # that, if we overwrite __main__, we replace it at the end
1618 # that, if we overwrite __main__, we replace it at the end
1617 main_mod_name = prog_ns['__name__']
1619 main_mod_name = prog_ns['__name__']
1618
1620
1619 if main_mod_name == '__main__':
1621 if main_mod_name == '__main__':
1620 restore_main = sys.modules['__main__']
1622 restore_main = sys.modules['__main__']
1621 else:
1623 else:
1622 restore_main = False
1624 restore_main = False
1623
1625
1624 # This needs to be undone at the end to prevent holding references to
1626 # This needs to be undone at the end to prevent holding references to
1625 # every single object ever created.
1627 # every single object ever created.
1626 sys.modules[main_mod_name] = main_mod
1628 sys.modules[main_mod_name] = main_mod
1627
1629
1628 stats = None
1630 stats = None
1629 try:
1631 try:
1630 self.shell.savehist()
1632 self.shell.savehist()
1631
1633
1632 if opts.has_key('p'):
1634 if opts.has_key('p'):
1633 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1635 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1634 else:
1636 else:
1635 if opts.has_key('d'):
1637 if opts.has_key('d'):
1636 deb = debugger.Pdb(self.shell.colors)
1638 deb = debugger.Pdb(self.shell.colors)
1637 # reset Breakpoint state, which is moronically kept
1639 # reset Breakpoint state, which is moronically kept
1638 # in a class
1640 # in a class
1639 bdb.Breakpoint.next = 1
1641 bdb.Breakpoint.next = 1
1640 bdb.Breakpoint.bplist = {}
1642 bdb.Breakpoint.bplist = {}
1641 bdb.Breakpoint.bpbynumber = [None]
1643 bdb.Breakpoint.bpbynumber = [None]
1642 # Set an initial breakpoint to stop execution
1644 # Set an initial breakpoint to stop execution
1643 maxtries = 10
1645 maxtries = 10
1644 bp = int(opts.get('b',[1])[0])
1646 bp = int(opts.get('b',[1])[0])
1645 checkline = deb.checkline(filename,bp)
1647 checkline = deb.checkline(filename,bp)
1646 if not checkline:
1648 if not checkline:
1647 for bp in range(bp+1,bp+maxtries+1):
1649 for bp in range(bp+1,bp+maxtries+1):
1648 if deb.checkline(filename,bp):
1650 if deb.checkline(filename,bp):
1649 break
1651 break
1650 else:
1652 else:
1651 msg = ("\nI failed to find a valid line to set "
1653 msg = ("\nI failed to find a valid line to set "
1652 "a breakpoint\n"
1654 "a breakpoint\n"
1653 "after trying up to line: %s.\n"
1655 "after trying up to line: %s.\n"
1654 "Please set a valid breakpoint manually "
1656 "Please set a valid breakpoint manually "
1655 "with the -b option." % bp)
1657 "with the -b option." % bp)
1656 error(msg)
1658 error(msg)
1657 return
1659 return
1658 # if we find a good linenumber, set the breakpoint
1660 # if we find a good linenumber, set the breakpoint
1659 deb.do_break('%s:%s' % (filename,bp))
1661 deb.do_break('%s:%s' % (filename,bp))
1660 # Start file run
1662 # Start file run
1661 print "NOTE: Enter 'c' at the",
1663 print "NOTE: Enter 'c' at the",
1662 print "%s prompt to start your script." % deb.prompt
1664 print "%s prompt to start your script." % deb.prompt
1663 try:
1665 try:
1664 deb.run('execfile("%s")' % filename,prog_ns)
1666 deb.run('execfile("%s")' % filename,prog_ns)
1665
1667
1666 except:
1668 except:
1667 etype, value, tb = sys.exc_info()
1669 etype, value, tb = sys.exc_info()
1668 # Skip three frames in the traceback: the %run one,
1670 # Skip three frames in the traceback: the %run one,
1669 # one inside bdb.py, and the command-line typed by the
1671 # one inside bdb.py, and the command-line typed by the
1670 # user (run by exec in pdb itself).
1672 # user (run by exec in pdb itself).
1671 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1673 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1672 else:
1674 else:
1673 if runner is None:
1675 if runner is None:
1674 runner = self.shell.safe_execfile
1676 runner = self.shell.safe_execfile
1675 if opts.has_key('t'):
1677 if opts.has_key('t'):
1676 # timed execution
1678 # timed execution
1677 try:
1679 try:
1678 nruns = int(opts['N'][0])
1680 nruns = int(opts['N'][0])
1679 if nruns < 1:
1681 if nruns < 1:
1680 error('Number of runs must be >=1')
1682 error('Number of runs must be >=1')
1681 return
1683 return
1682 except (KeyError):
1684 except (KeyError):
1683 nruns = 1
1685 nruns = 1
1684 if nruns == 1:
1686 if nruns == 1:
1685 t0 = clock2()
1687 t0 = clock2()
1686 runner(filename,prog_ns,prog_ns,
1688 runner(filename,prog_ns,prog_ns,
1687 exit_ignore=exit_ignore)
1689 exit_ignore=exit_ignore)
1688 t1 = clock2()
1690 t1 = clock2()
1689 t_usr = t1[0]-t0[0]
1691 t_usr = t1[0]-t0[0]
1690 t_sys = t1[1]-t0[1]
1692 t_sys = t1[1]-t0[1]
1691 print "\nIPython CPU timings (estimated):"
1693 print "\nIPython CPU timings (estimated):"
1692 print " User : %10s s." % t_usr
1694 print " User : %10s s." % t_usr
1693 print " System: %10s s." % t_sys
1695 print " System: %10s s." % t_sys
1694 else:
1696 else:
1695 runs = range(nruns)
1697 runs = range(nruns)
1696 t0 = clock2()
1698 t0 = clock2()
1697 for nr in runs:
1699 for nr in runs:
1698 runner(filename,prog_ns,prog_ns,
1700 runner(filename,prog_ns,prog_ns,
1699 exit_ignore=exit_ignore)
1701 exit_ignore=exit_ignore)
1700 t1 = clock2()
1702 t1 = clock2()
1701 t_usr = t1[0]-t0[0]
1703 t_usr = t1[0]-t0[0]
1702 t_sys = t1[1]-t0[1]
1704 t_sys = t1[1]-t0[1]
1703 print "\nIPython CPU timings (estimated):"
1705 print "\nIPython CPU timings (estimated):"
1704 print "Total runs performed:",nruns
1706 print "Total runs performed:",nruns
1705 print " Times : %10s %10s" % ('Total','Per run')
1707 print " Times : %10s %10s" % ('Total','Per run')
1706 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1708 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1707 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1709 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1708
1710
1709 else:
1711 else:
1710 # regular execution
1712 # regular execution
1711 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1713 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1712
1714
1713 if opts.has_key('i'):
1715 if opts.has_key('i'):
1714 self.shell.user_ns['__name__'] = __name__save
1716 self.shell.user_ns['__name__'] = __name__save
1715 else:
1717 else:
1716 # The shell MUST hold a reference to prog_ns so after %run
1718 # The shell MUST hold a reference to prog_ns so after %run
1717 # exits, the python deletion mechanism doesn't zero it out
1719 # exits, the python deletion mechanism doesn't zero it out
1718 # (leaving dangling references).
1720 # (leaving dangling references).
1719 self.shell.cache_main_mod(prog_ns,filename)
1721 self.shell.cache_main_mod(prog_ns,filename)
1720 # update IPython interactive namespace
1722 # update IPython interactive namespace
1721
1723
1722 # Some forms of read errors on the file may mean the
1724 # Some forms of read errors on the file may mean the
1723 # __name__ key was never set; using pop we don't have to
1725 # __name__ key was never set; using pop we don't have to
1724 # worry about a possible KeyError.
1726 # worry about a possible KeyError.
1725 prog_ns.pop('__name__', None)
1727 prog_ns.pop('__name__', None)
1726
1728
1727 self.shell.user_ns.update(prog_ns)
1729 self.shell.user_ns.update(prog_ns)
1728 finally:
1730 finally:
1729 # It's a bit of a mystery why, but __builtins__ can change from
1731 # It's a bit of a mystery why, but __builtins__ can change from
1730 # being a module to becoming a dict missing some key data after
1732 # being a module to becoming a dict missing some key data after
1731 # %run. As best I can see, this is NOT something IPython is doing
1733 # %run. As best I can see, this is NOT something IPython is doing
1732 # at all, and similar problems have been reported before:
1734 # at all, and similar problems have been reported before:
1733 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1735 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1734 # Since this seems to be done by the interpreter itself, the best
1736 # Since this seems to be done by the interpreter itself, the best
1735 # we can do is to at least restore __builtins__ for the user on
1737 # we can do is to at least restore __builtins__ for the user on
1736 # exit.
1738 # exit.
1737 self.shell.user_ns['__builtins__'] = __builtin__
1739 self.shell.user_ns['__builtins__'] = __builtin__
1738
1740
1739 # Ensure key global structures are restored
1741 # Ensure key global structures are restored
1740 sys.argv = save_argv
1742 sys.argv = save_argv
1741 if restore_main:
1743 if restore_main:
1742 sys.modules['__main__'] = restore_main
1744 sys.modules['__main__'] = restore_main
1743 else:
1745 else:
1744 # Remove from sys.modules the reference to main_mod we'd
1746 # Remove from sys.modules the reference to main_mod we'd
1745 # added. Otherwise it will trap references to objects
1747 # added. Otherwise it will trap references to objects
1746 # contained therein.
1748 # contained therein.
1747 del sys.modules[main_mod_name]
1749 del sys.modules[main_mod_name]
1748
1750
1749 self.shell.reloadhist()
1751 self.shell.reloadhist()
1750
1752
1751 return stats
1753 return stats
1752
1754
1753 @testdec.skip_doctest
1755 @testdec.skip_doctest
1754 def magic_timeit(self, parameter_s =''):
1756 def magic_timeit(self, parameter_s =''):
1755 """Time execution of a Python statement or expression
1757 """Time execution of a Python statement or expression
1756
1758
1757 Usage:\\
1759 Usage:\\
1758 %timeit [-n<N> -r<R> [-t|-c]] statement
1760 %timeit [-n<N> -r<R> [-t|-c]] statement
1759
1761
1760 Time execution of a Python statement or expression using the timeit
1762 Time execution of a Python statement or expression using the timeit
1761 module.
1763 module.
1762
1764
1763 Options:
1765 Options:
1764 -n<N>: execute the given statement <N> times in a loop. If this value
1766 -n<N>: execute the given statement <N> times in a loop. If this value
1765 is not given, a fitting value is chosen.
1767 is not given, a fitting value is chosen.
1766
1768
1767 -r<R>: repeat the loop iteration <R> times and take the best result.
1769 -r<R>: repeat the loop iteration <R> times and take the best result.
1768 Default: 3
1770 Default: 3
1769
1771
1770 -t: use time.time to measure the time, which is the default on Unix.
1772 -t: use time.time to measure the time, which is the default on Unix.
1771 This function measures wall time.
1773 This function measures wall time.
1772
1774
1773 -c: use time.clock to measure the time, which is the default on
1775 -c: use time.clock to measure the time, which is the default on
1774 Windows and measures wall time. On Unix, resource.getrusage is used
1776 Windows and measures wall time. On Unix, resource.getrusage is used
1775 instead and returns the CPU user time.
1777 instead and returns the CPU user time.
1776
1778
1777 -p<P>: use a precision of <P> digits to display the timing result.
1779 -p<P>: use a precision of <P> digits to display the timing result.
1778 Default: 3
1780 Default: 3
1779
1781
1780
1782
1781 Examples:
1783 Examples:
1782
1784
1783 In [1]: %timeit pass
1785 In [1]: %timeit pass
1784 10000000 loops, best of 3: 53.3 ns per loop
1786 10000000 loops, best of 3: 53.3 ns per loop
1785
1787
1786 In [2]: u = None
1788 In [2]: u = None
1787
1789
1788 In [3]: %timeit u is None
1790 In [3]: %timeit u is None
1789 10000000 loops, best of 3: 184 ns per loop
1791 10000000 loops, best of 3: 184 ns per loop
1790
1792
1791 In [4]: %timeit -r 4 u == None
1793 In [4]: %timeit -r 4 u == None
1792 1000000 loops, best of 4: 242 ns per loop
1794 1000000 loops, best of 4: 242 ns per loop
1793
1795
1794 In [5]: import time
1796 In [5]: import time
1795
1797
1796 In [6]: %timeit -n1 time.sleep(2)
1798 In [6]: %timeit -n1 time.sleep(2)
1797 1 loops, best of 3: 2 s per loop
1799 1 loops, best of 3: 2 s per loop
1798
1800
1799
1801
1800 The times reported by %timeit will be slightly higher than those
1802 The times reported by %timeit will be slightly higher than those
1801 reported by the timeit.py script when variables are accessed. This is
1803 reported by the timeit.py script when variables are accessed. This is
1802 due to the fact that %timeit executes the statement in the namespace
1804 due to the fact that %timeit executes the statement in the namespace
1803 of the shell, compared with timeit.py, which uses a single setup
1805 of the shell, compared with timeit.py, which uses a single setup
1804 statement to import function or create variables. Generally, the bias
1806 statement to import function or create variables. Generally, the bias
1805 does not matter as long as results from timeit.py are not mixed with
1807 does not matter as long as results from timeit.py are not mixed with
1806 those from %timeit."""
1808 those from %timeit."""
1807
1809
1808 import timeit
1810 import timeit
1809 import math
1811 import math
1810
1812
1811 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1813 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1812 # certain terminals. Until we figure out a robust way of
1814 # certain terminals. Until we figure out a robust way of
1813 # auto-detecting if the terminal can deal with it, use plain 'us' for
1815 # auto-detecting if the terminal can deal with it, use plain 'us' for
1814 # microseconds. I am really NOT happy about disabling the proper
1816 # microseconds. I am really NOT happy about disabling the proper
1815 # 'micro' prefix, but crashing is worse... If anyone knows what the
1817 # 'micro' prefix, but crashing is worse... If anyone knows what the
1816 # right solution for this is, I'm all ears...
1818 # right solution for this is, I'm all ears...
1817 #
1819 #
1818 # Note: using
1820 # Note: using
1819 #
1821 #
1820 # s = u'\xb5'
1822 # s = u'\xb5'
1821 # s.encode(sys.getdefaultencoding())
1823 # s.encode(sys.getdefaultencoding())
1822 #
1824 #
1823 # is not sufficient, as I've seen terminals where that fails but
1825 # is not sufficient, as I've seen terminals where that fails but
1824 # print s
1826 # print s
1825 #
1827 #
1826 # succeeds
1828 # succeeds
1827 #
1829 #
1828 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1830 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1829
1831
1830 #units = [u"s", u"ms",u'\xb5',"ns"]
1832 #units = [u"s", u"ms",u'\xb5',"ns"]
1831 units = [u"s", u"ms",u'us',"ns"]
1833 units = [u"s", u"ms",u'us',"ns"]
1832
1834
1833 scaling = [1, 1e3, 1e6, 1e9]
1835 scaling = [1, 1e3, 1e6, 1e9]
1834
1836
1835 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1837 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1836 posix=False)
1838 posix=False)
1837 if stmt == "":
1839 if stmt == "":
1838 return
1840 return
1839 timefunc = timeit.default_timer
1841 timefunc = timeit.default_timer
1840 number = int(getattr(opts, "n", 0))
1842 number = int(getattr(opts, "n", 0))
1841 repeat = int(getattr(opts, "r", timeit.default_repeat))
1843 repeat = int(getattr(opts, "r", timeit.default_repeat))
1842 precision = int(getattr(opts, "p", 3))
1844 precision = int(getattr(opts, "p", 3))
1843 if hasattr(opts, "t"):
1845 if hasattr(opts, "t"):
1844 timefunc = time.time
1846 timefunc = time.time
1845 if hasattr(opts, "c"):
1847 if hasattr(opts, "c"):
1846 timefunc = clock
1848 timefunc = clock
1847
1849
1848 timer = timeit.Timer(timer=timefunc)
1850 timer = timeit.Timer(timer=timefunc)
1849 # this code has tight coupling to the inner workings of timeit.Timer,
1851 # this code has tight coupling to the inner workings of timeit.Timer,
1850 # but is there a better way to achieve that the code stmt has access
1852 # but is there a better way to achieve that the code stmt has access
1851 # to the shell namespace?
1853 # to the shell namespace?
1852
1854
1853 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1855 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1854 'setup': "pass"}
1856 'setup': "pass"}
1855 # Track compilation time so it can be reported if too long
1857 # Track compilation time so it can be reported if too long
1856 # Minimum time above which compilation time will be reported
1858 # Minimum time above which compilation time will be reported
1857 tc_min = 0.1
1859 tc_min = 0.1
1858
1860
1859 t0 = clock()
1861 t0 = clock()
1860 code = compile(src, "<magic-timeit>", "exec")
1862 code = compile(src, "<magic-timeit>", "exec")
1861 tc = clock()-t0
1863 tc = clock()-t0
1862
1864
1863 ns = {}
1865 ns = {}
1864 exec code in self.shell.user_ns, ns
1866 exec code in self.shell.user_ns, ns
1865 timer.inner = ns["inner"]
1867 timer.inner = ns["inner"]
1866
1868
1867 if number == 0:
1869 if number == 0:
1868 # determine number so that 0.2 <= total time < 2.0
1870 # determine number so that 0.2 <= total time < 2.0
1869 number = 1
1871 number = 1
1870 for i in range(1, 10):
1872 for i in range(1, 10):
1871 if timer.timeit(number) >= 0.2:
1873 if timer.timeit(number) >= 0.2:
1872 break
1874 break
1873 number *= 10
1875 number *= 10
1874
1876
1875 best = min(timer.repeat(repeat, number)) / number
1877 best = min(timer.repeat(repeat, number)) / number
1876
1878
1877 if best > 0.0:
1879 if best > 0.0:
1878 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1880 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1879 else:
1881 else:
1880 order = 3
1882 order = 3
1881 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1883 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1882 precision,
1884 precision,
1883 best * scaling[order],
1885 best * scaling[order],
1884 units[order])
1886 units[order])
1885 if tc > tc_min:
1887 if tc > tc_min:
1886 print "Compiler time: %.2f s" % tc
1888 print "Compiler time: %.2f s" % tc
1887
1889
1888 @testdec.skip_doctest
1890 @testdec.skip_doctest
1889 def magic_time(self,parameter_s = ''):
1891 def magic_time(self,parameter_s = ''):
1890 """Time execution of a Python statement or expression.
1892 """Time execution of a Python statement or expression.
1891
1893
1892 The CPU and wall clock times are printed, and the value of the
1894 The CPU and wall clock times are printed, and the value of the
1893 expression (if any) is returned. Note that under Win32, system time
1895 expression (if any) is returned. Note that under Win32, system time
1894 is always reported as 0, since it can not be measured.
1896 is always reported as 0, since it can not be measured.
1895
1897
1896 This function provides very basic timing functionality. In Python
1898 This function provides very basic timing functionality. In Python
1897 2.3, the timeit module offers more control and sophistication, so this
1899 2.3, the timeit module offers more control and sophistication, so this
1898 could be rewritten to use it (patches welcome).
1900 could be rewritten to use it (patches welcome).
1899
1901
1900 Some examples:
1902 Some examples:
1901
1903
1902 In [1]: time 2**128
1904 In [1]: time 2**128
1903 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1905 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1904 Wall time: 0.00
1906 Wall time: 0.00
1905 Out[1]: 340282366920938463463374607431768211456L
1907 Out[1]: 340282366920938463463374607431768211456L
1906
1908
1907 In [2]: n = 1000000
1909 In [2]: n = 1000000
1908
1910
1909 In [3]: time sum(range(n))
1911 In [3]: time sum(range(n))
1910 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1912 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1911 Wall time: 1.37
1913 Wall time: 1.37
1912 Out[3]: 499999500000L
1914 Out[3]: 499999500000L
1913
1915
1914 In [4]: time print 'hello world'
1916 In [4]: time print 'hello world'
1915 hello world
1917 hello world
1916 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1917 Wall time: 0.00
1919 Wall time: 0.00
1918
1920
1919 Note that the time needed by Python to compile the given expression
1921 Note that the time needed by Python to compile the given expression
1920 will be reported if it is more than 0.1s. In this example, the
1922 will be reported if it is more than 0.1s. In this example, the
1921 actual exponentiation is done by Python at compilation time, so while
1923 actual exponentiation is done by Python at compilation time, so while
1922 the expression can take a noticeable amount of time to compute, that
1924 the expression can take a noticeable amount of time to compute, that
1923 time is purely due to the compilation:
1925 time is purely due to the compilation:
1924
1926
1925 In [5]: time 3**9999;
1927 In [5]: time 3**9999;
1926 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1928 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1927 Wall time: 0.00 s
1929 Wall time: 0.00 s
1928
1930
1929 In [6]: time 3**999999;
1931 In [6]: time 3**999999;
1930 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1932 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1931 Wall time: 0.00 s
1933 Wall time: 0.00 s
1932 Compiler : 0.78 s
1934 Compiler : 0.78 s
1933 """
1935 """
1934
1936
1935 # fail immediately if the given expression can't be compiled
1937 # fail immediately if the given expression can't be compiled
1936
1938
1937 expr = self.shell.prefilter(parameter_s,False)
1939 expr = self.shell.prefilter(parameter_s,False)
1938
1940
1939 # Minimum time above which compilation time will be reported
1941 # Minimum time above which compilation time will be reported
1940 tc_min = 0.1
1942 tc_min = 0.1
1941
1943
1942 try:
1944 try:
1943 mode = 'eval'
1945 mode = 'eval'
1944 t0 = clock()
1946 t0 = clock()
1945 code = compile(expr,'<timed eval>',mode)
1947 code = compile(expr,'<timed eval>',mode)
1946 tc = clock()-t0
1948 tc = clock()-t0
1947 except SyntaxError:
1949 except SyntaxError:
1948 mode = 'exec'
1950 mode = 'exec'
1949 t0 = clock()
1951 t0 = clock()
1950 code = compile(expr,'<timed exec>',mode)
1952 code = compile(expr,'<timed exec>',mode)
1951 tc = clock()-t0
1953 tc = clock()-t0
1952 # skew measurement as little as possible
1954 # skew measurement as little as possible
1953 glob = self.shell.user_ns
1955 glob = self.shell.user_ns
1954 clk = clock2
1956 clk = clock2
1955 wtime = time.time
1957 wtime = time.time
1956 # time execution
1958 # time execution
1957 wall_st = wtime()
1959 wall_st = wtime()
1958 if mode=='eval':
1960 if mode=='eval':
1959 st = clk()
1961 st = clk()
1960 out = eval(code,glob)
1962 out = eval(code,glob)
1961 end = clk()
1963 end = clk()
1962 else:
1964 else:
1963 st = clk()
1965 st = clk()
1964 exec code in glob
1966 exec code in glob
1965 end = clk()
1967 end = clk()
1966 out = None
1968 out = None
1967 wall_end = wtime()
1969 wall_end = wtime()
1968 # Compute actual times and report
1970 # Compute actual times and report
1969 wall_time = wall_end-wall_st
1971 wall_time = wall_end-wall_st
1970 cpu_user = end[0]-st[0]
1972 cpu_user = end[0]-st[0]
1971 cpu_sys = end[1]-st[1]
1973 cpu_sys = end[1]-st[1]
1972 cpu_tot = cpu_user+cpu_sys
1974 cpu_tot = cpu_user+cpu_sys
1973 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1975 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1974 (cpu_user,cpu_sys,cpu_tot)
1976 (cpu_user,cpu_sys,cpu_tot)
1975 print "Wall time: %.2f s" % wall_time
1977 print "Wall time: %.2f s" % wall_time
1976 if tc > tc_min:
1978 if tc > tc_min:
1977 print "Compiler : %.2f s" % tc
1979 print "Compiler : %.2f s" % tc
1978 return out
1980 return out
1979
1981
1980 @testdec.skip_doctest
1982 @testdec.skip_doctest
1981 def magic_macro(self,parameter_s = ''):
1983 def magic_macro(self,parameter_s = ''):
1982 """Define a set of input lines as a macro for future re-execution.
1984 """Define a set of input lines as a macro for future re-execution.
1983
1985
1984 Usage:\\
1986 Usage:\\
1985 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1987 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1986
1988
1987 Options:
1989 Options:
1988
1990
1989 -r: use 'raw' input. By default, the 'processed' history is used,
1991 -r: use 'raw' input. By default, the 'processed' history is used,
1990 so that magics are loaded in their transformed version to valid
1992 so that magics are loaded in their transformed version to valid
1991 Python. If this option is given, the raw input as typed as the
1993 Python. If this option is given, the raw input as typed as the
1992 command line is used instead.
1994 command line is used instead.
1993
1995
1994 This will define a global variable called `name` which is a string
1996 This will define a global variable called `name` which is a string
1995 made of joining the slices and lines you specify (n1,n2,... numbers
1997 made of joining the slices and lines you specify (n1,n2,... numbers
1996 above) from your input history into a single string. This variable
1998 above) from your input history into a single string. This variable
1997 acts like an automatic function which re-executes those lines as if
1999 acts like an automatic function which re-executes those lines as if
1998 you had typed them. You just type 'name' at the prompt and the code
2000 you had typed them. You just type 'name' at the prompt and the code
1999 executes.
2001 executes.
2000
2002
2001 The notation for indicating number ranges is: n1-n2 means 'use line
2003 The notation for indicating number ranges is: n1-n2 means 'use line
2002 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2004 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2003 using the lines numbered 5,6 and 7.
2005 using the lines numbered 5,6 and 7.
2004
2006
2005 Note: as a 'hidden' feature, you can also use traditional python slice
2007 Note: as a 'hidden' feature, you can also use traditional python slice
2006 notation, where N:M means numbers N through M-1.
2008 notation, where N:M means numbers N through M-1.
2007
2009
2008 For example, if your history contains (%hist prints it):
2010 For example, if your history contains (%hist prints it):
2009
2011
2010 44: x=1
2012 44: x=1
2011 45: y=3
2013 45: y=3
2012 46: z=x+y
2014 46: z=x+y
2013 47: print x
2015 47: print x
2014 48: a=5
2016 48: a=5
2015 49: print 'x',x,'y',y
2017 49: print 'x',x,'y',y
2016
2018
2017 you can create a macro with lines 44 through 47 (included) and line 49
2019 you can create a macro with lines 44 through 47 (included) and line 49
2018 called my_macro with:
2020 called my_macro with:
2019
2021
2020 In [55]: %macro my_macro 44-47 49
2022 In [55]: %macro my_macro 44-47 49
2021
2023
2022 Now, typing `my_macro` (without quotes) will re-execute all this code
2024 Now, typing `my_macro` (without quotes) will re-execute all this code
2023 in one pass.
2025 in one pass.
2024
2026
2025 You don't need to give the line-numbers in order, and any given line
2027 You don't need to give the line-numbers in order, and any given line
2026 number can appear multiple times. You can assemble macros with any
2028 number can appear multiple times. You can assemble macros with any
2027 lines from your input history in any order.
2029 lines from your input history in any order.
2028
2030
2029 The macro is a simple object which holds its value in an attribute,
2031 The macro is a simple object which holds its value in an attribute,
2030 but IPython's display system checks for macros and executes them as
2032 but IPython's display system checks for macros and executes them as
2031 code instead of printing them when you type their name.
2033 code instead of printing them when you type their name.
2032
2034
2033 You can view a macro's contents by explicitly printing it with:
2035 You can view a macro's contents by explicitly printing it with:
2034
2036
2035 'print macro_name'.
2037 'print macro_name'.
2036
2038
2037 For one-off cases which DON'T contain magic function calls in them you
2039 For one-off cases which DON'T contain magic function calls in them you
2038 can obtain similar results by explicitly executing slices from your
2040 can obtain similar results by explicitly executing slices from your
2039 input history with:
2041 input history with:
2040
2042
2041 In [60]: exec In[44:48]+In[49]"""
2043 In [60]: exec In[44:48]+In[49]"""
2042
2044
2043 opts,args = self.parse_options(parameter_s,'r',mode='list')
2045 opts,args = self.parse_options(parameter_s,'r',mode='list')
2044 if not args:
2046 if not args:
2045 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2047 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2046 macs.sort()
2048 macs.sort()
2047 return macs
2049 return macs
2048 if len(args) == 1:
2050 if len(args) == 1:
2049 raise UsageError(
2051 raise UsageError(
2050 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2052 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2051 name,ranges = args[0], args[1:]
2053 name,ranges = args[0], args[1:]
2052
2054
2053 #print 'rng',ranges # dbg
2055 #print 'rng',ranges # dbg
2054 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2056 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2055 macro = Macro(lines)
2057 macro = Macro(lines)
2056 self.shell.define_macro(name, macro)
2058 self.shell.define_macro(name, macro)
2057 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2059 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2058 print 'Macro contents:'
2060 print 'Macro contents:'
2059 print macro,
2061 print macro,
2060
2062
2061 def magic_save(self,parameter_s = ''):
2063 def magic_save(self,parameter_s = ''):
2062 """Save a set of lines to a given filename.
2064 """Save a set of lines to a given filename.
2063
2065
2064 Usage:\\
2066 Usage:\\
2065 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2067 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2066
2068
2067 Options:
2069 Options:
2068
2070
2069 -r: use 'raw' input. By default, the 'processed' history is used,
2071 -r: use 'raw' input. By default, the 'processed' history is used,
2070 so that magics are loaded in their transformed version to valid
2072 so that magics are loaded in their transformed version to valid
2071 Python. If this option is given, the raw input as typed as the
2073 Python. If this option is given, the raw input as typed as the
2072 command line is used instead.
2074 command line is used instead.
2073
2075
2074 This function uses the same syntax as %macro for line extraction, but
2076 This function uses the same syntax as %macro for line extraction, but
2075 instead of creating a macro it saves the resulting string to the
2077 instead of creating a macro it saves the resulting string to the
2076 filename you specify.
2078 filename you specify.
2077
2079
2078 It adds a '.py' extension to the file if you don't do so yourself, and
2080 It adds a '.py' extension to the file if you don't do so yourself, and
2079 it asks for confirmation before overwriting existing files."""
2081 it asks for confirmation before overwriting existing files."""
2080
2082
2081 opts,args = self.parse_options(parameter_s,'r',mode='list')
2083 opts,args = self.parse_options(parameter_s,'r',mode='list')
2082 fname,ranges = args[0], args[1:]
2084 fname,ranges = args[0], args[1:]
2083 if not fname.endswith('.py'):
2085 if not fname.endswith('.py'):
2084 fname += '.py'
2086 fname += '.py'
2085 if os.path.isfile(fname):
2087 if os.path.isfile(fname):
2086 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2088 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2087 if ans.lower() not in ['y','yes']:
2089 if ans.lower() not in ['y','yes']:
2088 print 'Operation cancelled.'
2090 print 'Operation cancelled.'
2089 return
2091 return
2090 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2092 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2091 f = file(fname,'w')
2093 f = file(fname,'w')
2092 f.write(cmds)
2094 f.write(cmds)
2093 f.close()
2095 f.close()
2094 print 'The following commands were written to file `%s`:' % fname
2096 print 'The following commands were written to file `%s`:' % fname
2095 print cmds
2097 print cmds
2096
2098
2097 def _edit_macro(self,mname,macro):
2099 def _edit_macro(self,mname,macro):
2098 """open an editor with the macro data in a file"""
2100 """open an editor with the macro data in a file"""
2099 filename = self.shell.mktempfile(macro.value)
2101 filename = self.shell.mktempfile(macro.value)
2100 self.shell.hooks.editor(filename)
2102 self.shell.hooks.editor(filename)
2101
2103
2102 # and make a new macro object, to replace the old one
2104 # and make a new macro object, to replace the old one
2103 mfile = open(filename)
2105 mfile = open(filename)
2104 mvalue = mfile.read()
2106 mvalue = mfile.read()
2105 mfile.close()
2107 mfile.close()
2106 self.shell.user_ns[mname] = Macro(mvalue)
2108 self.shell.user_ns[mname] = Macro(mvalue)
2107
2109
2108 def magic_ed(self,parameter_s=''):
2110 def magic_ed(self,parameter_s=''):
2109 """Alias to %edit."""
2111 """Alias to %edit."""
2110 return self.magic_edit(parameter_s)
2112 return self.magic_edit(parameter_s)
2111
2113
2112 @testdec.skip_doctest
2114 @testdec.skip_doctest
2113 def magic_edit(self,parameter_s='',last_call=['','']):
2115 def magic_edit(self,parameter_s='',last_call=['','']):
2114 """Bring up an editor and execute the resulting code.
2116 """Bring up an editor and execute the resulting code.
2115
2117
2116 Usage:
2118 Usage:
2117 %edit [options] [args]
2119 %edit [options] [args]
2118
2120
2119 %edit runs IPython's editor hook. The default version of this hook is
2121 %edit runs IPython's editor hook. The default version of this hook is
2120 set to call the __IPYTHON__.rc.editor command. This is read from your
2122 set to call the __IPYTHON__.rc.editor command. This is read from your
2121 environment variable $EDITOR. If this isn't found, it will default to
2123 environment variable $EDITOR. If this isn't found, it will default to
2122 vi under Linux/Unix and to notepad under Windows. See the end of this
2124 vi under Linux/Unix and to notepad under Windows. See the end of this
2123 docstring for how to change the editor hook.
2125 docstring for how to change the editor hook.
2124
2126
2125 You can also set the value of this editor via the command line option
2127 You can also set the value of this editor via the command line option
2126 '-editor' or in your ipythonrc file. This is useful if you wish to use
2128 '-editor' or in your ipythonrc file. This is useful if you wish to use
2127 specifically for IPython an editor different from your typical default
2129 specifically for IPython an editor different from your typical default
2128 (and for Windows users who typically don't set environment variables).
2130 (and for Windows users who typically don't set environment variables).
2129
2131
2130 This command allows you to conveniently edit multi-line code right in
2132 This command allows you to conveniently edit multi-line code right in
2131 your IPython session.
2133 your IPython session.
2132
2134
2133 If called without arguments, %edit opens up an empty editor with a
2135 If called without arguments, %edit opens up an empty editor with a
2134 temporary file and will execute the contents of this file when you
2136 temporary file and will execute the contents of this file when you
2135 close it (don't forget to save it!).
2137 close it (don't forget to save it!).
2136
2138
2137
2139
2138 Options:
2140 Options:
2139
2141
2140 -n <number>: open the editor at a specified line number. By default,
2142 -n <number>: open the editor at a specified line number. By default,
2141 the IPython editor hook uses the unix syntax 'editor +N filename', but
2143 the IPython editor hook uses the unix syntax 'editor +N filename', but
2142 you can configure this by providing your own modified hook if your
2144 you can configure this by providing your own modified hook if your
2143 favorite editor supports line-number specifications with a different
2145 favorite editor supports line-number specifications with a different
2144 syntax.
2146 syntax.
2145
2147
2146 -p: this will call the editor with the same data as the previous time
2148 -p: this will call the editor with the same data as the previous time
2147 it was used, regardless of how long ago (in your current session) it
2149 it was used, regardless of how long ago (in your current session) it
2148 was.
2150 was.
2149
2151
2150 -r: use 'raw' input. This option only applies to input taken from the
2152 -r: use 'raw' input. This option only applies to input taken from the
2151 user's history. By default, the 'processed' history is used, so that
2153 user's history. By default, the 'processed' history is used, so that
2152 magics are loaded in their transformed version to valid Python. If
2154 magics are loaded in their transformed version to valid Python. If
2153 this option is given, the raw input as typed as the command line is
2155 this option is given, the raw input as typed as the command line is
2154 used instead. When you exit the editor, it will be executed by
2156 used instead. When you exit the editor, it will be executed by
2155 IPython's own processor.
2157 IPython's own processor.
2156
2158
2157 -x: do not execute the edited code immediately upon exit. This is
2159 -x: do not execute the edited code immediately upon exit. This is
2158 mainly useful if you are editing programs which need to be called with
2160 mainly useful if you are editing programs which need to be called with
2159 command line arguments, which you can then do using %run.
2161 command line arguments, which you can then do using %run.
2160
2162
2161
2163
2162 Arguments:
2164 Arguments:
2163
2165
2164 If arguments are given, the following possibilites exist:
2166 If arguments are given, the following possibilites exist:
2165
2167
2166 - The arguments are numbers or pairs of colon-separated numbers (like
2168 - The arguments are numbers or pairs of colon-separated numbers (like
2167 1 4:8 9). These are interpreted as lines of previous input to be
2169 1 4:8 9). These are interpreted as lines of previous input to be
2168 loaded into the editor. The syntax is the same of the %macro command.
2170 loaded into the editor. The syntax is the same of the %macro command.
2169
2171
2170 - If the argument doesn't start with a number, it is evaluated as a
2172 - If the argument doesn't start with a number, it is evaluated as a
2171 variable and its contents loaded into the editor. You can thus edit
2173 variable and its contents loaded into the editor. You can thus edit
2172 any string which contains python code (including the result of
2174 any string which contains python code (including the result of
2173 previous edits).
2175 previous edits).
2174
2176
2175 - If the argument is the name of an object (other than a string),
2177 - If the argument is the name of an object (other than a string),
2176 IPython will try to locate the file where it was defined and open the
2178 IPython will try to locate the file where it was defined and open the
2177 editor at the point where it is defined. You can use `%edit function`
2179 editor at the point where it is defined. You can use `%edit function`
2178 to load an editor exactly at the point where 'function' is defined,
2180 to load an editor exactly at the point where 'function' is defined,
2179 edit it and have the file be executed automatically.
2181 edit it and have the file be executed automatically.
2180
2182
2181 If the object is a macro (see %macro for details), this opens up your
2183 If the object is a macro (see %macro for details), this opens up your
2182 specified editor with a temporary file containing the macro's data.
2184 specified editor with a temporary file containing the macro's data.
2183 Upon exit, the macro is reloaded with the contents of the file.
2185 Upon exit, the macro is reloaded with the contents of the file.
2184
2186
2185 Note: opening at an exact line is only supported under Unix, and some
2187 Note: opening at an exact line is only supported under Unix, and some
2186 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2188 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2187 '+NUMBER' parameter necessary for this feature. Good editors like
2189 '+NUMBER' parameter necessary for this feature. Good editors like
2188 (X)Emacs, vi, jed, pico and joe all do.
2190 (X)Emacs, vi, jed, pico and joe all do.
2189
2191
2190 - If the argument is not found as a variable, IPython will look for a
2192 - If the argument is not found as a variable, IPython will look for a
2191 file with that name (adding .py if necessary) and load it into the
2193 file with that name (adding .py if necessary) and load it into the
2192 editor. It will execute its contents with execfile() when you exit,
2194 editor. It will execute its contents with execfile() when you exit,
2193 loading any code in the file into your interactive namespace.
2195 loading any code in the file into your interactive namespace.
2194
2196
2195 After executing your code, %edit will return as output the code you
2197 After executing your code, %edit will return as output the code you
2196 typed in the editor (except when it was an existing file). This way
2198 typed in the editor (except when it was an existing file). This way
2197 you can reload the code in further invocations of %edit as a variable,
2199 you can reload the code in further invocations of %edit as a variable,
2198 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2200 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2199 the output.
2201 the output.
2200
2202
2201 Note that %edit is also available through the alias %ed.
2203 Note that %edit is also available through the alias %ed.
2202
2204
2203 This is an example of creating a simple function inside the editor and
2205 This is an example of creating a simple function inside the editor and
2204 then modifying it. First, start up the editor:
2206 then modifying it. First, start up the editor:
2205
2207
2206 In [1]: ed
2208 In [1]: ed
2207 Editing... done. Executing edited code...
2209 Editing... done. Executing edited code...
2208 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2210 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2209
2211
2210 We can then call the function foo():
2212 We can then call the function foo():
2211
2213
2212 In [2]: foo()
2214 In [2]: foo()
2213 foo() was defined in an editing session
2215 foo() was defined in an editing session
2214
2216
2215 Now we edit foo. IPython automatically loads the editor with the
2217 Now we edit foo. IPython automatically loads the editor with the
2216 (temporary) file where foo() was previously defined:
2218 (temporary) file where foo() was previously defined:
2217
2219
2218 In [3]: ed foo
2220 In [3]: ed foo
2219 Editing... done. Executing edited code...
2221 Editing... done. Executing edited code...
2220
2222
2221 And if we call foo() again we get the modified version:
2223 And if we call foo() again we get the modified version:
2222
2224
2223 In [4]: foo()
2225 In [4]: foo()
2224 foo() has now been changed!
2226 foo() has now been changed!
2225
2227
2226 Here is an example of how to edit a code snippet successive
2228 Here is an example of how to edit a code snippet successive
2227 times. First we call the editor:
2229 times. First we call the editor:
2228
2230
2229 In [5]: ed
2231 In [5]: ed
2230 Editing... done. Executing edited code...
2232 Editing... done. Executing edited code...
2231 hello
2233 hello
2232 Out[5]: "print 'hello'n"
2234 Out[5]: "print 'hello'n"
2233
2235
2234 Now we call it again with the previous output (stored in _):
2236 Now we call it again with the previous output (stored in _):
2235
2237
2236 In [6]: ed _
2238 In [6]: ed _
2237 Editing... done. Executing edited code...
2239 Editing... done. Executing edited code...
2238 hello world
2240 hello world
2239 Out[6]: "print 'hello world'n"
2241 Out[6]: "print 'hello world'n"
2240
2242
2241 Now we call it with the output #8 (stored in _8, also as Out[8]):
2243 Now we call it with the output #8 (stored in _8, also as Out[8]):
2242
2244
2243 In [7]: ed _8
2245 In [7]: ed _8
2244 Editing... done. Executing edited code...
2246 Editing... done. Executing edited code...
2245 hello again
2247 hello again
2246 Out[7]: "print 'hello again'n"
2248 Out[7]: "print 'hello again'n"
2247
2249
2248
2250
2249 Changing the default editor hook:
2251 Changing the default editor hook:
2250
2252
2251 If you wish to write your own editor hook, you can put it in a
2253 If you wish to write your own editor hook, you can put it in a
2252 configuration file which you load at startup time. The default hook
2254 configuration file which you load at startup time. The default hook
2253 is defined in the IPython.core.hooks module, and you can use that as a
2255 is defined in the IPython.core.hooks module, and you can use that as a
2254 starting example for further modifications. That file also has
2256 starting example for further modifications. That file also has
2255 general instructions on how to set a new hook for use once you've
2257 general instructions on how to set a new hook for use once you've
2256 defined it."""
2258 defined it."""
2257
2259
2258 # FIXME: This function has become a convoluted mess. It needs a
2260 # FIXME: This function has become a convoluted mess. It needs a
2259 # ground-up rewrite with clean, simple logic.
2261 # ground-up rewrite with clean, simple logic.
2260
2262
2261 def make_filename(arg):
2263 def make_filename(arg):
2262 "Make a filename from the given args"
2264 "Make a filename from the given args"
2263 try:
2265 try:
2264 filename = get_py_filename(arg)
2266 filename = get_py_filename(arg)
2265 except IOError:
2267 except IOError:
2266 if args.endswith('.py'):
2268 if args.endswith('.py'):
2267 filename = arg
2269 filename = arg
2268 else:
2270 else:
2269 filename = None
2271 filename = None
2270 return filename
2272 return filename
2271
2273
2272 # custom exceptions
2274 # custom exceptions
2273 class DataIsObject(Exception): pass
2275 class DataIsObject(Exception): pass
2274
2276
2275 opts,args = self.parse_options(parameter_s,'prxn:')
2277 opts,args = self.parse_options(parameter_s,'prxn:')
2276 # Set a few locals from the options for convenience:
2278 # Set a few locals from the options for convenience:
2277 opts_p = opts.has_key('p')
2279 opts_p = opts.has_key('p')
2278 opts_r = opts.has_key('r')
2280 opts_r = opts.has_key('r')
2279
2281
2280 # Default line number value
2282 # Default line number value
2281 lineno = opts.get('n',None)
2283 lineno = opts.get('n',None)
2282
2284
2283 if opts_p:
2285 if opts_p:
2284 args = '_%s' % last_call[0]
2286 args = '_%s' % last_call[0]
2285 if not self.shell.user_ns.has_key(args):
2287 if not self.shell.user_ns.has_key(args):
2286 args = last_call[1]
2288 args = last_call[1]
2287
2289
2288 # use last_call to remember the state of the previous call, but don't
2290 # use last_call to remember the state of the previous call, but don't
2289 # let it be clobbered by successive '-p' calls.
2291 # let it be clobbered by successive '-p' calls.
2290 try:
2292 try:
2291 last_call[0] = self.shell.outputcache.prompt_count
2293 last_call[0] = self.shell.outputcache.prompt_count
2292 if not opts_p:
2294 if not opts_p:
2293 last_call[1] = parameter_s
2295 last_call[1] = parameter_s
2294 except:
2296 except:
2295 pass
2297 pass
2296
2298
2297 # by default this is done with temp files, except when the given
2299 # by default this is done with temp files, except when the given
2298 # arg is a filename
2300 # arg is a filename
2299 use_temp = 1
2301 use_temp = 1
2300
2302
2301 if re.match(r'\d',args):
2303 if re.match(r'\d',args):
2302 # Mode where user specifies ranges of lines, like in %macro.
2304 # Mode where user specifies ranges of lines, like in %macro.
2303 # This means that you can't edit files whose names begin with
2305 # This means that you can't edit files whose names begin with
2304 # numbers this way. Tough.
2306 # numbers this way. Tough.
2305 ranges = args.split()
2307 ranges = args.split()
2306 data = ''.join(self.extract_input_slices(ranges,opts_r))
2308 data = ''.join(self.extract_input_slices(ranges,opts_r))
2307 elif args.endswith('.py'):
2309 elif args.endswith('.py'):
2308 filename = make_filename(args)
2310 filename = make_filename(args)
2309 data = ''
2311 data = ''
2310 use_temp = 0
2312 use_temp = 0
2311 elif args:
2313 elif args:
2312 try:
2314 try:
2313 # Load the parameter given as a variable. If not a string,
2315 # Load the parameter given as a variable. If not a string,
2314 # process it as an object instead (below)
2316 # process it as an object instead (below)
2315
2317
2316 #print '*** args',args,'type',type(args) # dbg
2318 #print '*** args',args,'type',type(args) # dbg
2317 data = eval(args,self.shell.user_ns)
2319 data = eval(args,self.shell.user_ns)
2318 if not type(data) in StringTypes:
2320 if not type(data) in StringTypes:
2319 raise DataIsObject
2321 raise DataIsObject
2320
2322
2321 except (NameError,SyntaxError):
2323 except (NameError,SyntaxError):
2322 # given argument is not a variable, try as a filename
2324 # given argument is not a variable, try as a filename
2323 filename = make_filename(args)
2325 filename = make_filename(args)
2324 if filename is None:
2326 if filename is None:
2325 warn("Argument given (%s) can't be found as a variable "
2327 warn("Argument given (%s) can't be found as a variable "
2326 "or as a filename." % args)
2328 "or as a filename." % args)
2327 return
2329 return
2328
2330
2329 data = ''
2331 data = ''
2330 use_temp = 0
2332 use_temp = 0
2331 except DataIsObject:
2333 except DataIsObject:
2332
2334
2333 # macros have a special edit function
2335 # macros have a special edit function
2334 if isinstance(data,Macro):
2336 if isinstance(data,Macro):
2335 self._edit_macro(args,data)
2337 self._edit_macro(args,data)
2336 return
2338 return
2337
2339
2338 # For objects, try to edit the file where they are defined
2340 # For objects, try to edit the file where they are defined
2339 try:
2341 try:
2340 filename = inspect.getabsfile(data)
2342 filename = inspect.getabsfile(data)
2341 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2343 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2342 # class created by %edit? Try to find source
2344 # class created by %edit? Try to find source
2343 # by looking for method definitions instead, the
2345 # by looking for method definitions instead, the
2344 # __module__ in those classes is FakeModule.
2346 # __module__ in those classes is FakeModule.
2345 attrs = [getattr(data, aname) for aname in dir(data)]
2347 attrs = [getattr(data, aname) for aname in dir(data)]
2346 for attr in attrs:
2348 for attr in attrs:
2347 if not inspect.ismethod(attr):
2349 if not inspect.ismethod(attr):
2348 continue
2350 continue
2349 filename = inspect.getabsfile(attr)
2351 filename = inspect.getabsfile(attr)
2350 if filename and 'fakemodule' not in filename.lower():
2352 if filename and 'fakemodule' not in filename.lower():
2351 # change the attribute to be the edit target instead
2353 # change the attribute to be the edit target instead
2352 data = attr
2354 data = attr
2353 break
2355 break
2354
2356
2355 datafile = 1
2357 datafile = 1
2356 except TypeError:
2358 except TypeError:
2357 filename = make_filename(args)
2359 filename = make_filename(args)
2358 datafile = 1
2360 datafile = 1
2359 warn('Could not find file where `%s` is defined.\n'
2361 warn('Could not find file where `%s` is defined.\n'
2360 'Opening a file named `%s`' % (args,filename))
2362 'Opening a file named `%s`' % (args,filename))
2361 # Now, make sure we can actually read the source (if it was in
2363 # Now, make sure we can actually read the source (if it was in
2362 # a temp file it's gone by now).
2364 # a temp file it's gone by now).
2363 if datafile:
2365 if datafile:
2364 try:
2366 try:
2365 if lineno is None:
2367 if lineno is None:
2366 lineno = inspect.getsourcelines(data)[1]
2368 lineno = inspect.getsourcelines(data)[1]
2367 except IOError:
2369 except IOError:
2368 filename = make_filename(args)
2370 filename = make_filename(args)
2369 if filename is None:
2371 if filename is None:
2370 warn('The file `%s` where `%s` was defined cannot '
2372 warn('The file `%s` where `%s` was defined cannot '
2371 'be read.' % (filename,data))
2373 'be read.' % (filename,data))
2372 return
2374 return
2373 use_temp = 0
2375 use_temp = 0
2374 else:
2376 else:
2375 data = ''
2377 data = ''
2376
2378
2377 if use_temp:
2379 if use_temp:
2378 filename = self.shell.mktempfile(data)
2380 filename = self.shell.mktempfile(data)
2379 print 'IPython will make a temporary file named:',filename
2381 print 'IPython will make a temporary file named:',filename
2380
2382
2381 # do actual editing here
2383 # do actual editing here
2382 print 'Editing...',
2384 print 'Editing...',
2383 sys.stdout.flush()
2385 sys.stdout.flush()
2384 try:
2386 try:
2385 self.shell.hooks.editor(filename,lineno)
2387 self.shell.hooks.editor(filename,lineno)
2386 except TryNext:
2388 except TryNext:
2387 warn('Could not open editor')
2389 warn('Could not open editor')
2388 return
2390 return
2389
2391
2390 # XXX TODO: should this be generalized for all string vars?
2392 # XXX TODO: should this be generalized for all string vars?
2391 # For now, this is special-cased to blocks created by cpaste
2393 # For now, this is special-cased to blocks created by cpaste
2392 if args.strip() == 'pasted_block':
2394 if args.strip() == 'pasted_block':
2393 self.shell.user_ns['pasted_block'] = file_read(filename)
2395 self.shell.user_ns['pasted_block'] = file_read(filename)
2394
2396
2395 if opts.has_key('x'): # -x prevents actual execution
2397 if opts.has_key('x'): # -x prevents actual execution
2396 print
2398 print
2397 else:
2399 else:
2398 print 'done. Executing edited code...'
2400 print 'done. Executing edited code...'
2399 if opts_r:
2401 if opts_r:
2400 self.shell.runlines(file_read(filename))
2402 self.shell.runlines(file_read(filename))
2401 else:
2403 else:
2402 self.shell.safe_execfile(filename,self.shell.user_ns,
2404 self.shell.safe_execfile(filename,self.shell.user_ns,
2403 self.shell.user_ns)
2405 self.shell.user_ns)
2404
2406
2405
2407
2406 if use_temp:
2408 if use_temp:
2407 try:
2409 try:
2408 return open(filename).read()
2410 return open(filename).read()
2409 except IOError,msg:
2411 except IOError,msg:
2410 if msg.filename == filename:
2412 if msg.filename == filename:
2411 warn('File not found. Did you forget to save?')
2413 warn('File not found. Did you forget to save?')
2412 return
2414 return
2413 else:
2415 else:
2414 self.shell.showtraceback()
2416 self.shell.showtraceback()
2415
2417
2416 def magic_xmode(self,parameter_s = ''):
2418 def magic_xmode(self,parameter_s = ''):
2417 """Switch modes for the exception handlers.
2419 """Switch modes for the exception handlers.
2418
2420
2419 Valid modes: Plain, Context and Verbose.
2421 Valid modes: Plain, Context and Verbose.
2420
2422
2421 If called without arguments, acts as a toggle."""
2423 If called without arguments, acts as a toggle."""
2422
2424
2423 def xmode_switch_err(name):
2425 def xmode_switch_err(name):
2424 warn('Error changing %s exception modes.\n%s' %
2426 warn('Error changing %s exception modes.\n%s' %
2425 (name,sys.exc_info()[1]))
2427 (name,sys.exc_info()[1]))
2426
2428
2427 shell = self.shell
2429 shell = self.shell
2428 new_mode = parameter_s.strip().capitalize()
2430 new_mode = parameter_s.strip().capitalize()
2429 try:
2431 try:
2430 shell.InteractiveTB.set_mode(mode=new_mode)
2432 shell.InteractiveTB.set_mode(mode=new_mode)
2431 print 'Exception reporting mode:',shell.InteractiveTB.mode
2433 print 'Exception reporting mode:',shell.InteractiveTB.mode
2432 except:
2434 except:
2433 xmode_switch_err('user')
2435 xmode_switch_err('user')
2434
2436
2435 # threaded shells use a special handler in sys.excepthook
2437 # threaded shells use a special handler in sys.excepthook
2436 if shell.isthreaded:
2438 if shell.isthreaded:
2437 try:
2439 try:
2438 shell.sys_excepthook.set_mode(mode=new_mode)
2440 shell.sys_excepthook.set_mode(mode=new_mode)
2439 except:
2441 except:
2440 xmode_switch_err('threaded')
2442 xmode_switch_err('threaded')
2441
2443
2442 def magic_colors(self,parameter_s = ''):
2444 def magic_colors(self,parameter_s = ''):
2443 """Switch color scheme for prompts, info system and exception handlers.
2445 """Switch color scheme for prompts, info system and exception handlers.
2444
2446
2445 Currently implemented schemes: NoColor, Linux, LightBG.
2447 Currently implemented schemes: NoColor, Linux, LightBG.
2446
2448
2447 Color scheme names are not case-sensitive."""
2449 Color scheme names are not case-sensitive."""
2448
2450
2449 def color_switch_err(name):
2451 def color_switch_err(name):
2450 warn('Error changing %s color schemes.\n%s' %
2452 warn('Error changing %s color schemes.\n%s' %
2451 (name,sys.exc_info()[1]))
2453 (name,sys.exc_info()[1]))
2452
2454
2453
2455
2454 new_scheme = parameter_s.strip()
2456 new_scheme = parameter_s.strip()
2455 if not new_scheme:
2457 if not new_scheme:
2456 raise UsageError(
2458 raise UsageError(
2457 "%colors: you must specify a color scheme. See '%colors?'")
2459 "%colors: you must specify a color scheme. See '%colors?'")
2458 return
2460 return
2459 # local shortcut
2461 # local shortcut
2460 shell = self.shell
2462 shell = self.shell
2461
2463
2462 import IPython.utils.rlineimpl as readline
2464 import IPython.utils.rlineimpl as readline
2463
2465
2464 if not readline.have_readline and sys.platform == "win32":
2466 if not readline.have_readline and sys.platform == "win32":
2465 msg = """\
2467 msg = """\
2466 Proper color support under MS Windows requires the pyreadline library.
2468 Proper color support under MS Windows requires the pyreadline library.
2467 You can find it at:
2469 You can find it at:
2468 http://ipython.scipy.org/moin/PyReadline/Intro
2470 http://ipython.scipy.org/moin/PyReadline/Intro
2469 Gary's readline needs the ctypes module, from:
2471 Gary's readline needs the ctypes module, from:
2470 http://starship.python.net/crew/theller/ctypes
2472 http://starship.python.net/crew/theller/ctypes
2471 (Note that ctypes is already part of Python versions 2.5 and newer).
2473 (Note that ctypes is already part of Python versions 2.5 and newer).
2472
2474
2473 Defaulting color scheme to 'NoColor'"""
2475 Defaulting color scheme to 'NoColor'"""
2474 new_scheme = 'NoColor'
2476 new_scheme = 'NoColor'
2475 warn(msg)
2477 warn(msg)
2476
2478
2477 # readline option is 0
2479 # readline option is 0
2478 if not shell.has_readline:
2480 if not shell.has_readline:
2479 new_scheme = 'NoColor'
2481 new_scheme = 'NoColor'
2480
2482
2481 # Set prompt colors
2483 # Set prompt colors
2482 try:
2484 try:
2483 shell.outputcache.set_colors(new_scheme)
2485 shell.outputcache.set_colors(new_scheme)
2484 except:
2486 except:
2485 color_switch_err('prompt')
2487 color_switch_err('prompt')
2486 else:
2488 else:
2487 shell.colors = \
2489 shell.colors = \
2488 shell.outputcache.color_table.active_scheme_name
2490 shell.outputcache.color_table.active_scheme_name
2489 # Set exception colors
2491 # Set exception colors
2490 try:
2492 try:
2491 shell.InteractiveTB.set_colors(scheme = new_scheme)
2493 shell.InteractiveTB.set_colors(scheme = new_scheme)
2492 shell.SyntaxTB.set_colors(scheme = new_scheme)
2494 shell.SyntaxTB.set_colors(scheme = new_scheme)
2493 except:
2495 except:
2494 color_switch_err('exception')
2496 color_switch_err('exception')
2495
2497
2496 # threaded shells use a verbose traceback in sys.excepthook
2498 # threaded shells use a verbose traceback in sys.excepthook
2497 if shell.isthreaded:
2499 if shell.isthreaded:
2498 try:
2500 try:
2499 shell.sys_excepthook.set_colors(scheme=new_scheme)
2501 shell.sys_excepthook.set_colors(scheme=new_scheme)
2500 except:
2502 except:
2501 color_switch_err('system exception handler')
2503 color_switch_err('system exception handler')
2502
2504
2503 # Set info (for 'object?') colors
2505 # Set info (for 'object?') colors
2504 if shell.color_info:
2506 if shell.color_info:
2505 try:
2507 try:
2506 shell.inspector.set_active_scheme(new_scheme)
2508 shell.inspector.set_active_scheme(new_scheme)
2507 except:
2509 except:
2508 color_switch_err('object inspector')
2510 color_switch_err('object inspector')
2509 else:
2511 else:
2510 shell.inspector.set_active_scheme('NoColor')
2512 shell.inspector.set_active_scheme('NoColor')
2511
2513
2512 def magic_color_info(self,parameter_s = ''):
2514 def magic_color_info(self,parameter_s = ''):
2513 """Toggle color_info.
2515 """Toggle color_info.
2514
2516
2515 The color_info configuration parameter controls whether colors are
2517 The color_info configuration parameter controls whether colors are
2516 used for displaying object details (by things like %psource, %pfile or
2518 used for displaying object details (by things like %psource, %pfile or
2517 the '?' system). This function toggles this value with each call.
2519 the '?' system). This function toggles this value with each call.
2518
2520
2519 Note that unless you have a fairly recent pager (less works better
2521 Note that unless you have a fairly recent pager (less works better
2520 than more) in your system, using colored object information displays
2522 than more) in your system, using colored object information displays
2521 will not work properly. Test it and see."""
2523 will not work properly. Test it and see."""
2522
2524
2523 self.shell.color_info = not self.shell.color_info
2525 self.shell.color_info = not self.shell.color_info
2524 self.magic_colors(self.shell.colors)
2526 self.magic_colors(self.shell.colors)
2525 print 'Object introspection functions have now coloring:',
2527 print 'Object introspection functions have now coloring:',
2526 print ['OFF','ON'][int(self.shell.color_info)]
2528 print ['OFF','ON'][int(self.shell.color_info)]
2527
2529
2528 def magic_Pprint(self, parameter_s=''):
2530 def magic_Pprint(self, parameter_s=''):
2529 """Toggle pretty printing on/off."""
2531 """Toggle pretty printing on/off."""
2530
2532
2531 self.shell.pprint = 1 - self.shell.pprint
2533 self.shell.pprint = 1 - self.shell.pprint
2532 print 'Pretty printing has been turned', \
2534 print 'Pretty printing has been turned', \
2533 ['OFF','ON'][self.shell.pprint]
2535 ['OFF','ON'][self.shell.pprint]
2534
2536
2535 def magic_Exit(self, parameter_s=''):
2537 def magic_Exit(self, parameter_s=''):
2536 """Exit IPython without confirmation."""
2538 """Exit IPython without confirmation."""
2537
2539
2538 self.shell.ask_exit()
2540 self.shell.ask_exit()
2539
2541
2540 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2542 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2541 magic_exit = magic_quit = magic_Quit = magic_Exit
2543 magic_exit = magic_quit = magic_Quit = magic_Exit
2542
2544
2543 #......................................................................
2545 #......................................................................
2544 # Functions to implement unix shell-type things
2546 # Functions to implement unix shell-type things
2545
2547
2546 @testdec.skip_doctest
2548 @testdec.skip_doctest
2547 def magic_alias(self, parameter_s = ''):
2549 def magic_alias(self, parameter_s = ''):
2548 """Define an alias for a system command.
2550 """Define an alias for a system command.
2549
2551
2550 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2552 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2551
2553
2552 Then, typing 'alias_name params' will execute the system command 'cmd
2554 Then, typing 'alias_name params' will execute the system command 'cmd
2553 params' (from your underlying operating system).
2555 params' (from your underlying operating system).
2554
2556
2555 Aliases have lower precedence than magic functions and Python normal
2557 Aliases have lower precedence than magic functions and Python normal
2556 variables, so if 'foo' is both a Python variable and an alias, the
2558 variables, so if 'foo' is both a Python variable and an alias, the
2557 alias can not be executed until 'del foo' removes the Python variable.
2559 alias can not be executed until 'del foo' removes the Python variable.
2558
2560
2559 You can use the %l specifier in an alias definition to represent the
2561 You can use the %l specifier in an alias definition to represent the
2560 whole line when the alias is called. For example:
2562 whole line when the alias is called. For example:
2561
2563
2562 In [2]: alias all echo "Input in brackets: <%l>"
2564 In [2]: alias all echo "Input in brackets: <%l>"
2563 In [3]: all hello world
2565 In [3]: all hello world
2564 Input in brackets: <hello world>
2566 Input in brackets: <hello world>
2565
2567
2566 You can also define aliases with parameters using %s specifiers (one
2568 You can also define aliases with parameters using %s specifiers (one
2567 per parameter):
2569 per parameter):
2568
2570
2569 In [1]: alias parts echo first %s second %s
2571 In [1]: alias parts echo first %s second %s
2570 In [2]: %parts A B
2572 In [2]: %parts A B
2571 first A second B
2573 first A second B
2572 In [3]: %parts A
2574 In [3]: %parts A
2573 Incorrect number of arguments: 2 expected.
2575 Incorrect number of arguments: 2 expected.
2574 parts is an alias to: 'echo first %s second %s'
2576 parts is an alias to: 'echo first %s second %s'
2575
2577
2576 Note that %l and %s are mutually exclusive. You can only use one or
2578 Note that %l and %s are mutually exclusive. You can only use one or
2577 the other in your aliases.
2579 the other in your aliases.
2578
2580
2579 Aliases expand Python variables just like system calls using ! or !!
2581 Aliases expand Python variables just like system calls using ! or !!
2580 do: all expressions prefixed with '$' get expanded. For details of
2582 do: all expressions prefixed with '$' get expanded. For details of
2581 the semantic rules, see PEP-215:
2583 the semantic rules, see PEP-215:
2582 http://www.python.org/peps/pep-0215.html. This is the library used by
2584 http://www.python.org/peps/pep-0215.html. This is the library used by
2583 IPython for variable expansion. If you want to access a true shell
2585 IPython for variable expansion. If you want to access a true shell
2584 variable, an extra $ is necessary to prevent its expansion by IPython:
2586 variable, an extra $ is necessary to prevent its expansion by IPython:
2585
2587
2586 In [6]: alias show echo
2588 In [6]: alias show echo
2587 In [7]: PATH='A Python string'
2589 In [7]: PATH='A Python string'
2588 In [8]: show $PATH
2590 In [8]: show $PATH
2589 A Python string
2591 A Python string
2590 In [9]: show $$PATH
2592 In [9]: show $$PATH
2591 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2593 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2592
2594
2593 You can use the alias facility to acess all of $PATH. See the %rehash
2595 You can use the alias facility to acess all of $PATH. See the %rehash
2594 and %rehashx functions, which automatically create aliases for the
2596 and %rehashx functions, which automatically create aliases for the
2595 contents of your $PATH.
2597 contents of your $PATH.
2596
2598
2597 If called with no parameters, %alias prints the current alias table."""
2599 If called with no parameters, %alias prints the current alias table."""
2598
2600
2599 par = parameter_s.strip()
2601 par = parameter_s.strip()
2600 if not par:
2602 if not par:
2601 stored = self.db.get('stored_aliases', {} )
2603 stored = self.db.get('stored_aliases', {} )
2602 aliases = sorted(self.shell.alias_manager.aliases)
2604 aliases = sorted(self.shell.alias_manager.aliases)
2603 # for k, v in stored:
2605 # for k, v in stored:
2604 # atab.append(k, v[0])
2606 # atab.append(k, v[0])
2605
2607
2606 print "Total number of aliases:", len(aliases)
2608 print "Total number of aliases:", len(aliases)
2607 return aliases
2609 return aliases
2608
2610
2609 # Now try to define a new one
2611 # Now try to define a new one
2610 try:
2612 try:
2611 alias,cmd = par.split(None, 1)
2613 alias,cmd = par.split(None, 1)
2612 except:
2614 except:
2613 print oinspect.getdoc(self.magic_alias)
2615 print oinspect.getdoc(self.magic_alias)
2614 else:
2616 else:
2615 self.shell.alias_manager.soft_define_alias(alias, cmd)
2617 self.shell.alias_manager.soft_define_alias(alias, cmd)
2616 # end magic_alias
2618 # end magic_alias
2617
2619
2618 def magic_unalias(self, parameter_s = ''):
2620 def magic_unalias(self, parameter_s = ''):
2619 """Remove an alias"""
2621 """Remove an alias"""
2620
2622
2621 aname = parameter_s.strip()
2623 aname = parameter_s.strip()
2622 self.shell.alias_manager.undefine_alias(aname)
2624 self.shell.alias_manager.undefine_alias(aname)
2623 stored = self.db.get('stored_aliases', {} )
2625 stored = self.db.get('stored_aliases', {} )
2624 if aname in stored:
2626 if aname in stored:
2625 print "Removing %stored alias",aname
2627 print "Removing %stored alias",aname
2626 del stored[aname]
2628 del stored[aname]
2627 self.db['stored_aliases'] = stored
2629 self.db['stored_aliases'] = stored
2628
2630
2629
2631
2630 def magic_rehashx(self, parameter_s = ''):
2632 def magic_rehashx(self, parameter_s = ''):
2631 """Update the alias table with all executable files in $PATH.
2633 """Update the alias table with all executable files in $PATH.
2632
2634
2633 This version explicitly checks that every entry in $PATH is a file
2635 This version explicitly checks that every entry in $PATH is a file
2634 with execute access (os.X_OK), so it is much slower than %rehash.
2636 with execute access (os.X_OK), so it is much slower than %rehash.
2635
2637
2636 Under Windows, it checks executability as a match agains a
2638 Under Windows, it checks executability as a match agains a
2637 '|'-separated string of extensions, stored in the IPython config
2639 '|'-separated string of extensions, stored in the IPython config
2638 variable win_exec_ext. This defaults to 'exe|com|bat'.
2640 variable win_exec_ext. This defaults to 'exe|com|bat'.
2639
2641
2640 This function also resets the root module cache of module completer,
2642 This function also resets the root module cache of module completer,
2641 used on slow filesystems.
2643 used on slow filesystems.
2642 """
2644 """
2643 from IPython.core.alias import InvalidAliasError
2645 from IPython.core.alias import InvalidAliasError
2644
2646
2645 # for the benefit of module completer in ipy_completers.py
2647 # for the benefit of module completer in ipy_completers.py
2646 del self.db['rootmodules']
2648 del self.db['rootmodules']
2647
2649
2648 path = [os.path.abspath(os.path.expanduser(p)) for p in
2650 path = [os.path.abspath(os.path.expanduser(p)) for p in
2649 os.environ.get('PATH','').split(os.pathsep)]
2651 os.environ.get('PATH','').split(os.pathsep)]
2650 path = filter(os.path.isdir,path)
2652 path = filter(os.path.isdir,path)
2651
2653
2652 syscmdlist = []
2654 syscmdlist = []
2653 # Now define isexec in a cross platform manner.
2655 # Now define isexec in a cross platform manner.
2654 if os.name == 'posix':
2656 if os.name == 'posix':
2655 isexec = lambda fname:os.path.isfile(fname) and \
2657 isexec = lambda fname:os.path.isfile(fname) and \
2656 os.access(fname,os.X_OK)
2658 os.access(fname,os.X_OK)
2657 else:
2659 else:
2658 try:
2660 try:
2659 winext = os.environ['pathext'].replace(';','|').replace('.','')
2661 winext = os.environ['pathext'].replace(';','|').replace('.','')
2660 except KeyError:
2662 except KeyError:
2661 winext = 'exe|com|bat|py'
2663 winext = 'exe|com|bat|py'
2662 if 'py' not in winext:
2664 if 'py' not in winext:
2663 winext += '|py'
2665 winext += '|py'
2664 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2666 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2665 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2667 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2666 savedir = os.getcwd()
2668 savedir = os.getcwd()
2667
2669
2668 # Now walk the paths looking for executables to alias.
2670 # Now walk the paths looking for executables to alias.
2669 try:
2671 try:
2670 # write the whole loop for posix/Windows so we don't have an if in
2672 # write the whole loop for posix/Windows so we don't have an if in
2671 # the innermost part
2673 # the innermost part
2672 if os.name == 'posix':
2674 if os.name == 'posix':
2673 for pdir in path:
2675 for pdir in path:
2674 os.chdir(pdir)
2676 os.chdir(pdir)
2675 for ff in os.listdir(pdir):
2677 for ff in os.listdir(pdir):
2676 if isexec(ff):
2678 if isexec(ff):
2677 try:
2679 try:
2678 # Removes dots from the name since ipython
2680 # Removes dots from the name since ipython
2679 # will assume names with dots to be python.
2681 # will assume names with dots to be python.
2680 self.shell.alias_manager.define_alias(
2682 self.shell.alias_manager.define_alias(
2681 ff.replace('.',''), ff)
2683 ff.replace('.',''), ff)
2682 except InvalidAliasError:
2684 except InvalidAliasError:
2683 pass
2685 pass
2684 else:
2686 else:
2685 syscmdlist.append(ff)
2687 syscmdlist.append(ff)
2686 else:
2688 else:
2687 no_alias = self.shell.alias_manager.no_alias
2689 no_alias = self.shell.alias_manager.no_alias
2688 for pdir in path:
2690 for pdir in path:
2689 os.chdir(pdir)
2691 os.chdir(pdir)
2690 for ff in os.listdir(pdir):
2692 for ff in os.listdir(pdir):
2691 base, ext = os.path.splitext(ff)
2693 base, ext = os.path.splitext(ff)
2692 if isexec(ff) and base.lower() not in no_alias:
2694 if isexec(ff) and base.lower() not in no_alias:
2693 if ext.lower() == '.exe':
2695 if ext.lower() == '.exe':
2694 ff = base
2696 ff = base
2695 try:
2697 try:
2696 # Removes dots from the name since ipython
2698 # Removes dots from the name since ipython
2697 # will assume names with dots to be python.
2699 # will assume names with dots to be python.
2698 self.shell.alias_manager.define_alias(
2700 self.shell.alias_manager.define_alias(
2699 base.lower().replace('.',''), ff)
2701 base.lower().replace('.',''), ff)
2700 except InvalidAliasError:
2702 except InvalidAliasError:
2701 pass
2703 pass
2702 syscmdlist.append(ff)
2704 syscmdlist.append(ff)
2703 db = self.db
2705 db = self.db
2704 db['syscmdlist'] = syscmdlist
2706 db['syscmdlist'] = syscmdlist
2705 finally:
2707 finally:
2706 os.chdir(savedir)
2708 os.chdir(savedir)
2707
2709
2708 def magic_pwd(self, parameter_s = ''):
2710 def magic_pwd(self, parameter_s = ''):
2709 """Return the current working directory path."""
2711 """Return the current working directory path."""
2710 return os.getcwd()
2712 return os.getcwd()
2711
2713
2712 def magic_cd(self, parameter_s=''):
2714 def magic_cd(self, parameter_s=''):
2713 """Change the current working directory.
2715 """Change the current working directory.
2714
2716
2715 This command automatically maintains an internal list of directories
2717 This command automatically maintains an internal list of directories
2716 you visit during your IPython session, in the variable _dh. The
2718 you visit during your IPython session, in the variable _dh. The
2717 command %dhist shows this history nicely formatted. You can also
2719 command %dhist shows this history nicely formatted. You can also
2718 do 'cd -<tab>' to see directory history conveniently.
2720 do 'cd -<tab>' to see directory history conveniently.
2719
2721
2720 Usage:
2722 Usage:
2721
2723
2722 cd 'dir': changes to directory 'dir'.
2724 cd 'dir': changes to directory 'dir'.
2723
2725
2724 cd -: changes to the last visited directory.
2726 cd -: changes to the last visited directory.
2725
2727
2726 cd -<n>: changes to the n-th directory in the directory history.
2728 cd -<n>: changes to the n-th directory in the directory history.
2727
2729
2728 cd --foo: change to directory that matches 'foo' in history
2730 cd --foo: change to directory that matches 'foo' in history
2729
2731
2730 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2732 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2731 (note: cd <bookmark_name> is enough if there is no
2733 (note: cd <bookmark_name> is enough if there is no
2732 directory <bookmark_name>, but a bookmark with the name exists.)
2734 directory <bookmark_name>, but a bookmark with the name exists.)
2733 'cd -b <tab>' allows you to tab-complete bookmark names.
2735 'cd -b <tab>' allows you to tab-complete bookmark names.
2734
2736
2735 Options:
2737 Options:
2736
2738
2737 -q: quiet. Do not print the working directory after the cd command is
2739 -q: quiet. Do not print the working directory after the cd command is
2738 executed. By default IPython's cd command does print this directory,
2740 executed. By default IPython's cd command does print this directory,
2739 since the default prompts do not display path information.
2741 since the default prompts do not display path information.
2740
2742
2741 Note that !cd doesn't work for this purpose because the shell where
2743 Note that !cd doesn't work for this purpose because the shell where
2742 !command runs is immediately discarded after executing 'command'."""
2744 !command runs is immediately discarded after executing 'command'."""
2743
2745
2744 parameter_s = parameter_s.strip()
2746 parameter_s = parameter_s.strip()
2745 #bkms = self.shell.persist.get("bookmarks",{})
2747 #bkms = self.shell.persist.get("bookmarks",{})
2746
2748
2747 oldcwd = os.getcwd()
2749 oldcwd = os.getcwd()
2748 numcd = re.match(r'(-)(\d+)$',parameter_s)
2750 numcd = re.match(r'(-)(\d+)$',parameter_s)
2749 # jump in directory history by number
2751 # jump in directory history by number
2750 if numcd:
2752 if numcd:
2751 nn = int(numcd.group(2))
2753 nn = int(numcd.group(2))
2752 try:
2754 try:
2753 ps = self.shell.user_ns['_dh'][nn]
2755 ps = self.shell.user_ns['_dh'][nn]
2754 except IndexError:
2756 except IndexError:
2755 print 'The requested directory does not exist in history.'
2757 print 'The requested directory does not exist in history.'
2756 return
2758 return
2757 else:
2759 else:
2758 opts = {}
2760 opts = {}
2759 elif parameter_s.startswith('--'):
2761 elif parameter_s.startswith('--'):
2760 ps = None
2762 ps = None
2761 fallback = None
2763 fallback = None
2762 pat = parameter_s[2:]
2764 pat = parameter_s[2:]
2763 dh = self.shell.user_ns['_dh']
2765 dh = self.shell.user_ns['_dh']
2764 # first search only by basename (last component)
2766 # first search only by basename (last component)
2765 for ent in reversed(dh):
2767 for ent in reversed(dh):
2766 if pat in os.path.basename(ent) and os.path.isdir(ent):
2768 if pat in os.path.basename(ent) and os.path.isdir(ent):
2767 ps = ent
2769 ps = ent
2768 break
2770 break
2769
2771
2770 if fallback is None and pat in ent and os.path.isdir(ent):
2772 if fallback is None and pat in ent and os.path.isdir(ent):
2771 fallback = ent
2773 fallback = ent
2772
2774
2773 # if we have no last part match, pick the first full path match
2775 # if we have no last part match, pick the first full path match
2774 if ps is None:
2776 if ps is None:
2775 ps = fallback
2777 ps = fallback
2776
2778
2777 if ps is None:
2779 if ps is None:
2778 print "No matching entry in directory history"
2780 print "No matching entry in directory history"
2779 return
2781 return
2780 else:
2782 else:
2781 opts = {}
2783 opts = {}
2782
2784
2783
2785
2784 else:
2786 else:
2785 #turn all non-space-escaping backslashes to slashes,
2787 #turn all non-space-escaping backslashes to slashes,
2786 # for c:\windows\directory\names\
2788 # for c:\windows\directory\names\
2787 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2789 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2788 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2790 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2789 # jump to previous
2791 # jump to previous
2790 if ps == '-':
2792 if ps == '-':
2791 try:
2793 try:
2792 ps = self.shell.user_ns['_dh'][-2]
2794 ps = self.shell.user_ns['_dh'][-2]
2793 except IndexError:
2795 except IndexError:
2794 raise UsageError('%cd -: No previous directory to change to.')
2796 raise UsageError('%cd -: No previous directory to change to.')
2795 # jump to bookmark if needed
2797 # jump to bookmark if needed
2796 else:
2798 else:
2797 if not os.path.isdir(ps) or opts.has_key('b'):
2799 if not os.path.isdir(ps) or opts.has_key('b'):
2798 bkms = self.db.get('bookmarks', {})
2800 bkms = self.db.get('bookmarks', {})
2799
2801
2800 if bkms.has_key(ps):
2802 if bkms.has_key(ps):
2801 target = bkms[ps]
2803 target = bkms[ps]
2802 print '(bookmark:%s) -> %s' % (ps,target)
2804 print '(bookmark:%s) -> %s' % (ps,target)
2803 ps = target
2805 ps = target
2804 else:
2806 else:
2805 if opts.has_key('b'):
2807 if opts.has_key('b'):
2806 raise UsageError("Bookmark '%s' not found. "
2808 raise UsageError("Bookmark '%s' not found. "
2807 "Use '%%bookmark -l' to see your bookmarks." % ps)
2809 "Use '%%bookmark -l' to see your bookmarks." % ps)
2808
2810
2809 # at this point ps should point to the target dir
2811 # at this point ps should point to the target dir
2810 if ps:
2812 if ps:
2811 try:
2813 try:
2812 os.chdir(os.path.expanduser(ps))
2814 os.chdir(os.path.expanduser(ps))
2813 if self.shell.term_title:
2815 if self.shell.term_title:
2814 platutils.set_term_title('IPython: ' + abbrev_cwd())
2816 set_term_title('IPython: ' + abbrev_cwd())
2815 except OSError:
2817 except OSError:
2816 print sys.exc_info()[1]
2818 print sys.exc_info()[1]
2817 else:
2819 else:
2818 cwd = os.getcwd()
2820 cwd = os.getcwd()
2819 dhist = self.shell.user_ns['_dh']
2821 dhist = self.shell.user_ns['_dh']
2820 if oldcwd != cwd:
2822 if oldcwd != cwd:
2821 dhist.append(cwd)
2823 dhist.append(cwd)
2822 self.db['dhist'] = compress_dhist(dhist)[-100:]
2824 self.db['dhist'] = compress_dhist(dhist)[-100:]
2823
2825
2824 else:
2826 else:
2825 os.chdir(self.shell.home_dir)
2827 os.chdir(self.shell.home_dir)
2826 if self.shell.term_title:
2828 if self.shell.term_title:
2827 platutils.set_term_title('IPython: ' + '~')
2829 set_term_title('IPython: ' + '~')
2828 cwd = os.getcwd()
2830 cwd = os.getcwd()
2829 dhist = self.shell.user_ns['_dh']
2831 dhist = self.shell.user_ns['_dh']
2830
2832
2831 if oldcwd != cwd:
2833 if oldcwd != cwd:
2832 dhist.append(cwd)
2834 dhist.append(cwd)
2833 self.db['dhist'] = compress_dhist(dhist)[-100:]
2835 self.db['dhist'] = compress_dhist(dhist)[-100:]
2834 if not 'q' in opts and self.shell.user_ns['_dh']:
2836 if not 'q' in opts and self.shell.user_ns['_dh']:
2835 print self.shell.user_ns['_dh'][-1]
2837 print self.shell.user_ns['_dh'][-1]
2836
2838
2837
2839
2838 def magic_env(self, parameter_s=''):
2840 def magic_env(self, parameter_s=''):
2839 """List environment variables."""
2841 """List environment variables."""
2840
2842
2841 return os.environ.data
2843 return os.environ.data
2842
2844
2843 def magic_pushd(self, parameter_s=''):
2845 def magic_pushd(self, parameter_s=''):
2844 """Place the current dir on stack and change directory.
2846 """Place the current dir on stack and change directory.
2845
2847
2846 Usage:\\
2848 Usage:\\
2847 %pushd ['dirname']
2849 %pushd ['dirname']
2848 """
2850 """
2849
2851
2850 dir_s = self.shell.dir_stack
2852 dir_s = self.shell.dir_stack
2851 tgt = os.path.expanduser(parameter_s)
2853 tgt = os.path.expanduser(parameter_s)
2852 cwd = os.getcwd().replace(self.home_dir,'~')
2854 cwd = os.getcwd().replace(self.home_dir,'~')
2853 if tgt:
2855 if tgt:
2854 self.magic_cd(parameter_s)
2856 self.magic_cd(parameter_s)
2855 dir_s.insert(0,cwd)
2857 dir_s.insert(0,cwd)
2856 return self.magic_dirs()
2858 return self.magic_dirs()
2857
2859
2858 def magic_popd(self, parameter_s=''):
2860 def magic_popd(self, parameter_s=''):
2859 """Change to directory popped off the top of the stack.
2861 """Change to directory popped off the top of the stack.
2860 """
2862 """
2861 if not self.shell.dir_stack:
2863 if not self.shell.dir_stack:
2862 raise UsageError("%popd on empty stack")
2864 raise UsageError("%popd on empty stack")
2863 top = self.shell.dir_stack.pop(0)
2865 top = self.shell.dir_stack.pop(0)
2864 self.magic_cd(top)
2866 self.magic_cd(top)
2865 print "popd ->",top
2867 print "popd ->",top
2866
2868
2867 def magic_dirs(self, parameter_s=''):
2869 def magic_dirs(self, parameter_s=''):
2868 """Return the current directory stack."""
2870 """Return the current directory stack."""
2869
2871
2870 return self.shell.dir_stack
2872 return self.shell.dir_stack
2871
2873
2872 def magic_dhist(self, parameter_s=''):
2874 def magic_dhist(self, parameter_s=''):
2873 """Print your history of visited directories.
2875 """Print your history of visited directories.
2874
2876
2875 %dhist -> print full history\\
2877 %dhist -> print full history\\
2876 %dhist n -> print last n entries only\\
2878 %dhist n -> print last n entries only\\
2877 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2879 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2878
2880
2879 This history is automatically maintained by the %cd command, and
2881 This history is automatically maintained by the %cd command, and
2880 always available as the global list variable _dh. You can use %cd -<n>
2882 always available as the global list variable _dh. You can use %cd -<n>
2881 to go to directory number <n>.
2883 to go to directory number <n>.
2882
2884
2883 Note that most of time, you should view directory history by entering
2885 Note that most of time, you should view directory history by entering
2884 cd -<TAB>.
2886 cd -<TAB>.
2885
2887
2886 """
2888 """
2887
2889
2888 dh = self.shell.user_ns['_dh']
2890 dh = self.shell.user_ns['_dh']
2889 if parameter_s:
2891 if parameter_s:
2890 try:
2892 try:
2891 args = map(int,parameter_s.split())
2893 args = map(int,parameter_s.split())
2892 except:
2894 except:
2893 self.arg_err(Magic.magic_dhist)
2895 self.arg_err(Magic.magic_dhist)
2894 return
2896 return
2895 if len(args) == 1:
2897 if len(args) == 1:
2896 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2898 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2897 elif len(args) == 2:
2899 elif len(args) == 2:
2898 ini,fin = args
2900 ini,fin = args
2899 else:
2901 else:
2900 self.arg_err(Magic.magic_dhist)
2902 self.arg_err(Magic.magic_dhist)
2901 return
2903 return
2902 else:
2904 else:
2903 ini,fin = 0,len(dh)
2905 ini,fin = 0,len(dh)
2904 nlprint(dh,
2906 nlprint(dh,
2905 header = 'Directory history (kept in _dh)',
2907 header = 'Directory history (kept in _dh)',
2906 start=ini,stop=fin)
2908 start=ini,stop=fin)
2907
2909
2908 @testdec.skip_doctest
2910 @testdec.skip_doctest
2909 def magic_sc(self, parameter_s=''):
2911 def magic_sc(self, parameter_s=''):
2910 """Shell capture - execute a shell command and capture its output.
2912 """Shell capture - execute a shell command and capture its output.
2911
2913
2912 DEPRECATED. Suboptimal, retained for backwards compatibility.
2914 DEPRECATED. Suboptimal, retained for backwards compatibility.
2913
2915
2914 You should use the form 'var = !command' instead. Example:
2916 You should use the form 'var = !command' instead. Example:
2915
2917
2916 "%sc -l myfiles = ls ~" should now be written as
2918 "%sc -l myfiles = ls ~" should now be written as
2917
2919
2918 "myfiles = !ls ~"
2920 "myfiles = !ls ~"
2919
2921
2920 myfiles.s, myfiles.l and myfiles.n still apply as documented
2922 myfiles.s, myfiles.l and myfiles.n still apply as documented
2921 below.
2923 below.
2922
2924
2923 --
2925 --
2924 %sc [options] varname=command
2926 %sc [options] varname=command
2925
2927
2926 IPython will run the given command using commands.getoutput(), and
2928 IPython will run the given command using commands.getoutput(), and
2927 will then update the user's interactive namespace with a variable
2929 will then update the user's interactive namespace with a variable
2928 called varname, containing the value of the call. Your command can
2930 called varname, containing the value of the call. Your command can
2929 contain shell wildcards, pipes, etc.
2931 contain shell wildcards, pipes, etc.
2930
2932
2931 The '=' sign in the syntax is mandatory, and the variable name you
2933 The '=' sign in the syntax is mandatory, and the variable name you
2932 supply must follow Python's standard conventions for valid names.
2934 supply must follow Python's standard conventions for valid names.
2933
2935
2934 (A special format without variable name exists for internal use)
2936 (A special format without variable name exists for internal use)
2935
2937
2936 Options:
2938 Options:
2937
2939
2938 -l: list output. Split the output on newlines into a list before
2940 -l: list output. Split the output on newlines into a list before
2939 assigning it to the given variable. By default the output is stored
2941 assigning it to the given variable. By default the output is stored
2940 as a single string.
2942 as a single string.
2941
2943
2942 -v: verbose. Print the contents of the variable.
2944 -v: verbose. Print the contents of the variable.
2943
2945
2944 In most cases you should not need to split as a list, because the
2946 In most cases you should not need to split as a list, because the
2945 returned value is a special type of string which can automatically
2947 returned value is a special type of string which can automatically
2946 provide its contents either as a list (split on newlines) or as a
2948 provide its contents either as a list (split on newlines) or as a
2947 space-separated string. These are convenient, respectively, either
2949 space-separated string. These are convenient, respectively, either
2948 for sequential processing or to be passed to a shell command.
2950 for sequential processing or to be passed to a shell command.
2949
2951
2950 For example:
2952 For example:
2951
2953
2952 # all-random
2954 # all-random
2953
2955
2954 # Capture into variable a
2956 # Capture into variable a
2955 In [1]: sc a=ls *py
2957 In [1]: sc a=ls *py
2956
2958
2957 # a is a string with embedded newlines
2959 # a is a string with embedded newlines
2958 In [2]: a
2960 In [2]: a
2959 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2961 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2960
2962
2961 # which can be seen as a list:
2963 # which can be seen as a list:
2962 In [3]: a.l
2964 In [3]: a.l
2963 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2965 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2964
2966
2965 # or as a whitespace-separated string:
2967 # or as a whitespace-separated string:
2966 In [4]: a.s
2968 In [4]: a.s
2967 Out[4]: 'setup.py win32_manual_post_install.py'
2969 Out[4]: 'setup.py win32_manual_post_install.py'
2968
2970
2969 # a.s is useful to pass as a single command line:
2971 # a.s is useful to pass as a single command line:
2970 In [5]: !wc -l $a.s
2972 In [5]: !wc -l $a.s
2971 146 setup.py
2973 146 setup.py
2972 130 win32_manual_post_install.py
2974 130 win32_manual_post_install.py
2973 276 total
2975 276 total
2974
2976
2975 # while the list form is useful to loop over:
2977 # while the list form is useful to loop over:
2976 In [6]: for f in a.l:
2978 In [6]: for f in a.l:
2977 ...: !wc -l $f
2979 ...: !wc -l $f
2978 ...:
2980 ...:
2979 146 setup.py
2981 146 setup.py
2980 130 win32_manual_post_install.py
2982 130 win32_manual_post_install.py
2981
2983
2982 Similiarly, the lists returned by the -l option are also special, in
2984 Similiarly, the lists returned by the -l option are also special, in
2983 the sense that you can equally invoke the .s attribute on them to
2985 the sense that you can equally invoke the .s attribute on them to
2984 automatically get a whitespace-separated string from their contents:
2986 automatically get a whitespace-separated string from their contents:
2985
2987
2986 In [7]: sc -l b=ls *py
2988 In [7]: sc -l b=ls *py
2987
2989
2988 In [8]: b
2990 In [8]: b
2989 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2991 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2990
2992
2991 In [9]: b.s
2993 In [9]: b.s
2992 Out[9]: 'setup.py win32_manual_post_install.py'
2994 Out[9]: 'setup.py win32_manual_post_install.py'
2993
2995
2994 In summary, both the lists and strings used for ouptut capture have
2996 In summary, both the lists and strings used for ouptut capture have
2995 the following special attributes:
2997 the following special attributes:
2996
2998
2997 .l (or .list) : value as list.
2999 .l (or .list) : value as list.
2998 .n (or .nlstr): value as newline-separated string.
3000 .n (or .nlstr): value as newline-separated string.
2999 .s (or .spstr): value as space-separated string.
3001 .s (or .spstr): value as space-separated string.
3000 """
3002 """
3001
3003
3002 opts,args = self.parse_options(parameter_s,'lv')
3004 opts,args = self.parse_options(parameter_s,'lv')
3003 # Try to get a variable name and command to run
3005 # Try to get a variable name and command to run
3004 try:
3006 try:
3005 # the variable name must be obtained from the parse_options
3007 # the variable name must be obtained from the parse_options
3006 # output, which uses shlex.split to strip options out.
3008 # output, which uses shlex.split to strip options out.
3007 var,_ = args.split('=',1)
3009 var,_ = args.split('=',1)
3008 var = var.strip()
3010 var = var.strip()
3009 # But the the command has to be extracted from the original input
3011 # But the the command has to be extracted from the original input
3010 # parameter_s, not on what parse_options returns, to avoid the
3012 # parameter_s, not on what parse_options returns, to avoid the
3011 # quote stripping which shlex.split performs on it.
3013 # quote stripping which shlex.split performs on it.
3012 _,cmd = parameter_s.split('=',1)
3014 _,cmd = parameter_s.split('=',1)
3013 except ValueError:
3015 except ValueError:
3014 var,cmd = '',''
3016 var,cmd = '',''
3015 # If all looks ok, proceed
3017 # If all looks ok, proceed
3016 out,err = self.shell.getoutputerror(cmd)
3018 out,err = self.shell.getoutputerror(cmd)
3017 if err:
3019 if err:
3018 print >> Term.cerr,err
3020 print >> Term.cerr,err
3019 if opts.has_key('l'):
3021 if opts.has_key('l'):
3020 out = SList(out.split('\n'))
3022 out = SList(out.split('\n'))
3021 else:
3023 else:
3022 out = LSString(out)
3024 out = LSString(out)
3023 if opts.has_key('v'):
3025 if opts.has_key('v'):
3024 print '%s ==\n%s' % (var,pformat(out))
3026 print '%s ==\n%s' % (var,pformat(out))
3025 if var:
3027 if var:
3026 self.shell.user_ns.update({var:out})
3028 self.shell.user_ns.update({var:out})
3027 else:
3029 else:
3028 return out
3030 return out
3029
3031
3030 def magic_sx(self, parameter_s=''):
3032 def magic_sx(self, parameter_s=''):
3031 """Shell execute - run a shell command and capture its output.
3033 """Shell execute - run a shell command and capture its output.
3032
3034
3033 %sx command
3035 %sx command
3034
3036
3035 IPython will run the given command using commands.getoutput(), and
3037 IPython will run the given command using commands.getoutput(), and
3036 return the result formatted as a list (split on '\\n'). Since the
3038 return the result formatted as a list (split on '\\n'). Since the
3037 output is _returned_, it will be stored in ipython's regular output
3039 output is _returned_, it will be stored in ipython's regular output
3038 cache Out[N] and in the '_N' automatic variables.
3040 cache Out[N] and in the '_N' automatic variables.
3039
3041
3040 Notes:
3042 Notes:
3041
3043
3042 1) If an input line begins with '!!', then %sx is automatically
3044 1) If an input line begins with '!!', then %sx is automatically
3043 invoked. That is, while:
3045 invoked. That is, while:
3044 !ls
3046 !ls
3045 causes ipython to simply issue system('ls'), typing
3047 causes ipython to simply issue system('ls'), typing
3046 !!ls
3048 !!ls
3047 is a shorthand equivalent to:
3049 is a shorthand equivalent to:
3048 %sx ls
3050 %sx ls
3049
3051
3050 2) %sx differs from %sc in that %sx automatically splits into a list,
3052 2) %sx differs from %sc in that %sx automatically splits into a list,
3051 like '%sc -l'. The reason for this is to make it as easy as possible
3053 like '%sc -l'. The reason for this is to make it as easy as possible
3052 to process line-oriented shell output via further python commands.
3054 to process line-oriented shell output via further python commands.
3053 %sc is meant to provide much finer control, but requires more
3055 %sc is meant to provide much finer control, but requires more
3054 typing.
3056 typing.
3055
3057
3056 3) Just like %sc -l, this is a list with special attributes:
3058 3) Just like %sc -l, this is a list with special attributes:
3057
3059
3058 .l (or .list) : value as list.
3060 .l (or .list) : value as list.
3059 .n (or .nlstr): value as newline-separated string.
3061 .n (or .nlstr): value as newline-separated string.
3060 .s (or .spstr): value as whitespace-separated string.
3062 .s (or .spstr): value as whitespace-separated string.
3061
3063
3062 This is very useful when trying to use such lists as arguments to
3064 This is very useful when trying to use such lists as arguments to
3063 system commands."""
3065 system commands."""
3064
3066
3065 if parameter_s:
3067 if parameter_s:
3066 out,err = self.shell.getoutputerror(parameter_s)
3068 out,err = self.shell.getoutputerror(parameter_s)
3067 if err:
3069 if err:
3068 print >> Term.cerr,err
3070 print >> Term.cerr,err
3069 return SList(out.split('\n'))
3071 return SList(out.split('\n'))
3070
3072
3071 def magic_bg(self, parameter_s=''):
3073 def magic_bg(self, parameter_s=''):
3072 """Run a job in the background, in a separate thread.
3074 """Run a job in the background, in a separate thread.
3073
3075
3074 For example,
3076 For example,
3075
3077
3076 %bg myfunc(x,y,z=1)
3078 %bg myfunc(x,y,z=1)
3077
3079
3078 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3080 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3079 execution starts, a message will be printed indicating the job
3081 execution starts, a message will be printed indicating the job
3080 number. If your job number is 5, you can use
3082 number. If your job number is 5, you can use
3081
3083
3082 myvar = jobs.result(5) or myvar = jobs[5].result
3084 myvar = jobs.result(5) or myvar = jobs[5].result
3083
3085
3084 to assign this result to variable 'myvar'.
3086 to assign this result to variable 'myvar'.
3085
3087
3086 IPython has a job manager, accessible via the 'jobs' object. You can
3088 IPython has a job manager, accessible via the 'jobs' object. You can
3087 type jobs? to get more information about it, and use jobs.<TAB> to see
3089 type jobs? to get more information about it, and use jobs.<TAB> to see
3088 its attributes. All attributes not starting with an underscore are
3090 its attributes. All attributes not starting with an underscore are
3089 meant for public use.
3091 meant for public use.
3090
3092
3091 In particular, look at the jobs.new() method, which is used to create
3093 In particular, look at the jobs.new() method, which is used to create
3092 new jobs. This magic %bg function is just a convenience wrapper
3094 new jobs. This magic %bg function is just a convenience wrapper
3093 around jobs.new(), for expression-based jobs. If you want to create a
3095 around jobs.new(), for expression-based jobs. If you want to create a
3094 new job with an explicit function object and arguments, you must call
3096 new job with an explicit function object and arguments, you must call
3095 jobs.new() directly.
3097 jobs.new() directly.
3096
3098
3097 The jobs.new docstring also describes in detail several important
3099 The jobs.new docstring also describes in detail several important
3098 caveats associated with a thread-based model for background job
3100 caveats associated with a thread-based model for background job
3099 execution. Type jobs.new? for details.
3101 execution. Type jobs.new? for details.
3100
3102
3101 You can check the status of all jobs with jobs.status().
3103 You can check the status of all jobs with jobs.status().
3102
3104
3103 The jobs variable is set by IPython into the Python builtin namespace.
3105 The jobs variable is set by IPython into the Python builtin namespace.
3104 If you ever declare a variable named 'jobs', you will shadow this
3106 If you ever declare a variable named 'jobs', you will shadow this
3105 name. You can either delete your global jobs variable to regain
3107 name. You can either delete your global jobs variable to regain
3106 access to the job manager, or make a new name and assign it manually
3108 access to the job manager, or make a new name and assign it manually
3107 to the manager (stored in IPython's namespace). For example, to
3109 to the manager (stored in IPython's namespace). For example, to
3108 assign the job manager to the Jobs name, use:
3110 assign the job manager to the Jobs name, use:
3109
3111
3110 Jobs = __builtins__.jobs"""
3112 Jobs = __builtins__.jobs"""
3111
3113
3112 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3114 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3113
3115
3114 def magic_r(self, parameter_s=''):
3116 def magic_r(self, parameter_s=''):
3115 """Repeat previous input.
3117 """Repeat previous input.
3116
3118
3117 Note: Consider using the more powerfull %rep instead!
3119 Note: Consider using the more powerfull %rep instead!
3118
3120
3119 If given an argument, repeats the previous command which starts with
3121 If given an argument, repeats the previous command which starts with
3120 the same string, otherwise it just repeats the previous input.
3122 the same string, otherwise it just repeats the previous input.
3121
3123
3122 Shell escaped commands (with ! as first character) are not recognized
3124 Shell escaped commands (with ! as first character) are not recognized
3123 by this system, only pure python code and magic commands.
3125 by this system, only pure python code and magic commands.
3124 """
3126 """
3125
3127
3126 start = parameter_s.strip()
3128 start = parameter_s.strip()
3127 esc_magic = ESC_MAGIC
3129 esc_magic = ESC_MAGIC
3128 # Identify magic commands even if automagic is on (which means
3130 # Identify magic commands even if automagic is on (which means
3129 # the in-memory version is different from that typed by the user).
3131 # the in-memory version is different from that typed by the user).
3130 if self.shell.automagic:
3132 if self.shell.automagic:
3131 start_magic = esc_magic+start
3133 start_magic = esc_magic+start
3132 else:
3134 else:
3133 start_magic = start
3135 start_magic = start
3134 # Look through the input history in reverse
3136 # Look through the input history in reverse
3135 for n in range(len(self.shell.input_hist)-2,0,-1):
3137 for n in range(len(self.shell.input_hist)-2,0,-1):
3136 input = self.shell.input_hist[n]
3138 input = self.shell.input_hist[n]
3137 # skip plain 'r' lines so we don't recurse to infinity
3139 # skip plain 'r' lines so we don't recurse to infinity
3138 if input != '_ip.magic("r")\n' and \
3140 if input != '_ip.magic("r")\n' and \
3139 (input.startswith(start) or input.startswith(start_magic)):
3141 (input.startswith(start) or input.startswith(start_magic)):
3140 #print 'match',`input` # dbg
3142 #print 'match',`input` # dbg
3141 print 'Executing:',input,
3143 print 'Executing:',input,
3142 self.shell.runlines(input)
3144 self.shell.runlines(input)
3143 return
3145 return
3144 print 'No previous input matching `%s` found.' % start
3146 print 'No previous input matching `%s` found.' % start
3145
3147
3146
3148
3147 def magic_bookmark(self, parameter_s=''):
3149 def magic_bookmark(self, parameter_s=''):
3148 """Manage IPython's bookmark system.
3150 """Manage IPython's bookmark system.
3149
3151
3150 %bookmark <name> - set bookmark to current dir
3152 %bookmark <name> - set bookmark to current dir
3151 %bookmark <name> <dir> - set bookmark to <dir>
3153 %bookmark <name> <dir> - set bookmark to <dir>
3152 %bookmark -l - list all bookmarks
3154 %bookmark -l - list all bookmarks
3153 %bookmark -d <name> - remove bookmark
3155 %bookmark -d <name> - remove bookmark
3154 %bookmark -r - remove all bookmarks
3156 %bookmark -r - remove all bookmarks
3155
3157
3156 You can later on access a bookmarked folder with:
3158 You can later on access a bookmarked folder with:
3157 %cd -b <name>
3159 %cd -b <name>
3158 or simply '%cd <name>' if there is no directory called <name> AND
3160 or simply '%cd <name>' if there is no directory called <name> AND
3159 there is such a bookmark defined.
3161 there is such a bookmark defined.
3160
3162
3161 Your bookmarks persist through IPython sessions, but they are
3163 Your bookmarks persist through IPython sessions, but they are
3162 associated with each profile."""
3164 associated with each profile."""
3163
3165
3164 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3166 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3165 if len(args) > 2:
3167 if len(args) > 2:
3166 raise UsageError("%bookmark: too many arguments")
3168 raise UsageError("%bookmark: too many arguments")
3167
3169
3168 bkms = self.db.get('bookmarks',{})
3170 bkms = self.db.get('bookmarks',{})
3169
3171
3170 if opts.has_key('d'):
3172 if opts.has_key('d'):
3171 try:
3173 try:
3172 todel = args[0]
3174 todel = args[0]
3173 except IndexError:
3175 except IndexError:
3174 raise UsageError(
3176 raise UsageError(
3175 "%bookmark -d: must provide a bookmark to delete")
3177 "%bookmark -d: must provide a bookmark to delete")
3176 else:
3178 else:
3177 try:
3179 try:
3178 del bkms[todel]
3180 del bkms[todel]
3179 except KeyError:
3181 except KeyError:
3180 raise UsageError(
3182 raise UsageError(
3181 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3183 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3182
3184
3183 elif opts.has_key('r'):
3185 elif opts.has_key('r'):
3184 bkms = {}
3186 bkms = {}
3185 elif opts.has_key('l'):
3187 elif opts.has_key('l'):
3186 bks = bkms.keys()
3188 bks = bkms.keys()
3187 bks.sort()
3189 bks.sort()
3188 if bks:
3190 if bks:
3189 size = max(map(len,bks))
3191 size = max(map(len,bks))
3190 else:
3192 else:
3191 size = 0
3193 size = 0
3192 fmt = '%-'+str(size)+'s -> %s'
3194 fmt = '%-'+str(size)+'s -> %s'
3193 print 'Current bookmarks:'
3195 print 'Current bookmarks:'
3194 for bk in bks:
3196 for bk in bks:
3195 print fmt % (bk,bkms[bk])
3197 print fmt % (bk,bkms[bk])
3196 else:
3198 else:
3197 if not args:
3199 if not args:
3198 raise UsageError("%bookmark: You must specify the bookmark name")
3200 raise UsageError("%bookmark: You must specify the bookmark name")
3199 elif len(args)==1:
3201 elif len(args)==1:
3200 bkms[args[0]] = os.getcwd()
3202 bkms[args[0]] = os.getcwd()
3201 elif len(args)==2:
3203 elif len(args)==2:
3202 bkms[args[0]] = args[1]
3204 bkms[args[0]] = args[1]
3203 self.db['bookmarks'] = bkms
3205 self.db['bookmarks'] = bkms
3204
3206
3205 def magic_pycat(self, parameter_s=''):
3207 def magic_pycat(self, parameter_s=''):
3206 """Show a syntax-highlighted file through a pager.
3208 """Show a syntax-highlighted file through a pager.
3207
3209
3208 This magic is similar to the cat utility, but it will assume the file
3210 This magic is similar to the cat utility, but it will assume the file
3209 to be Python source and will show it with syntax highlighting. """
3211 to be Python source and will show it with syntax highlighting. """
3210
3212
3211 try:
3213 try:
3212 filename = get_py_filename(parameter_s)
3214 filename = get_py_filename(parameter_s)
3213 cont = file_read(filename)
3215 cont = file_read(filename)
3214 except IOError:
3216 except IOError:
3215 try:
3217 try:
3216 cont = eval(parameter_s,self.user_ns)
3218 cont = eval(parameter_s,self.user_ns)
3217 except NameError:
3219 except NameError:
3218 cont = None
3220 cont = None
3219 if cont is None:
3221 if cont is None:
3220 print "Error: no such file or variable"
3222 print "Error: no such file or variable"
3221 return
3223 return
3222
3224
3223 page(self.shell.pycolorize(cont),
3225 page(self.shell.pycolorize(cont),
3224 screen_lines=self.shell.usable_screen_length)
3226 screen_lines=self.shell.usable_screen_length)
3225
3227
3226 def _rerun_pasted(self):
3228 def _rerun_pasted(self):
3227 """ Rerun a previously pasted command.
3229 """ Rerun a previously pasted command.
3228 """
3230 """
3229 b = self.user_ns.get('pasted_block', None)
3231 b = self.user_ns.get('pasted_block', None)
3230 if b is None:
3232 if b is None:
3231 raise UsageError('No previous pasted block available')
3233 raise UsageError('No previous pasted block available')
3232 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3234 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3233 exec b in self.user_ns
3235 exec b in self.user_ns
3234
3236
3235 def _get_pasted_lines(self, sentinel):
3237 def _get_pasted_lines(self, sentinel):
3236 """ Yield pasted lines until the user enters the given sentinel value.
3238 """ Yield pasted lines until the user enters the given sentinel value.
3237 """
3239 """
3238 from IPython.core import iplib
3240 from IPython.core import iplib
3239 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3241 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3240 while True:
3242 while True:
3241 l = iplib.raw_input_original(':')
3243 l = iplib.raw_input_original(':')
3242 if l == sentinel:
3244 if l == sentinel:
3243 return
3245 return
3244 else:
3246 else:
3245 yield l
3247 yield l
3246
3248
3247 def _strip_pasted_lines_for_code(self, raw_lines):
3249 def _strip_pasted_lines_for_code(self, raw_lines):
3248 """ Strip non-code parts of a sequence of lines to return a block of
3250 """ Strip non-code parts of a sequence of lines to return a block of
3249 code.
3251 code.
3250 """
3252 """
3251 # Regular expressions that declare text we strip from the input:
3253 # Regular expressions that declare text we strip from the input:
3252 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3254 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3253 r'^\s*(\s?>)+', # Python input prompt
3255 r'^\s*(\s?>)+', # Python input prompt
3254 r'^\s*\.{3,}', # Continuation prompts
3256 r'^\s*\.{3,}', # Continuation prompts
3255 r'^\++',
3257 r'^\++',
3256 ]
3258 ]
3257
3259
3258 strip_from_start = map(re.compile,strip_re)
3260 strip_from_start = map(re.compile,strip_re)
3259
3261
3260 lines = []
3262 lines = []
3261 for l in raw_lines:
3263 for l in raw_lines:
3262 for pat in strip_from_start:
3264 for pat in strip_from_start:
3263 l = pat.sub('',l)
3265 l = pat.sub('',l)
3264 lines.append(l)
3266 lines.append(l)
3265
3267
3266 block = "\n".join(lines) + '\n'
3268 block = "\n".join(lines) + '\n'
3267 #print "block:\n",block
3269 #print "block:\n",block
3268 return block
3270 return block
3269
3271
3270 def _execute_block(self, block, par):
3272 def _execute_block(self, block, par):
3271 """ Execute a block, or store it in a variable, per the user's request.
3273 """ Execute a block, or store it in a variable, per the user's request.
3272 """
3274 """
3273 if not par:
3275 if not par:
3274 b = textwrap.dedent(block)
3276 b = textwrap.dedent(block)
3275 self.user_ns['pasted_block'] = b
3277 self.user_ns['pasted_block'] = b
3276 exec b in self.user_ns
3278 exec b in self.user_ns
3277 else:
3279 else:
3278 self.user_ns[par] = SList(block.splitlines())
3280 self.user_ns[par] = SList(block.splitlines())
3279 print "Block assigned to '%s'" % par
3281 print "Block assigned to '%s'" % par
3280
3282
3281 def magic_cpaste(self, parameter_s=''):
3283 def magic_cpaste(self, parameter_s=''):
3282 """Allows you to paste & execute a pre-formatted code block from clipboard.
3284 """Allows you to paste & execute a pre-formatted code block from clipboard.
3283
3285
3284 You must terminate the block with '--' (two minus-signs) alone on the
3286 You must terminate the block with '--' (two minus-signs) alone on the
3285 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3287 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3286 is the new sentinel for this operation)
3288 is the new sentinel for this operation)
3287
3289
3288 The block is dedented prior to execution to enable execution of method
3290 The block is dedented prior to execution to enable execution of method
3289 definitions. '>' and '+' characters at the beginning of a line are
3291 definitions. '>' and '+' characters at the beginning of a line are
3290 ignored, to allow pasting directly from e-mails, diff files and
3292 ignored, to allow pasting directly from e-mails, diff files and
3291 doctests (the '...' continuation prompt is also stripped). The
3293 doctests (the '...' continuation prompt is also stripped). The
3292 executed block is also assigned to variable named 'pasted_block' for
3294 executed block is also assigned to variable named 'pasted_block' for
3293 later editing with '%edit pasted_block'.
3295 later editing with '%edit pasted_block'.
3294
3296
3295 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3297 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3296 This assigns the pasted block to variable 'foo' as string, without
3298 This assigns the pasted block to variable 'foo' as string, without
3297 dedenting or executing it (preceding >>> and + is still stripped)
3299 dedenting or executing it (preceding >>> and + is still stripped)
3298
3300
3299 '%cpaste -r' re-executes the block previously entered by cpaste.
3301 '%cpaste -r' re-executes the block previously entered by cpaste.
3300
3302
3301 Do not be alarmed by garbled output on Windows (it's a readline bug).
3303 Do not be alarmed by garbled output on Windows (it's a readline bug).
3302 Just press enter and type -- (and press enter again) and the block
3304 Just press enter and type -- (and press enter again) and the block
3303 will be what was just pasted.
3305 will be what was just pasted.
3304
3306
3305 IPython statements (magics, shell escapes) are not supported (yet).
3307 IPython statements (magics, shell escapes) are not supported (yet).
3306
3308
3307 See also
3309 See also
3308 --------
3310 --------
3309 paste: automatically pull code from clipboard.
3311 paste: automatically pull code from clipboard.
3310 """
3312 """
3311
3313
3312 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3314 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3313 par = args.strip()
3315 par = args.strip()
3314 if opts.has_key('r'):
3316 if opts.has_key('r'):
3315 self._rerun_pasted()
3317 self._rerun_pasted()
3316 return
3318 return
3317
3319
3318 sentinel = opts.get('s','--')
3320 sentinel = opts.get('s','--')
3319
3321
3320 block = self._strip_pasted_lines_for_code(
3322 block = self._strip_pasted_lines_for_code(
3321 self._get_pasted_lines(sentinel))
3323 self._get_pasted_lines(sentinel))
3322
3324
3323 self._execute_block(block, par)
3325 self._execute_block(block, par)
3324
3326
3325 def magic_paste(self, parameter_s=''):
3327 def magic_paste(self, parameter_s=''):
3326 """Allows you to paste & execute a pre-formatted code block from clipboard.
3328 """Allows you to paste & execute a pre-formatted code block from clipboard.
3327
3329
3328 The text is pulled directly from the clipboard without user
3330 The text is pulled directly from the clipboard without user
3329 intervention and printed back on the screen before execution (unless
3331 intervention and printed back on the screen before execution (unless
3330 the -q flag is given to force quiet mode).
3332 the -q flag is given to force quiet mode).
3331
3333
3332 The block is dedented prior to execution to enable execution of method
3334 The block is dedented prior to execution to enable execution of method
3333 definitions. '>' and '+' characters at the beginning of a line are
3335 definitions. '>' and '+' characters at the beginning of a line are
3334 ignored, to allow pasting directly from e-mails, diff files and
3336 ignored, to allow pasting directly from e-mails, diff files and
3335 doctests (the '...' continuation prompt is also stripped). The
3337 doctests (the '...' continuation prompt is also stripped). The
3336 executed block is also assigned to variable named 'pasted_block' for
3338 executed block is also assigned to variable named 'pasted_block' for
3337 later editing with '%edit pasted_block'.
3339 later editing with '%edit pasted_block'.
3338
3340
3339 You can also pass a variable name as an argument, e.g. '%paste foo'.
3341 You can also pass a variable name as an argument, e.g. '%paste foo'.
3340 This assigns the pasted block to variable 'foo' as string, without
3342 This assigns the pasted block to variable 'foo' as string, without
3341 dedenting or executing it (preceding >>> and + is still stripped)
3343 dedenting or executing it (preceding >>> and + is still stripped)
3342
3344
3343 Options
3345 Options
3344 -------
3346 -------
3345
3347
3346 -r: re-executes the block previously entered by cpaste.
3348 -r: re-executes the block previously entered by cpaste.
3347
3349
3348 -q: quiet mode: do not echo the pasted text back to the terminal.
3350 -q: quiet mode: do not echo the pasted text back to the terminal.
3349
3351
3350 IPython statements (magics, shell escapes) are not supported (yet).
3352 IPython statements (magics, shell escapes) are not supported (yet).
3351
3353
3352 See also
3354 See also
3353 --------
3355 --------
3354 cpaste: manually paste code into terminal until you mark its end.
3356 cpaste: manually paste code into terminal until you mark its end.
3355 """
3357 """
3356 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3358 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3357 par = args.strip()
3359 par = args.strip()
3358 if opts.has_key('r'):
3360 if opts.has_key('r'):
3359 self._rerun_pasted()
3361 self._rerun_pasted()
3360 return
3362 return
3361
3363
3362 text = self.shell.hooks.clipboard_get()
3364 text = self.shell.hooks.clipboard_get()
3363 block = self._strip_pasted_lines_for_code(text.splitlines())
3365 block = self._strip_pasted_lines_for_code(text.splitlines())
3364
3366
3365 # By default, echo back to terminal unless quiet mode is requested
3367 # By default, echo back to terminal unless quiet mode is requested
3366 if not opts.has_key('q'):
3368 if not opts.has_key('q'):
3367 write = self.shell.write
3369 write = self.shell.write
3368 write(self.shell.pycolorize(block))
3370 write(self.shell.pycolorize(block))
3369 if not block.endswith('\n'):
3371 if not block.endswith('\n'):
3370 write('\n')
3372 write('\n')
3371 write("## -- End pasted text --\n")
3373 write("## -- End pasted text --\n")
3372
3374
3373 self._execute_block(block, par)
3375 self._execute_block(block, par)
3374
3376
3375 def magic_quickref(self,arg):
3377 def magic_quickref(self,arg):
3376 """ Show a quick reference sheet """
3378 """ Show a quick reference sheet """
3377 import IPython.core.usage
3379 import IPython.core.usage
3378 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3380 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3379
3381
3380 page(qr)
3382 page(qr)
3381
3383
3382 def magic_doctest_mode(self,parameter_s=''):
3384 def magic_doctest_mode(self,parameter_s=''):
3383 """Toggle doctest mode on and off.
3385 """Toggle doctest mode on and off.
3384
3386
3385 This mode allows you to toggle the prompt behavior between normal
3387 This mode allows you to toggle the prompt behavior between normal
3386 IPython prompts and ones that are as similar to the default IPython
3388 IPython prompts and ones that are as similar to the default IPython
3387 interpreter as possible.
3389 interpreter as possible.
3388
3390
3389 It also supports the pasting of code snippets that have leading '>>>'
3391 It also supports the pasting of code snippets that have leading '>>>'
3390 and '...' prompts in them. This means that you can paste doctests from
3392 and '...' prompts in them. This means that you can paste doctests from
3391 files or docstrings (even if they have leading whitespace), and the
3393 files or docstrings (even if they have leading whitespace), and the
3392 code will execute correctly. You can then use '%history -tn' to see
3394 code will execute correctly. You can then use '%history -tn' to see
3393 the translated history without line numbers; this will give you the
3395 the translated history without line numbers; this will give you the
3394 input after removal of all the leading prompts and whitespace, which
3396 input after removal of all the leading prompts and whitespace, which
3395 can be pasted back into an editor.
3397 can be pasted back into an editor.
3396
3398
3397 With these features, you can switch into this mode easily whenever you
3399 With these features, you can switch into this mode easily whenever you
3398 need to do testing and changes to doctests, without having to leave
3400 need to do testing and changes to doctests, without having to leave
3399 your existing IPython session.
3401 your existing IPython session.
3400 """
3402 """
3401
3403
3402 from IPython.utils.ipstruct import Struct
3404 from IPython.utils.ipstruct import Struct
3403
3405
3404 # Shorthands
3406 # Shorthands
3405 shell = self.shell
3407 shell = self.shell
3406 oc = shell.outputcache
3408 oc = shell.outputcache
3407 meta = shell.meta
3409 meta = shell.meta
3408 # dstore is a data store kept in the instance metadata bag to track any
3410 # dstore is a data store kept in the instance metadata bag to track any
3409 # changes we make, so we can undo them later.
3411 # changes we make, so we can undo them later.
3410 dstore = meta.setdefault('doctest_mode',Struct())
3412 dstore = meta.setdefault('doctest_mode',Struct())
3411 save_dstore = dstore.setdefault
3413 save_dstore = dstore.setdefault
3412
3414
3413 # save a few values we'll need to recover later
3415 # save a few values we'll need to recover later
3414 mode = save_dstore('mode',False)
3416 mode = save_dstore('mode',False)
3415 save_dstore('rc_pprint',shell.pprint)
3417 save_dstore('rc_pprint',shell.pprint)
3416 save_dstore('xmode',shell.InteractiveTB.mode)
3418 save_dstore('xmode',shell.InteractiveTB.mode)
3417 save_dstore('rc_separate_out',shell.separate_out)
3419 save_dstore('rc_separate_out',shell.separate_out)
3418 save_dstore('rc_separate_out2',shell.separate_out2)
3420 save_dstore('rc_separate_out2',shell.separate_out2)
3419 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3421 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3420 save_dstore('rc_separate_in',shell.separate_in)
3422 save_dstore('rc_separate_in',shell.separate_in)
3421
3423
3422 if mode == False:
3424 if mode == False:
3423 # turn on
3425 # turn on
3424 oc.prompt1.p_template = '>>> '
3426 oc.prompt1.p_template = '>>> '
3425 oc.prompt2.p_template = '... '
3427 oc.prompt2.p_template = '... '
3426 oc.prompt_out.p_template = ''
3428 oc.prompt_out.p_template = ''
3427
3429
3428 # Prompt separators like plain python
3430 # Prompt separators like plain python
3429 oc.input_sep = oc.prompt1.sep = ''
3431 oc.input_sep = oc.prompt1.sep = ''
3430 oc.output_sep = ''
3432 oc.output_sep = ''
3431 oc.output_sep2 = ''
3433 oc.output_sep2 = ''
3432
3434
3433 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3435 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3434 oc.prompt_out.pad_left = False
3436 oc.prompt_out.pad_left = False
3435
3437
3436 shell.pprint = False
3438 shell.pprint = False
3437
3439
3438 shell.magic_xmode('Plain')
3440 shell.magic_xmode('Plain')
3439
3441
3440 else:
3442 else:
3441 # turn off
3443 # turn off
3442 oc.prompt1.p_template = shell.prompt_in1
3444 oc.prompt1.p_template = shell.prompt_in1
3443 oc.prompt2.p_template = shell.prompt_in2
3445 oc.prompt2.p_template = shell.prompt_in2
3444 oc.prompt_out.p_template = shell.prompt_out
3446 oc.prompt_out.p_template = shell.prompt_out
3445
3447
3446 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3448 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3447
3449
3448 oc.output_sep = dstore.rc_separate_out
3450 oc.output_sep = dstore.rc_separate_out
3449 oc.output_sep2 = dstore.rc_separate_out2
3451 oc.output_sep2 = dstore.rc_separate_out2
3450
3452
3451 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3453 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3452 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3454 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3453
3455
3454 shell.pprint = dstore.rc_pprint
3456 shell.pprint = dstore.rc_pprint
3455
3457
3456 shell.magic_xmode(dstore.xmode)
3458 shell.magic_xmode(dstore.xmode)
3457
3459
3458 # Store new mode and inform
3460 # Store new mode and inform
3459 dstore.mode = bool(1-int(mode))
3461 dstore.mode = bool(1-int(mode))
3460 print 'Doctest mode is:',
3462 print 'Doctest mode is:',
3461 print ['OFF','ON'][dstore.mode]
3463 print ['OFF','ON'][dstore.mode]
3462
3464
3463 def magic_gui(self, parameter_s=''):
3465 def magic_gui(self, parameter_s=''):
3464 """Enable or disable IPython GUI event loop integration.
3466 """Enable or disable IPython GUI event loop integration.
3465
3467
3466 %gui [-a] [GUINAME]
3468 %gui [-a] [GUINAME]
3467
3469
3468 This magic replaces IPython's threaded shells that were activated
3470 This magic replaces IPython's threaded shells that were activated
3469 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3471 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3470 can now be enabled, disabled and swtiched at runtime and keyboard
3472 can now be enabled, disabled and swtiched at runtime and keyboard
3471 interrupts should work without any problems. The following toolkits
3473 interrupts should work without any problems. The following toolkits
3472 are supported: wxPython, PyQt4, PyGTK, and Tk::
3474 are supported: wxPython, PyQt4, PyGTK, and Tk::
3473
3475
3474 %gui wx # enable wxPython event loop integration
3476 %gui wx # enable wxPython event loop integration
3475 %gui qt4|qt # enable PyQt4 event loop integration
3477 %gui qt4|qt # enable PyQt4 event loop integration
3476 %gui gtk # enable PyGTK event loop integration
3478 %gui gtk # enable PyGTK event loop integration
3477 %gui tk # enable Tk event loop integration
3479 %gui tk # enable Tk event loop integration
3478 %gui # disable all event loop integration
3480 %gui # disable all event loop integration
3479
3481
3480 WARNING: after any of these has been called you can simply create
3482 WARNING: after any of these has been called you can simply create
3481 an application object, but DO NOT start the event loop yourself, as
3483 an application object, but DO NOT start the event loop yourself, as
3482 we have already handled that.
3484 we have already handled that.
3483
3485
3484 If you want us to create an appropriate application object add the
3486 If you want us to create an appropriate application object add the
3485 "-a" flag to your command::
3487 "-a" flag to your command::
3486
3488
3487 %gui -a wx
3489 %gui -a wx
3488
3490
3489 This is highly recommended for most users.
3491 This is highly recommended for most users.
3490 """
3492 """
3491 opts, arg = self.parse_options(parameter_s,'a')
3493 opts, arg = self.parse_options(parameter_s,'a')
3492 if arg=='': arg = None
3494 if arg=='': arg = None
3493 return enable_gui(arg, 'a' in opts)
3495 return enable_gui(arg, 'a' in opts)
3494
3496
3495 def magic_load_ext(self, module_str):
3497 def magic_load_ext(self, module_str):
3496 """Load an IPython extension by its module name."""
3498 """Load an IPython extension by its module name."""
3497 return self.load_extension(module_str)
3499 return self.load_extension(module_str)
3498
3500
3499 def magic_unload_ext(self, module_str):
3501 def magic_unload_ext(self, module_str):
3500 """Unload an IPython extension by its module name."""
3502 """Unload an IPython extension by its module name."""
3501 self.unload_extension(module_str)
3503 self.unload_extension(module_str)
3502
3504
3503 def magic_reload_ext(self, module_str):
3505 def magic_reload_ext(self, module_str):
3504 """Reload an IPython extension by its module name."""
3506 """Reload an IPython extension by its module name."""
3505 self.reload_extension(module_str)
3507 self.reload_extension(module_str)
3506
3508
3507 @testdec.skip_doctest
3509 @testdec.skip_doctest
3508 def magic_install_profiles(self, s):
3510 def magic_install_profiles(self, s):
3509 """Install the default IPython profiles into the .ipython dir.
3511 """Install the default IPython profiles into the .ipython dir.
3510
3512
3511 If the default profiles have already been installed, they will not
3513 If the default profiles have already been installed, they will not
3512 be overwritten. You can force overwriting them by using the ``-o``
3514 be overwritten. You can force overwriting them by using the ``-o``
3513 option::
3515 option::
3514
3516
3515 In [1]: %install_profiles -o
3517 In [1]: %install_profiles -o
3516 """
3518 """
3517 if '-o' in s:
3519 if '-o' in s:
3518 overwrite = True
3520 overwrite = True
3519 else:
3521 else:
3520 overwrite = False
3522 overwrite = False
3521 from IPython.config import profile
3523 from IPython.config import profile
3522 profile_dir = os.path.split(profile.__file__)[0]
3524 profile_dir = os.path.split(profile.__file__)[0]
3523 ipython_dir = self.ipython_dir
3525 ipython_dir = self.ipython_dir
3524 files = os.listdir(profile_dir)
3526 files = os.listdir(profile_dir)
3525
3527
3526 to_install = []
3528 to_install = []
3527 for f in files:
3529 for f in files:
3528 if f.startswith('ipython_config'):
3530 if f.startswith('ipython_config'):
3529 src = os.path.join(profile_dir, f)
3531 src = os.path.join(profile_dir, f)
3530 dst = os.path.join(ipython_dir, f)
3532 dst = os.path.join(ipython_dir, f)
3531 if (not os.path.isfile(dst)) or overwrite:
3533 if (not os.path.isfile(dst)) or overwrite:
3532 to_install.append((f, src, dst))
3534 to_install.append((f, src, dst))
3533 if len(to_install)>0:
3535 if len(to_install)>0:
3534 print "Installing profiles to: ", ipython_dir
3536 print "Installing profiles to: ", ipython_dir
3535 for (f, src, dst) in to_install:
3537 for (f, src, dst) in to_install:
3536 shutil.copy(src, dst)
3538 shutil.copy(src, dst)
3537 print " %s" % f
3539 print " %s" % f
3538
3540
3539 def magic_install_default_config(self, s):
3541 def magic_install_default_config(self, s):
3540 """Install IPython's default config file into the .ipython dir.
3542 """Install IPython's default config file into the .ipython dir.
3541
3543
3542 If the default config file (:file:`ipython_config.py`) is already
3544 If the default config file (:file:`ipython_config.py`) is already
3543 installed, it will not be overwritten. You can force overwriting
3545 installed, it will not be overwritten. You can force overwriting
3544 by using the ``-o`` option::
3546 by using the ``-o`` option::
3545
3547
3546 In [1]: %install_default_config
3548 In [1]: %install_default_config
3547 """
3549 """
3548 if '-o' in s:
3550 if '-o' in s:
3549 overwrite = True
3551 overwrite = True
3550 else:
3552 else:
3551 overwrite = False
3553 overwrite = False
3552 from IPython.config import default
3554 from IPython.config import default
3553 config_dir = os.path.split(default.__file__)[0]
3555 config_dir = os.path.split(default.__file__)[0]
3554 ipython_dir = self.ipython_dir
3556 ipython_dir = self.ipython_dir
3555 default_config_file_name = 'ipython_config.py'
3557 default_config_file_name = 'ipython_config.py'
3556 src = os.path.join(config_dir, default_config_file_name)
3558 src = os.path.join(config_dir, default_config_file_name)
3557 dst = os.path.join(ipython_dir, default_config_file_name)
3559 dst = os.path.join(ipython_dir, default_config_file_name)
3558 if (not os.path.isfile(dst)) or overwrite:
3560 if (not os.path.isfile(dst)) or overwrite:
3559 shutil.copy(src, dst)
3561 shutil.copy(src, dst)
3560 print "Installing default config file: %s" % dst
3562 print "Installing default config file: %s" % dst
3561
3563
3562 # Pylab support: simple wrappers that activate pylab, load gui input
3564 # Pylab support: simple wrappers that activate pylab, load gui input
3563 # handling and modify slightly %run
3565 # handling and modify slightly %run
3564
3566
3565 @testdec.skip_doctest
3567 @testdec.skip_doctest
3566 def _pylab_magic_run(self, parameter_s=''):
3568 def _pylab_magic_run(self, parameter_s=''):
3567 Magic.magic_run(self, parameter_s,
3569 Magic.magic_run(self, parameter_s,
3568 runner=mpl_runner(self.shell.safe_execfile))
3570 runner=mpl_runner(self.shell.safe_execfile))
3569
3571
3570 _pylab_magic_run.__doc__ = magic_run.__doc__
3572 _pylab_magic_run.__doc__ = magic_run.__doc__
3571
3573
3572 @testdec.skip_doctest
3574 @testdec.skip_doctest
3573 def magic_pylab(self, s):
3575 def magic_pylab(self, s):
3574 """Load numpy and matplotlib to work interactively.
3576 """Load numpy and matplotlib to work interactively.
3575
3577
3576 %pylab [GUINAME]
3578 %pylab [GUINAME]
3577
3579
3578 This function lets you activate pylab (matplotlib, numpy and
3580 This function lets you activate pylab (matplotlib, numpy and
3579 interactive support) at any point during an IPython session.
3581 interactive support) at any point during an IPython session.
3580
3582
3581 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3583 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3582 pylab and mlab, as well as all names from numpy and pylab.
3584 pylab and mlab, as well as all names from numpy and pylab.
3583
3585
3584 Parameters
3586 Parameters
3585 ----------
3587 ----------
3586 guiname : optional
3588 guiname : optional
3587 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3589 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3588 'tk'). If given, the corresponding Matplotlib backend is used,
3590 'tk'). If given, the corresponding Matplotlib backend is used,
3589 otherwise matplotlib's default (which you can override in your
3591 otherwise matplotlib's default (which you can override in your
3590 matplotlib config file) is used.
3592 matplotlib config file) is used.
3591
3593
3592 Examples
3594 Examples
3593 --------
3595 --------
3594 In this case, where the MPL default is TkAgg:
3596 In this case, where the MPL default is TkAgg:
3595 In [2]: %pylab
3597 In [2]: %pylab
3596
3598
3597 Welcome to pylab, a matplotlib-based Python environment.
3599 Welcome to pylab, a matplotlib-based Python environment.
3598 Backend in use: TkAgg
3600 Backend in use: TkAgg
3599 For more information, type 'help(pylab)'.
3601 For more information, type 'help(pylab)'.
3600
3602
3601 But you can explicitly request a different backend:
3603 But you can explicitly request a different backend:
3602 In [3]: %pylab qt
3604 In [3]: %pylab qt
3603
3605
3604 Welcome to pylab, a matplotlib-based Python environment.
3606 Welcome to pylab, a matplotlib-based Python environment.
3605 Backend in use: Qt4Agg
3607 Backend in use: Qt4Agg
3606 For more information, type 'help(pylab)'.
3608 For more information, type 'help(pylab)'.
3607 """
3609 """
3608 self.shell.enable_pylab(s)
3610 self.shell.enable_pylab(s)
3609
3611
3610 def magic_tb(self, s):
3612 def magic_tb(self, s):
3611 """Print the last traceback with the currently active exception mode.
3613 """Print the last traceback with the currently active exception mode.
3612
3614
3613 See %xmode for changing exception reporting modes."""
3615 See %xmode for changing exception reporting modes."""
3614 self.shell.showtraceback()
3616 self.shell.showtraceback()
3615
3617
3616 # end Magic
3618 # end Magic
@@ -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 #----------------------------------------------------------------------------
221
225 def get_pager_cmd(pager_cmd = None):
222 def get_pager_cmd(pager_cmd=None):
226 """Return a pager command.
223 """Return a pager command.
227
224
228 Makes some attempts at finding an OS-correct one."""
225 Makes some attempts at finding an OS-correct one.
229
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
305 return snip
306
@@ -1,1052 +1,1051 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import keyword
31 import os
32 import re
30 import re
33 import sys
34
31
35 from IPython.core.alias import AliasManager
32 from IPython.core.alias import AliasManager
36 from IPython.core.autocall import IPyAutocall
33 from IPython.core.autocall import IPyAutocall
37 from IPython.core.component import Component
34 from IPython.core.component import Component
38 from IPython.core.splitinput import split_user_input
35 from IPython.core.splitinput import split_user_input
39 from IPython.core.page import page
36 from IPython.core.page import page
40
37
41 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
42 from IPython.utils.genutils import make_quoted_expr, Term
39 from IPython.utils.io import Term
40 from IPython.utils.text import make_quoted_expr
43 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
44
42
45 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
46 # Global utilities, errors and constants
44 # Global utilities, errors and constants
47 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
48
46
49 # Warning, these cannot be changed unless various regular expressions
47 # Warning, these cannot be changed unless various regular expressions
50 # are updated in a number of places. Not great, but at least we told you.
48 # are updated in a number of places. Not great, but at least we told you.
51 ESC_SHELL = '!'
49 ESC_SHELL = '!'
52 ESC_SH_CAP = '!!'
50 ESC_SH_CAP = '!!'
53 ESC_HELP = '?'
51 ESC_HELP = '?'
54 ESC_MAGIC = '%'
52 ESC_MAGIC = '%'
55 ESC_QUOTE = ','
53 ESC_QUOTE = ','
56 ESC_QUOTE2 = ';'
54 ESC_QUOTE2 = ';'
57 ESC_PAREN = '/'
55 ESC_PAREN = '/'
58
56
59
57
60 class PrefilterError(Exception):
58 class PrefilterError(Exception):
61 pass
59 pass
62
60
63
61
64 # RegExp to identify potential function names
62 # RegExp to identify potential function names
65 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
66
64
67 # RegExp to exclude strings with this start from autocalling. In
65 # RegExp to exclude strings with this start from autocalling. In
68 # particular, all binary operators should be excluded, so that if foo is
66 # particular, all binary operators should be excluded, so that if foo is
69 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
70 # characters '!=()' don't need to be checked for, as the checkPythonChars
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
71 # routine explicitely does so, to catch direct calls and rebindings of
69 # routine explicitely does so, to catch direct calls and rebindings of
72 # existing names.
70 # existing names.
73
71
74 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
75 # it affects the rest of the group in square brackets.
73 # it affects the rest of the group in square brackets.
76 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
77 r'|^is |^not |^in |^and |^or ')
75 r'|^is |^not |^in |^and |^or ')
78
76
79 # try to catch also methods for stuff in lists/tuples/dicts: off
77 # try to catch also methods for stuff in lists/tuples/dicts: off
80 # (experimental). For this to work, the line_split regexp would need
78 # (experimental). For this to work, the line_split regexp would need
81 # to be modified so it wouldn't break things at '['. That line is
79 # to be modified so it wouldn't break things at '['. That line is
82 # nasty enough that I shouldn't change it until I can test it _well_.
80 # nasty enough that I shouldn't change it until I can test it _well_.
83 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
84
82
85
83
86 # Handler Check Utilities
84 # Handler Check Utilities
87 def is_shadowed(identifier, ip):
85 def is_shadowed(identifier, ip):
88 """Is the given identifier defined in one of the namespaces which shadow
86 """Is the given identifier defined in one of the namespaces which shadow
89 the alias and magic namespaces? Note that an identifier is different
87 the alias and magic namespaces? Note that an identifier is different
90 than ifun, because it can not contain a '.' character."""
88 than ifun, because it can not contain a '.' character."""
91 # This is much safer than calling ofind, which can change state
89 # This is much safer than calling ofind, which can change state
92 return (identifier in ip.user_ns \
90 return (identifier in ip.user_ns \
93 or identifier in ip.internal_ns \
91 or identifier in ip.internal_ns \
94 or identifier in ip.ns_table['builtin'])
92 or identifier in ip.ns_table['builtin'])
95
93
96
94
97 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
98 # The LineInfo class used throughout
96 # The LineInfo class used throughout
99 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
100
98
101
99
102 class LineInfo(object):
100 class LineInfo(object):
103 """A single line of input and associated info.
101 """A single line of input and associated info.
104
102
105 Includes the following as properties:
103 Includes the following as properties:
106
104
107 line
105 line
108 The original, raw line
106 The original, raw line
109
107
110 continue_prompt
108 continue_prompt
111 Is this line a continuation in a sequence of multiline input?
109 Is this line a continuation in a sequence of multiline input?
112
110
113 pre
111 pre
114 The initial esc character or whitespace.
112 The initial esc character or whitespace.
115
113
116 pre_char
114 pre_char
117 The escape character(s) in pre or the empty string if there isn't one.
115 The escape character(s) in pre or the empty string if there isn't one.
118 Note that '!!' is a possible value for pre_char. Otherwise it will
116 Note that '!!' is a possible value for pre_char. Otherwise it will
119 always be a single character.
117 always be a single character.
120
118
121 pre_whitespace
119 pre_whitespace
122 The leading whitespace from pre if it exists. If there is a pre_char,
120 The leading whitespace from pre if it exists. If there is a pre_char,
123 this is just ''.
121 this is just ''.
124
122
125 ifun
123 ifun
126 The 'function part', which is basically the maximal initial sequence
124 The 'function part', which is basically the maximal initial sequence
127 of valid python identifiers and the '.' character. This is what is
125 of valid python identifiers and the '.' character. This is what is
128 checked for alias and magic transformations, used for auto-calling,
126 checked for alias and magic transformations, used for auto-calling,
129 etc.
127 etc.
130
128
131 the_rest
129 the_rest
132 Everything else on the line.
130 Everything else on the line.
133 """
131 """
134 def __init__(self, line, continue_prompt):
132 def __init__(self, line, continue_prompt):
135 self.line = line
133 self.line = line
136 self.continue_prompt = continue_prompt
134 self.continue_prompt = continue_prompt
137 self.pre, self.ifun, self.the_rest = split_user_input(line)
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
138
136
139 self.pre_char = self.pre.strip()
137 self.pre_char = self.pre.strip()
140 if self.pre_char:
138 if self.pre_char:
141 self.pre_whitespace = '' # No whitespace allowd before esc chars
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
142 else:
140 else:
143 self.pre_whitespace = self.pre
141 self.pre_whitespace = self.pre
144
142
145 self._oinfo = None
143 self._oinfo = None
146
144
147 def ofind(self, ip):
145 def ofind(self, ip):
148 """Do a full, attribute-walking lookup of the ifun in the various
146 """Do a full, attribute-walking lookup of the ifun in the various
149 namespaces for the given IPython InteractiveShell instance.
147 namespaces for the given IPython InteractiveShell instance.
150
148
151 Return a dict with keys: found,obj,ospace,ismagic
149 Return a dict with keys: found,obj,ospace,ismagic
152
150
153 Note: can cause state changes because of calling getattr, but should
151 Note: can cause state changes because of calling getattr, but should
154 only be run if autocall is on and if the line hasn't matched any
152 only be run if autocall is on and if the line hasn't matched any
155 other, less dangerous handlers.
153 other, less dangerous handlers.
156
154
157 Does cache the results of the call, so can be called multiple times
155 Does cache the results of the call, so can be called multiple times
158 without worrying about *further* damaging state.
156 without worrying about *further* damaging state.
159 """
157 """
160 if not self._oinfo:
158 if not self._oinfo:
159 # ip.shell._ofind is actually on the Magic class!
161 self._oinfo = ip.shell._ofind(self.ifun)
160 self._oinfo = ip.shell._ofind(self.ifun)
162 return self._oinfo
161 return self._oinfo
163
162
164 def __str__(self):
163 def __str__(self):
165 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
166
165
167
166
168 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
169 # Main Prefilter manager
168 # Main Prefilter manager
170 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
171
170
172
171
173 class PrefilterManager(Component):
172 class PrefilterManager(Component):
174 """Main prefilter component.
173 """Main prefilter component.
175
174
176 The IPython prefilter is run on all user input before it is run. The
175 The IPython prefilter is run on all user input before it is run. The
177 prefilter consumes lines of input and produces transformed lines of
176 prefilter consumes lines of input and produces transformed lines of
178 input.
177 input.
179
178
180 The iplementation consists of two phases:
179 The iplementation consists of two phases:
181
180
182 1. Transformers
181 1. Transformers
183 2. Checkers and handlers
182 2. Checkers and handlers
184
183
185 Over time, we plan on deprecating the checkers and handlers and doing
184 Over time, we plan on deprecating the checkers and handlers and doing
186 everything in the transformers.
185 everything in the transformers.
187
186
188 The transformers are instances of :class:`PrefilterTransformer` and have
187 The transformers are instances of :class:`PrefilterTransformer` and have
189 a single method :meth:`transform` that takes a line and returns a
188 a single method :meth:`transform` that takes a line and returns a
190 transformed line. The transformation can be accomplished using any
189 transformed line. The transformation can be accomplished using any
191 tool, but our current ones use regular expressions for speed. We also
190 tool, but our current ones use regular expressions for speed. We also
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
193
192
194 After all the transformers have been run, the line is fed to the checkers,
193 After all the transformers have been run, the line is fed to the checkers,
195 which are instances of :class:`PrefilterChecker`. The line is passed to
194 which are instances of :class:`PrefilterChecker`. The line is passed to
196 the :meth:`check` method, which either returns `None` or a
195 the :meth:`check` method, which either returns `None` or a
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
199 the line is passed to the :meth:`handle` method of the returned
198 the line is passed to the :meth:`handle` method of the returned
200 handler and no further checkers are tried.
199 handler and no further checkers are tried.
201
200
202 Both transformers and checkers have a `priority` attribute, that determines
201 Both transformers and checkers have a `priority` attribute, that determines
203 the order in which they are called. Smaller priorities are tried first.
202 the order in which they are called. Smaller priorities are tried first.
204
203
205 Both transformers and checkers also have `enabled` attribute, which is
204 Both transformers and checkers also have `enabled` attribute, which is
206 a boolean that determines if the instance is used.
205 a boolean that determines if the instance is used.
207
206
208 Users or developers can change the priority or enabled attribute of
207 Users or developers can change the priority or enabled attribute of
209 transformers or checkers, but they must call the :meth:`sort_checkers`
208 transformers or checkers, but they must call the :meth:`sort_checkers`
210 or :meth:`sort_transformers` method after changing the priority.
209 or :meth:`sort_transformers` method after changing the priority.
211 """
210 """
212
211
213 multi_line_specials = CBool(True, config=True)
212 multi_line_specials = CBool(True, config=True)
214
213
215 def __init__(self, parent, config=None):
214 def __init__(self, parent, config=None):
216 super(PrefilterManager, self).__init__(parent, config=config)
215 super(PrefilterManager, self).__init__(parent, config=config)
217 self.init_transformers()
216 self.init_transformers()
218 self.init_handlers()
217 self.init_handlers()
219 self.init_checkers()
218 self.init_checkers()
220
219
221 @auto_attr
220 @auto_attr
222 def shell(self):
221 def shell(self):
223 return Component.get_instances(
222 return Component.get_instances(
224 root=self.root,
223 root=self.root,
225 klass='IPython.core.iplib.InteractiveShell')[0]
224 klass='IPython.core.iplib.InteractiveShell')[0]
226
225
227 #-------------------------------------------------------------------------
226 #-------------------------------------------------------------------------
228 # API for managing transformers
227 # API for managing transformers
229 #-------------------------------------------------------------------------
228 #-------------------------------------------------------------------------
230
229
231 def init_transformers(self):
230 def init_transformers(self):
232 """Create the default transformers."""
231 """Create the default transformers."""
233 self._transformers = []
232 self._transformers = []
234 for transformer_cls in _default_transformers:
233 for transformer_cls in _default_transformers:
235 transformer_cls(self, config=self.config)
234 transformer_cls(self, config=self.config)
236
235
237 def sort_transformers(self):
236 def sort_transformers(self):
238 """Sort the transformers by priority.
237 """Sort the transformers by priority.
239
238
240 This must be called after the priority of a transformer is changed.
239 This must be called after the priority of a transformer is changed.
241 The :meth:`register_transformer` method calls this automatically.
240 The :meth:`register_transformer` method calls this automatically.
242 """
241 """
243 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
242 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
244
243
245 @property
244 @property
246 def transformers(self):
245 def transformers(self):
247 """Return a list of checkers, sorted by priority."""
246 """Return a list of checkers, sorted by priority."""
248 return self._transformers
247 return self._transformers
249
248
250 def register_transformer(self, transformer):
249 def register_transformer(self, transformer):
251 """Register a transformer instance."""
250 """Register a transformer instance."""
252 if transformer not in self._transformers:
251 if transformer not in self._transformers:
253 self._transformers.append(transformer)
252 self._transformers.append(transformer)
254 self.sort_transformers()
253 self.sort_transformers()
255
254
256 def unregister_transformer(self, transformer):
255 def unregister_transformer(self, transformer):
257 """Unregister a transformer instance."""
256 """Unregister a transformer instance."""
258 if transformer in self._transformers:
257 if transformer in self._transformers:
259 self._transformers.remove(transformer)
258 self._transformers.remove(transformer)
260
259
261 #-------------------------------------------------------------------------
260 #-------------------------------------------------------------------------
262 # API for managing checkers
261 # API for managing checkers
263 #-------------------------------------------------------------------------
262 #-------------------------------------------------------------------------
264
263
265 def init_checkers(self):
264 def init_checkers(self):
266 """Create the default checkers."""
265 """Create the default checkers."""
267 self._checkers = []
266 self._checkers = []
268 for checker in _default_checkers:
267 for checker in _default_checkers:
269 checker(self, config=self.config)
268 checker(self, config=self.config)
270
269
271 def sort_checkers(self):
270 def sort_checkers(self):
272 """Sort the checkers by priority.
271 """Sort the checkers by priority.
273
272
274 This must be called after the priority of a checker is changed.
273 This must be called after the priority of a checker is changed.
275 The :meth:`register_checker` method calls this automatically.
274 The :meth:`register_checker` method calls this automatically.
276 """
275 """
277 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
278
277
279 @property
278 @property
280 def checkers(self):
279 def checkers(self):
281 """Return a list of checkers, sorted by priority."""
280 """Return a list of checkers, sorted by priority."""
282 return self._checkers
281 return self._checkers
283
282
284 def register_checker(self, checker):
283 def register_checker(self, checker):
285 """Register a checker instance."""
284 """Register a checker instance."""
286 if checker not in self._checkers:
285 if checker not in self._checkers:
287 self._checkers.append(checker)
286 self._checkers.append(checker)
288 self.sort_checkers()
287 self.sort_checkers()
289
288
290 def unregister_checker(self, checker):
289 def unregister_checker(self, checker):
291 """Unregister a checker instance."""
290 """Unregister a checker instance."""
292 if checker in self._checkers:
291 if checker in self._checkers:
293 self._checkers.remove(checker)
292 self._checkers.remove(checker)
294
293
295 #-------------------------------------------------------------------------
294 #-------------------------------------------------------------------------
296 # API for managing checkers
295 # API for managing checkers
297 #-------------------------------------------------------------------------
296 #-------------------------------------------------------------------------
298
297
299 def init_handlers(self):
298 def init_handlers(self):
300 """Create the default handlers."""
299 """Create the default handlers."""
301 self._handlers = {}
300 self._handlers = {}
302 self._esc_handlers = {}
301 self._esc_handlers = {}
303 for handler in _default_handlers:
302 for handler in _default_handlers:
304 handler(self, config=self.config)
303 handler(self, config=self.config)
305
304
306 @property
305 @property
307 def handlers(self):
306 def handlers(self):
308 """Return a dict of all the handlers."""
307 """Return a dict of all the handlers."""
309 return self._handlers
308 return self._handlers
310
309
311 def register_handler(self, name, handler, esc_strings):
310 def register_handler(self, name, handler, esc_strings):
312 """Register a handler instance by name with esc_strings."""
311 """Register a handler instance by name with esc_strings."""
313 self._handlers[name] = handler
312 self._handlers[name] = handler
314 for esc_str in esc_strings:
313 for esc_str in esc_strings:
315 self._esc_handlers[esc_str] = handler
314 self._esc_handlers[esc_str] = handler
316
315
317 def unregister_handler(self, name, handler, esc_strings):
316 def unregister_handler(self, name, handler, esc_strings):
318 """Unregister a handler instance by name with esc_strings."""
317 """Unregister a handler instance by name with esc_strings."""
319 try:
318 try:
320 del self._handlers[name]
319 del self._handlers[name]
321 except KeyError:
320 except KeyError:
322 pass
321 pass
323 for esc_str in esc_strings:
322 for esc_str in esc_strings:
324 h = self._esc_handlers.get(esc_str)
323 h = self._esc_handlers.get(esc_str)
325 if h is handler:
324 if h is handler:
326 del self._esc_handlers[esc_str]
325 del self._esc_handlers[esc_str]
327
326
328 def get_handler_by_name(self, name):
327 def get_handler_by_name(self, name):
329 """Get a handler by its name."""
328 """Get a handler by its name."""
330 return self._handlers.get(name)
329 return self._handlers.get(name)
331
330
332 def get_handler_by_esc(self, esc_str):
331 def get_handler_by_esc(self, esc_str):
333 """Get a handler by its escape string."""
332 """Get a handler by its escape string."""
334 return self._esc_handlers.get(esc_str)
333 return self._esc_handlers.get(esc_str)
335
334
336 #-------------------------------------------------------------------------
335 #-------------------------------------------------------------------------
337 # Main prefiltering API
336 # Main prefiltering API
338 #-------------------------------------------------------------------------
337 #-------------------------------------------------------------------------
339
338
340 def prefilter_line_info(self, line_info):
339 def prefilter_line_info(self, line_info):
341 """Prefilter a line that has been converted to a LineInfo object.
340 """Prefilter a line that has been converted to a LineInfo object.
342
341
343 This implements the checker/handler part of the prefilter pipe.
342 This implements the checker/handler part of the prefilter pipe.
344 """
343 """
345 # print "prefilter_line_info: ", line_info
344 # print "prefilter_line_info: ", line_info
346 handler = self.find_handler(line_info)
345 handler = self.find_handler(line_info)
347 return handler.handle(line_info)
346 return handler.handle(line_info)
348
347
349 def find_handler(self, line_info):
348 def find_handler(self, line_info):
350 """Find a handler for the line_info by trying checkers."""
349 """Find a handler for the line_info by trying checkers."""
351 for checker in self.checkers:
350 for checker in self.checkers:
352 if checker.enabled:
351 if checker.enabled:
353 handler = checker.check(line_info)
352 handler = checker.check(line_info)
354 if handler:
353 if handler:
355 return handler
354 return handler
356 return self.get_handler_by_name('normal')
355 return self.get_handler_by_name('normal')
357
356
358 def transform_line(self, line, continue_prompt):
357 def transform_line(self, line, continue_prompt):
359 """Calls the enabled transformers in order of increasing priority."""
358 """Calls the enabled transformers in order of increasing priority."""
360 for transformer in self.transformers:
359 for transformer in self.transformers:
361 if transformer.enabled:
360 if transformer.enabled:
362 line = transformer.transform(line, continue_prompt)
361 line = transformer.transform(line, continue_prompt)
363 return line
362 return line
364
363
365 def prefilter_line(self, line, continue_prompt=False):
364 def prefilter_line(self, line, continue_prompt=False):
366 """Prefilter a single input line as text.
365 """Prefilter a single input line as text.
367
366
368 This method prefilters a single line of text by calling the
367 This method prefilters a single line of text by calling the
369 transformers and then the checkers/handlers.
368 transformers and then the checkers/handlers.
370 """
369 """
371
370
372 # print "prefilter_line: ", line, continue_prompt
371 # print "prefilter_line: ", line, continue_prompt
373 # All handlers *must* return a value, even if it's blank ('').
372 # All handlers *must* return a value, even if it's blank ('').
374
373
375 # Lines are NOT logged here. Handlers should process the line as
374 # Lines are NOT logged here. Handlers should process the line as
376 # needed, update the cache AND log it (so that the input cache array
375 # needed, update the cache AND log it (so that the input cache array
377 # stays synced).
376 # stays synced).
378
377
379 # save the line away in case we crash, so the post-mortem handler can
378 # save the line away in case we crash, so the post-mortem handler can
380 # record it
379 # record it
381 self.shell._last_input_line = line
380 self.shell._last_input_line = line
382
381
383 if not line:
382 if not line:
384 # Return immediately on purely empty lines, so that if the user
383 # Return immediately on purely empty lines, so that if the user
385 # previously typed some whitespace that started a continuation
384 # previously typed some whitespace that started a continuation
386 # prompt, he can break out of that loop with just an empty line.
385 # prompt, he can break out of that loop with just an empty line.
387 # This is how the default python prompt works.
386 # This is how the default python prompt works.
388
387
389 # Only return if the accumulated input buffer was just whitespace!
388 # Only return if the accumulated input buffer was just whitespace!
390 if ''.join(self.shell.buffer).isspace():
389 if ''.join(self.shell.buffer).isspace():
391 self.shell.buffer[:] = []
390 self.shell.buffer[:] = []
392 return ''
391 return ''
393
392
394 # At this point, we invoke our transformers.
393 # At this point, we invoke our transformers.
395 if not continue_prompt or (continue_prompt and self.multi_line_specials):
394 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 line = self.transform_line(line, continue_prompt)
395 line = self.transform_line(line, continue_prompt)
397
396
398 # Now we compute line_info for the checkers and handlers
397 # Now we compute line_info for the checkers and handlers
399 line_info = LineInfo(line, continue_prompt)
398 line_info = LineInfo(line, continue_prompt)
400
399
401 # the input history needs to track even empty lines
400 # the input history needs to track even empty lines
402 stripped = line.strip()
401 stripped = line.strip()
403
402
404 normal_handler = self.get_handler_by_name('normal')
403 normal_handler = self.get_handler_by_name('normal')
405 if not stripped:
404 if not stripped:
406 if not continue_prompt:
405 if not continue_prompt:
407 self.shell.outputcache.prompt_count -= 1
406 self.shell.outputcache.prompt_count -= 1
408
407
409 return normal_handler.handle(line_info)
408 return normal_handler.handle(line_info)
410
409
411 # special handlers are only allowed for single line statements
410 # special handlers are only allowed for single line statements
412 if continue_prompt and not self.multi_line_specials:
411 if continue_prompt and not self.multi_line_specials:
413 return normal_handler.handle(line_info)
412 return normal_handler.handle(line_info)
414
413
415 prefiltered = self.prefilter_line_info(line_info)
414 prefiltered = self.prefilter_line_info(line_info)
416 # print "prefiltered line: %r" % prefiltered
415 # print "prefiltered line: %r" % prefiltered
417 return prefiltered
416 return prefiltered
418
417
419 def prefilter_lines(self, lines, continue_prompt=False):
418 def prefilter_lines(self, lines, continue_prompt=False):
420 """Prefilter multiple input lines of text.
419 """Prefilter multiple input lines of text.
421
420
422 This is the main entry point for prefiltering multiple lines of
421 This is the main entry point for prefiltering multiple lines of
423 input. This simply calls :meth:`prefilter_line` for each line of
422 input. This simply calls :meth:`prefilter_line` for each line of
424 input.
423 input.
425
424
426 This covers cases where there are multiple lines in the user entry,
425 This covers cases where there are multiple lines in the user entry,
427 which is the case when the user goes back to a multiline history
426 which is the case when the user goes back to a multiline history
428 entry and presses enter.
427 entry and presses enter.
429 """
428 """
430 llines = lines.rstrip('\n').split('\n')
429 llines = lines.rstrip('\n').split('\n')
431 # We can get multiple lines in one shot, where multiline input 'blends'
430 # We can get multiple lines in one shot, where multiline input 'blends'
432 # into one line, in cases like recalling from the readline history
431 # into one line, in cases like recalling from the readline history
433 # buffer. We need to make sure that in such cases, we correctly
432 # buffer. We need to make sure that in such cases, we correctly
434 # communicate downstream which line is first and which are continuation
433 # communicate downstream which line is first and which are continuation
435 # ones.
434 # ones.
436 if len(llines) > 1:
435 if len(llines) > 1:
437 out = '\n'.join([self.prefilter_line(line, lnum>0)
436 out = '\n'.join([self.prefilter_line(line, lnum>0)
438 for lnum, line in enumerate(llines) ])
437 for lnum, line in enumerate(llines) ])
439 else:
438 else:
440 out = self.prefilter_line(llines[0], continue_prompt)
439 out = self.prefilter_line(llines[0], continue_prompt)
441
440
442 return out
441 return out
443
442
444 #-----------------------------------------------------------------------------
443 #-----------------------------------------------------------------------------
445 # Prefilter transformers
444 # Prefilter transformers
446 #-----------------------------------------------------------------------------
445 #-----------------------------------------------------------------------------
447
446
448
447
449 class PrefilterTransformer(Component):
448 class PrefilterTransformer(Component):
450 """Transform a line of user input."""
449 """Transform a line of user input."""
451
450
452 priority = Int(100, config=True)
451 priority = Int(100, config=True)
453 shell = Any
452 shell = Any
454 prefilter_manager = Any
453 prefilter_manager = Any
455 enabled = Bool(True, config=True)
454 enabled = Bool(True, config=True)
456
455
457 def __init__(self, parent, config=None):
456 def __init__(self, parent, config=None):
458 super(PrefilterTransformer, self).__init__(parent, config=config)
457 super(PrefilterTransformer, self).__init__(parent, config=config)
459 self.prefilter_manager.register_transformer(self)
458 self.prefilter_manager.register_transformer(self)
460
459
461 @auto_attr
460 @auto_attr
462 def shell(self):
461 def shell(self):
463 return Component.get_instances(
462 return Component.get_instances(
464 root=self.root,
463 root=self.root,
465 klass='IPython.core.iplib.InteractiveShell')[0]
464 klass='IPython.core.iplib.InteractiveShell')[0]
466
465
467 @auto_attr
466 @auto_attr
468 def prefilter_manager(self):
467 def prefilter_manager(self):
469 return PrefilterManager.get_instances(root=self.root)[0]
468 return PrefilterManager.get_instances(root=self.root)[0]
470
469
471 def transform(self, line, continue_prompt):
470 def transform(self, line, continue_prompt):
472 """Transform a line, returning the new one."""
471 """Transform a line, returning the new one."""
473 return None
472 return None
474
473
475 def __repr__(self):
474 def __repr__(self):
476 return "<%s(priority=%r, enabled=%r)>" % (
475 return "<%s(priority=%r, enabled=%r)>" % (
477 self.__class__.__name__, self.priority, self.enabled)
476 self.__class__.__name__, self.priority, self.enabled)
478
477
479
478
480 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
479 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
481 r'\s*=\s*!(?P<cmd>.*)')
480 r'\s*=\s*!(?P<cmd>.*)')
482
481
483
482
484 class AssignSystemTransformer(PrefilterTransformer):
483 class AssignSystemTransformer(PrefilterTransformer):
485 """Handle the `files = !ls` syntax."""
484 """Handle the `files = !ls` syntax."""
486
485
487 priority = Int(100, config=True)
486 priority = Int(100, config=True)
488
487
489 def transform(self, line, continue_prompt):
488 def transform(self, line, continue_prompt):
490 m = _assign_system_re.match(line)
489 m = _assign_system_re.match(line)
491 if m is not None:
490 if m is not None:
492 cmd = m.group('cmd')
491 cmd = m.group('cmd')
493 lhs = m.group('lhs')
492 lhs = m.group('lhs')
494 expr = make_quoted_expr("sc -l =%s" % cmd)
493 expr = make_quoted_expr("sc -l =%s" % cmd)
495 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
494 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
496 return new_line
495 return new_line
497 return line
496 return line
498
497
499
498
500 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
499 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
501 r'\s*=\s*%(?P<cmd>.*)')
500 r'\s*=\s*%(?P<cmd>.*)')
502
501
503 class AssignMagicTransformer(PrefilterTransformer):
502 class AssignMagicTransformer(PrefilterTransformer):
504 """Handle the `a = %who` syntax."""
503 """Handle the `a = %who` syntax."""
505
504
506 priority = Int(200, config=True)
505 priority = Int(200, config=True)
507
506
508 def transform(self, line, continue_prompt):
507 def transform(self, line, continue_prompt):
509 m = _assign_magic_re.match(line)
508 m = _assign_magic_re.match(line)
510 if m is not None:
509 if m is not None:
511 cmd = m.group('cmd')
510 cmd = m.group('cmd')
512 lhs = m.group('lhs')
511 lhs = m.group('lhs')
513 expr = make_quoted_expr(cmd)
512 expr = make_quoted_expr(cmd)
514 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
513 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
515 return new_line
514 return new_line
516 return line
515 return line
517
516
518
517
519 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
518 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
520
519
521 class PyPromptTransformer(PrefilterTransformer):
520 class PyPromptTransformer(PrefilterTransformer):
522 """Handle inputs that start with '>>> ' syntax."""
521 """Handle inputs that start with '>>> ' syntax."""
523
522
524 priority = Int(50, config=True)
523 priority = Int(50, config=True)
525
524
526 def transform(self, line, continue_prompt):
525 def transform(self, line, continue_prompt):
527
526
528 if not line or line.isspace() or line.strip() == '...':
527 if not line or line.isspace() or line.strip() == '...':
529 # This allows us to recognize multiple input prompts separated by
528 # This allows us to recognize multiple input prompts separated by
530 # blank lines and pasted in a single chunk, very common when
529 # blank lines and pasted in a single chunk, very common when
531 # pasting doctests or long tutorial passages.
530 # pasting doctests or long tutorial passages.
532 return ''
531 return ''
533 m = _classic_prompt_re.match(line)
532 m = _classic_prompt_re.match(line)
534 if m:
533 if m:
535 return line[len(m.group(0)):]
534 return line[len(m.group(0)):]
536 else:
535 else:
537 return line
536 return line
538
537
539
538
540 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
539 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
541
540
542 class IPyPromptTransformer(PrefilterTransformer):
541 class IPyPromptTransformer(PrefilterTransformer):
543 """Handle inputs that start classic IPython prompt syntax."""
542 """Handle inputs that start classic IPython prompt syntax."""
544
543
545 priority = Int(50, config=True)
544 priority = Int(50, config=True)
546
545
547 def transform(self, line, continue_prompt):
546 def transform(self, line, continue_prompt):
548
547
549 if not line or line.isspace() or line.strip() == '...':
548 if not line or line.isspace() or line.strip() == '...':
550 # This allows us to recognize multiple input prompts separated by
549 # This allows us to recognize multiple input prompts separated by
551 # blank lines and pasted in a single chunk, very common when
550 # blank lines and pasted in a single chunk, very common when
552 # pasting doctests or long tutorial passages.
551 # pasting doctests or long tutorial passages.
553 return ''
552 return ''
554 m = _ipy_prompt_re.match(line)
553 m = _ipy_prompt_re.match(line)
555 if m:
554 if m:
556 return line[len(m.group(0)):]
555 return line[len(m.group(0)):]
557 else:
556 else:
558 return line
557 return line
559
558
560 #-----------------------------------------------------------------------------
559 #-----------------------------------------------------------------------------
561 # Prefilter checkers
560 # Prefilter checkers
562 #-----------------------------------------------------------------------------
561 #-----------------------------------------------------------------------------
563
562
564
563
565 class PrefilterChecker(Component):
564 class PrefilterChecker(Component):
566 """Inspect an input line and return a handler for that line."""
565 """Inspect an input line and return a handler for that line."""
567
566
568 priority = Int(100, config=True)
567 priority = Int(100, config=True)
569 shell = Any
568 shell = Any
570 prefilter_manager = Any
569 prefilter_manager = Any
571 enabled = Bool(True, config=True)
570 enabled = Bool(True, config=True)
572
571
573 def __init__(self, parent, config=None):
572 def __init__(self, parent, config=None):
574 super(PrefilterChecker, self).__init__(parent, config=config)
573 super(PrefilterChecker, self).__init__(parent, config=config)
575 self.prefilter_manager.register_checker(self)
574 self.prefilter_manager.register_checker(self)
576
575
577 @auto_attr
576 @auto_attr
578 def shell(self):
577 def shell(self):
579 return Component.get_instances(
578 return Component.get_instances(
580 root=self.root,
579 root=self.root,
581 klass='IPython.core.iplib.InteractiveShell')[0]
580 klass='IPython.core.iplib.InteractiveShell')[0]
582
581
583 @auto_attr
582 @auto_attr
584 def prefilter_manager(self):
583 def prefilter_manager(self):
585 return PrefilterManager.get_instances(root=self.root)[0]
584 return PrefilterManager.get_instances(root=self.root)[0]
586
585
587 def check(self, line_info):
586 def check(self, line_info):
588 """Inspect line_info and return a handler instance or None."""
587 """Inspect line_info and return a handler instance or None."""
589 return None
588 return None
590
589
591 def __repr__(self):
590 def __repr__(self):
592 return "<%s(priority=%r, enabled=%r)>" % (
591 return "<%s(priority=%r, enabled=%r)>" % (
593 self.__class__.__name__, self.priority, self.enabled)
592 self.__class__.__name__, self.priority, self.enabled)
594
593
595
594
596 class EmacsChecker(PrefilterChecker):
595 class EmacsChecker(PrefilterChecker):
597
596
598 priority = Int(100, config=True)
597 priority = Int(100, config=True)
599 enabled = Bool(False, config=True)
598 enabled = Bool(False, config=True)
600
599
601 def check(self, line_info):
600 def check(self, line_info):
602 "Emacs ipython-mode tags certain input lines."
601 "Emacs ipython-mode tags certain input lines."
603 if line_info.line.endswith('# PYTHON-MODE'):
602 if line_info.line.endswith('# PYTHON-MODE'):
604 return self.prefilter_manager.get_handler_by_name('emacs')
603 return self.prefilter_manager.get_handler_by_name('emacs')
605 else:
604 else:
606 return None
605 return None
607
606
608
607
609 class ShellEscapeChecker(PrefilterChecker):
608 class ShellEscapeChecker(PrefilterChecker):
610
609
611 priority = Int(200, config=True)
610 priority = Int(200, config=True)
612
611
613 def check(self, line_info):
612 def check(self, line_info):
614 if line_info.line.lstrip().startswith(ESC_SHELL):
613 if line_info.line.lstrip().startswith(ESC_SHELL):
615 return self.prefilter_manager.get_handler_by_name('shell')
614 return self.prefilter_manager.get_handler_by_name('shell')
616
615
617
616
618 class IPyAutocallChecker(PrefilterChecker):
617 class IPyAutocallChecker(PrefilterChecker):
619
618
620 priority = Int(300, config=True)
619 priority = Int(300, config=True)
621
620
622 def check(self, line_info):
621 def check(self, line_info):
623 "Instances of IPyAutocall in user_ns get autocalled immediately"
622 "Instances of IPyAutocall in user_ns get autocalled immediately"
624 obj = self.shell.user_ns.get(line_info.ifun, None)
623 obj = self.shell.user_ns.get(line_info.ifun, None)
625 if isinstance(obj, IPyAutocall):
624 if isinstance(obj, IPyAutocall):
626 obj.set_ip(self.shell)
625 obj.set_ip(self.shell)
627 return self.prefilter_manager.get_handler_by_name('auto')
626 return self.prefilter_manager.get_handler_by_name('auto')
628 else:
627 else:
629 return None
628 return None
630
629
631
630
632 class MultiLineMagicChecker(PrefilterChecker):
631 class MultiLineMagicChecker(PrefilterChecker):
633
632
634 priority = Int(400, config=True)
633 priority = Int(400, config=True)
635
634
636 def check(self, line_info):
635 def check(self, line_info):
637 "Allow ! and !! in multi-line statements if multi_line_specials is on"
636 "Allow ! and !! in multi-line statements if multi_line_specials is on"
638 # Note that this one of the only places we check the first character of
637 # Note that this one of the only places we check the first character of
639 # ifun and *not* the pre_char. Also note that the below test matches
638 # ifun and *not* the pre_char. Also note that the below test matches
640 # both ! and !!.
639 # both ! and !!.
641 if line_info.continue_prompt \
640 if line_info.continue_prompt \
642 and self.prefilter_manager.multi_line_specials:
641 and self.prefilter_manager.multi_line_specials:
643 if line_info.ifun.startswith(ESC_MAGIC):
642 if line_info.ifun.startswith(ESC_MAGIC):
644 return self.prefilter_manager.get_handler_by_name('magic')
643 return self.prefilter_manager.get_handler_by_name('magic')
645 else:
644 else:
646 return None
645 return None
647
646
648
647
649 class EscCharsChecker(PrefilterChecker):
648 class EscCharsChecker(PrefilterChecker):
650
649
651 priority = Int(500, config=True)
650 priority = Int(500, config=True)
652
651
653 def check(self, line_info):
652 def check(self, line_info):
654 """Check for escape character and return either a handler to handle it,
653 """Check for escape character and return either a handler to handle it,
655 or None if there is no escape char."""
654 or None if there is no escape char."""
656 if line_info.line[-1] == ESC_HELP \
655 if line_info.line[-1] == ESC_HELP \
657 and line_info.pre_char != ESC_SHELL \
656 and line_info.pre_char != ESC_SHELL \
658 and line_info.pre_char != ESC_SH_CAP:
657 and line_info.pre_char != ESC_SH_CAP:
659 # the ? can be at the end, but *not* for either kind of shell escape,
658 # the ? can be at the end, but *not* for either kind of shell escape,
660 # because a ? can be a vaild final char in a shell cmd
659 # because a ? can be a vaild final char in a shell cmd
661 return self.prefilter_manager.get_handler_by_name('help')
660 return self.prefilter_manager.get_handler_by_name('help')
662 else:
661 else:
663 # This returns None like it should if no handler exists
662 # This returns None like it should if no handler exists
664 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
663 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
665
664
666
665
667 class AssignmentChecker(PrefilterChecker):
666 class AssignmentChecker(PrefilterChecker):
668
667
669 priority = Int(600, config=True)
668 priority = Int(600, config=True)
670
669
671 def check(self, line_info):
670 def check(self, line_info):
672 """Check to see if user is assigning to a var for the first time, in
671 """Check to see if user is assigning to a var for the first time, in
673 which case we want to avoid any sort of automagic / autocall games.
672 which case we want to avoid any sort of automagic / autocall games.
674
673
675 This allows users to assign to either alias or magic names true python
674 This allows users to assign to either alias or magic names true python
676 variables (the magic/alias systems always take second seat to true
675 variables (the magic/alias systems always take second seat to true
677 python code). E.g. ls='hi', or ls,that=1,2"""
676 python code). E.g. ls='hi', or ls,that=1,2"""
678 if line_info.the_rest:
677 if line_info.the_rest:
679 if line_info.the_rest[0] in '=,':
678 if line_info.the_rest[0] in '=,':
680 return self.prefilter_manager.get_handler_by_name('normal')
679 return self.prefilter_manager.get_handler_by_name('normal')
681 else:
680 else:
682 return None
681 return None
683
682
684
683
685 class AutoMagicChecker(PrefilterChecker):
684 class AutoMagicChecker(PrefilterChecker):
686
685
687 priority = Int(700, config=True)
686 priority = Int(700, config=True)
688
687
689 def check(self, line_info):
688 def check(self, line_info):
690 """If the ifun is magic, and automagic is on, run it. Note: normal,
689 """If the ifun is magic, and automagic is on, run it. Note: normal,
691 non-auto magic would already have been triggered via '%' in
690 non-auto magic would already have been triggered via '%' in
692 check_esc_chars. This just checks for automagic. Also, before
691 check_esc_chars. This just checks for automagic. Also, before
693 triggering the magic handler, make sure that there is nothing in the
692 triggering the magic handler, make sure that there is nothing in the
694 user namespace which could shadow it."""
693 user namespace which could shadow it."""
695 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
694 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
696 return None
695 return None
697
696
698 # We have a likely magic method. Make sure we should actually call it.
697 # We have a likely magic method. Make sure we should actually call it.
699 if line_info.continue_prompt and not self.shell.multi_line_specials:
698 if line_info.continue_prompt and not self.shell.multi_line_specials:
700 return None
699 return None
701
700
702 head = line_info.ifun.split('.',1)[0]
701 head = line_info.ifun.split('.',1)[0]
703 if is_shadowed(head, self.shell):
702 if is_shadowed(head, self.shell):
704 return None
703 return None
705
704
706 return self.prefilter_manager.get_handler_by_name('magic')
705 return self.prefilter_manager.get_handler_by_name('magic')
707
706
708
707
709 class AliasChecker(PrefilterChecker):
708 class AliasChecker(PrefilterChecker):
710
709
711 priority = Int(800, config=True)
710 priority = Int(800, config=True)
712
711
713 @auto_attr
712 @auto_attr
714 def alias_manager(self):
713 def alias_manager(self):
715 return AliasManager.get_instances(root=self.root)[0]
714 return AliasManager.get_instances(root=self.root)[0]
716
715
717 def check(self, line_info):
716 def check(self, line_info):
718 "Check if the initital identifier on the line is an alias."
717 "Check if the initital identifier on the line is an alias."
719 # Note: aliases can not contain '.'
718 # Note: aliases can not contain '.'
720 head = line_info.ifun.split('.',1)[0]
719 head = line_info.ifun.split('.',1)[0]
721 if line_info.ifun not in self.alias_manager \
720 if line_info.ifun not in self.alias_manager \
722 or head not in self.alias_manager \
721 or head not in self.alias_manager \
723 or is_shadowed(head, self.shell):
722 or is_shadowed(head, self.shell):
724 return None
723 return None
725
724
726 return self.prefilter_manager.get_handler_by_name('alias')
725 return self.prefilter_manager.get_handler_by_name('alias')
727
726
728
727
729 class PythonOpsChecker(PrefilterChecker):
728 class PythonOpsChecker(PrefilterChecker):
730
729
731 priority = Int(900, config=True)
730 priority = Int(900, config=True)
732
731
733 def check(self, line_info):
732 def check(self, line_info):
734 """If the 'rest' of the line begins with a function call or pretty much
733 """If the 'rest' of the line begins with a function call or pretty much
735 any python operator, we should simply execute the line (regardless of
734 any python operator, we should simply execute the line (regardless of
736 whether or not there's a possible autocall expansion). This avoids
735 whether or not there's a possible autocall expansion). This avoids
737 spurious (and very confusing) geattr() accesses."""
736 spurious (and very confusing) geattr() accesses."""
738 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
737 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
739 return self.prefilter_manager.get_handler_by_name('normal')
738 return self.prefilter_manager.get_handler_by_name('normal')
740 else:
739 else:
741 return None
740 return None
742
741
743
742
744 class AutocallChecker(PrefilterChecker):
743 class AutocallChecker(PrefilterChecker):
745
744
746 priority = Int(1000, config=True)
745 priority = Int(1000, config=True)
747
746
748 def check(self, line_info):
747 def check(self, line_info):
749 "Check if the initial word/function is callable and autocall is on."
748 "Check if the initial word/function is callable and autocall is on."
750 if not self.shell.autocall:
749 if not self.shell.autocall:
751 return None
750 return None
752
751
753 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
752 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
754 if not oinfo['found']:
753 if not oinfo['found']:
755 return None
754 return None
756
755
757 if callable(oinfo['obj']) \
756 if callable(oinfo['obj']) \
758 and (not re_exclude_auto.match(line_info.the_rest)) \
757 and (not re_exclude_auto.match(line_info.the_rest)) \
759 and re_fun_name.match(line_info.ifun):
758 and re_fun_name.match(line_info.ifun):
760 return self.prefilter_manager.get_handler_by_name('auto')
759 return self.prefilter_manager.get_handler_by_name('auto')
761 else:
760 else:
762 return None
761 return None
763
762
764
763
765 #-----------------------------------------------------------------------------
764 #-----------------------------------------------------------------------------
766 # Prefilter handlers
765 # Prefilter handlers
767 #-----------------------------------------------------------------------------
766 #-----------------------------------------------------------------------------
768
767
769
768
770 class PrefilterHandler(Component):
769 class PrefilterHandler(Component):
771
770
772 handler_name = Str('normal')
771 handler_name = Str('normal')
773 esc_strings = List([])
772 esc_strings = List([])
774 shell = Any
773 shell = Any
775 prefilter_manager = Any
774 prefilter_manager = Any
776
775
777 def __init__(self, parent, config=None):
776 def __init__(self, parent, config=None):
778 super(PrefilterHandler, self).__init__(parent, config=config)
777 super(PrefilterHandler, self).__init__(parent, config=config)
779 self.prefilter_manager.register_handler(
778 self.prefilter_manager.register_handler(
780 self.handler_name,
779 self.handler_name,
781 self,
780 self,
782 self.esc_strings
781 self.esc_strings
783 )
782 )
784
783
785 @auto_attr
784 @auto_attr
786 def shell(self):
785 def shell(self):
787 return Component.get_instances(
786 return Component.get_instances(
788 root=self.root,
787 root=self.root,
789 klass='IPython.core.iplib.InteractiveShell')[0]
788 klass='IPython.core.iplib.InteractiveShell')[0]
790
789
791 @auto_attr
790 @auto_attr
792 def prefilter_manager(self):
791 def prefilter_manager(self):
793 return PrefilterManager.get_instances(root=self.root)[0]
792 return PrefilterManager.get_instances(root=self.root)[0]
794
793
795 def handle(self, line_info):
794 def handle(self, line_info):
796 # print "normal: ", line_info
795 # print "normal: ", line_info
797 """Handle normal input lines. Use as a template for handlers."""
796 """Handle normal input lines. Use as a template for handlers."""
798
797
799 # With autoindent on, we need some way to exit the input loop, and I
798 # With autoindent on, we need some way to exit the input loop, and I
800 # don't want to force the user to have to backspace all the way to
799 # don't want to force the user to have to backspace all the way to
801 # clear the line. The rule will be in this case, that either two
800 # clear the line. The rule will be in this case, that either two
802 # lines of pure whitespace in a row, or a line of pure whitespace but
801 # lines of pure whitespace in a row, or a line of pure whitespace but
803 # of a size different to the indent level, will exit the input loop.
802 # of a size different to the indent level, will exit the input loop.
804 line = line_info.line
803 line = line_info.line
805 continue_prompt = line_info.continue_prompt
804 continue_prompt = line_info.continue_prompt
806
805
807 if (continue_prompt and
806 if (continue_prompt and
808 self.shell.autoindent and
807 self.shell.autoindent and
809 line.isspace() and
808 line.isspace() and
810
809
811 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
810 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
812 or
811 or
813 not self.shell.buffer
812 not self.shell.buffer
814 or
813 or
815 (self.shell.buffer[-1]).isspace()
814 (self.shell.buffer[-1]).isspace()
816 )
815 )
817 ):
816 ):
818 line = ''
817 line = ''
819
818
820 self.shell.log(line, line, continue_prompt)
819 self.shell.log(line, line, continue_prompt)
821 return line
820 return line
822
821
823 def __str__(self):
822 def __str__(self):
824 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
823 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
825
824
826
825
827 class AliasHandler(PrefilterHandler):
826 class AliasHandler(PrefilterHandler):
828
827
829 handler_name = Str('alias')
828 handler_name = Str('alias')
830
829
831 @auto_attr
830 @auto_attr
832 def alias_manager(self):
831 def alias_manager(self):
833 return AliasManager.get_instances(root=self.root)[0]
832 return AliasManager.get_instances(root=self.root)[0]
834
833
835 def handle(self, line_info):
834 def handle(self, line_info):
836 """Handle alias input lines. """
835 """Handle alias input lines. """
837 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
836 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
838 # pre is needed, because it carries the leading whitespace. Otherwise
837 # pre is needed, because it carries the leading whitespace. Otherwise
839 # aliases won't work in indented sections.
838 # aliases won't work in indented sections.
840 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
839 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
841 make_quoted_expr(transformed))
840 make_quoted_expr(transformed))
842
841
843 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
842 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
844 return line_out
843 return line_out
845
844
846
845
847 class ShellEscapeHandler(PrefilterHandler):
846 class ShellEscapeHandler(PrefilterHandler):
848
847
849 handler_name = Str('shell')
848 handler_name = Str('shell')
850 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
849 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
851
850
852 def handle(self, line_info):
851 def handle(self, line_info):
853 """Execute the line in a shell, empty return value"""
852 """Execute the line in a shell, empty return value"""
854 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
853 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
855
854
856 line = line_info.line
855 line = line_info.line
857 if line.lstrip().startswith(ESC_SH_CAP):
856 if line.lstrip().startswith(ESC_SH_CAP):
858 # rewrite LineInfo's line, ifun and the_rest to properly hold the
857 # rewrite LineInfo's line, ifun and the_rest to properly hold the
859 # call to %sx and the actual command to be executed, so
858 # call to %sx and the actual command to be executed, so
860 # handle_magic can work correctly. Note that this works even if
859 # handle_magic can work correctly. Note that this works even if
861 # the line is indented, so it handles multi_line_specials
860 # the line is indented, so it handles multi_line_specials
862 # properly.
861 # properly.
863 new_rest = line.lstrip()[2:]
862 new_rest = line.lstrip()[2:]
864 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
863 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
865 line_info.ifun = 'sx'
864 line_info.ifun = 'sx'
866 line_info.the_rest = new_rest
865 line_info.the_rest = new_rest
867 return magic_handler.handle(line_info)
866 return magic_handler.handle(line_info)
868 else:
867 else:
869 cmd = line.lstrip().lstrip(ESC_SHELL)
868 cmd = line.lstrip().lstrip(ESC_SHELL)
870 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
869 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
871 make_quoted_expr(cmd))
870 make_quoted_expr(cmd))
872 # update cache/log and return
871 # update cache/log and return
873 self.shell.log(line, line_out, line_info.continue_prompt)
872 self.shell.log(line, line_out, line_info.continue_prompt)
874 return line_out
873 return line_out
875
874
876
875
877 class MagicHandler(PrefilterHandler):
876 class MagicHandler(PrefilterHandler):
878
877
879 handler_name = Str('magic')
878 handler_name = Str('magic')
880 esc_strings = List([ESC_MAGIC])
879 esc_strings = List([ESC_MAGIC])
881
880
882 def handle(self, line_info):
881 def handle(self, line_info):
883 """Execute magic functions."""
882 """Execute magic functions."""
884 ifun = line_info.ifun
883 ifun = line_info.ifun
885 the_rest = line_info.the_rest
884 the_rest = line_info.the_rest
886 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
885 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
887 make_quoted_expr(ifun + " " + the_rest))
886 make_quoted_expr(ifun + " " + the_rest))
888 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
887 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
889 return cmd
888 return cmd
890
889
891
890
892 class AutoHandler(PrefilterHandler):
891 class AutoHandler(PrefilterHandler):
893
892
894 handler_name = Str('auto')
893 handler_name = Str('auto')
895 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
894 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
896
895
897 def handle(self, line_info):
896 def handle(self, line_info):
898 """Hande lines which can be auto-executed, quoting if requested."""
897 """Hande lines which can be auto-executed, quoting if requested."""
899 line = line_info.line
898 line = line_info.line
900 ifun = line_info.ifun
899 ifun = line_info.ifun
901 the_rest = line_info.the_rest
900 the_rest = line_info.the_rest
902 pre = line_info.pre
901 pre = line_info.pre
903 continue_prompt = line_info.continue_prompt
902 continue_prompt = line_info.continue_prompt
904 obj = line_info.ofind(self)['obj']
903 obj = line_info.ofind(self)['obj']
905 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
904 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
906
905
907 # This should only be active for single-line input!
906 # This should only be active for single-line input!
908 if continue_prompt:
907 if continue_prompt:
909 self.shell.log(line,line,continue_prompt)
908 self.shell.log(line,line,continue_prompt)
910 return line
909 return line
911
910
912 force_auto = isinstance(obj, IPyAutocall)
911 force_auto = isinstance(obj, IPyAutocall)
913 auto_rewrite = True
912 auto_rewrite = True
914
913
915 if pre == ESC_QUOTE:
914 if pre == ESC_QUOTE:
916 # Auto-quote splitting on whitespace
915 # Auto-quote splitting on whitespace
917 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
916 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
918 elif pre == ESC_QUOTE2:
917 elif pre == ESC_QUOTE2:
919 # Auto-quote whole string
918 # Auto-quote whole string
920 newcmd = '%s("%s")' % (ifun,the_rest)
919 newcmd = '%s("%s")' % (ifun,the_rest)
921 elif pre == ESC_PAREN:
920 elif pre == ESC_PAREN:
922 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
921 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
923 else:
922 else:
924 # Auto-paren.
923 # Auto-paren.
925 # We only apply it to argument-less calls if the autocall
924 # We only apply it to argument-less calls if the autocall
926 # parameter is set to 2. We only need to check that autocall is <
925 # parameter is set to 2. We only need to check that autocall is <
927 # 2, since this function isn't called unless it's at least 1.
926 # 2, since this function isn't called unless it's at least 1.
928 if not the_rest and (self.shell.autocall < 2) and not force_auto:
927 if not the_rest and (self.shell.autocall < 2) and not force_auto:
929 newcmd = '%s %s' % (ifun,the_rest)
928 newcmd = '%s %s' % (ifun,the_rest)
930 auto_rewrite = False
929 auto_rewrite = False
931 else:
930 else:
932 if not force_auto and the_rest.startswith('['):
931 if not force_auto and the_rest.startswith('['):
933 if hasattr(obj,'__getitem__'):
932 if hasattr(obj,'__getitem__'):
934 # Don't autocall in this case: item access for an object
933 # Don't autocall in this case: item access for an object
935 # which is BOTH callable and implements __getitem__.
934 # which is BOTH callable and implements __getitem__.
936 newcmd = '%s %s' % (ifun,the_rest)
935 newcmd = '%s %s' % (ifun,the_rest)
937 auto_rewrite = False
936 auto_rewrite = False
938 else:
937 else:
939 # if the object doesn't support [] access, go ahead and
938 # if the object doesn't support [] access, go ahead and
940 # autocall
939 # autocall
941 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
940 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
942 elif the_rest.endswith(';'):
941 elif the_rest.endswith(';'):
943 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
942 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
944 else:
943 else:
945 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
944 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
946
945
947 if auto_rewrite:
946 if auto_rewrite:
948 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
947 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
949
948
950 try:
949 try:
951 # plain ascii works better w/ pyreadline, on some machines, so
950 # plain ascii works better w/ pyreadline, on some machines, so
952 # we use it and only print uncolored rewrite if we have unicode
951 # we use it and only print uncolored rewrite if we have unicode
953 rw = str(rw)
952 rw = str(rw)
954 print >>Term.cout, rw
953 print >>Term.cout, rw
955 except UnicodeEncodeError:
954 except UnicodeEncodeError:
956 print "-------------->" + newcmd
955 print "-------------->" + newcmd
957
956
958 # log what is now valid Python, not the actual user input (without the
957 # log what is now valid Python, not the actual user input (without the
959 # final newline)
958 # final newline)
960 self.shell.log(line,newcmd,continue_prompt)
959 self.shell.log(line,newcmd,continue_prompt)
961 return newcmd
960 return newcmd
962
961
963
962
964 class HelpHandler(PrefilterHandler):
963 class HelpHandler(PrefilterHandler):
965
964
966 handler_name = Str('help')
965 handler_name = Str('help')
967 esc_strings = List([ESC_HELP])
966 esc_strings = List([ESC_HELP])
968
967
969 def handle(self, line_info):
968 def handle(self, line_info):
970 """Try to get some help for the object.
969 """Try to get some help for the object.
971
970
972 obj? or ?obj -> basic information.
971 obj? or ?obj -> basic information.
973 obj?? or ??obj -> more details.
972 obj?? or ??obj -> more details.
974 """
973 """
975 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
974 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
976 line = line_info.line
975 line = line_info.line
977 # We need to make sure that we don't process lines which would be
976 # We need to make sure that we don't process lines which would be
978 # otherwise valid python, such as "x=1 # what?"
977 # otherwise valid python, such as "x=1 # what?"
979 try:
978 try:
980 codeop.compile_command(line)
979 codeop.compile_command(line)
981 except SyntaxError:
980 except SyntaxError:
982 # We should only handle as help stuff which is NOT valid syntax
981 # We should only handle as help stuff which is NOT valid syntax
983 if line[0]==ESC_HELP:
982 if line[0]==ESC_HELP:
984 line = line[1:]
983 line = line[1:]
985 elif line[-1]==ESC_HELP:
984 elif line[-1]==ESC_HELP:
986 line = line[:-1]
985 line = line[:-1]
987 self.shell.log(line, '#?'+line, line_info.continue_prompt)
986 self.shell.log(line, '#?'+line, line_info.continue_prompt)
988 if line:
987 if line:
989 #print 'line:<%r>' % line # dbg
988 #print 'line:<%r>' % line # dbg
990 self.shell.magic_pinfo(line)
989 self.shell.magic_pinfo(line)
991 else:
990 else:
992 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
991 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
993 return '' # Empty string is needed here!
992 return '' # Empty string is needed here!
994 except:
993 except:
995 raise
994 raise
996 # Pass any other exceptions through to the normal handler
995 # Pass any other exceptions through to the normal handler
997 return normal_handler.handle(line_info)
996 return normal_handler.handle(line_info)
998 else:
997 else:
999 raise
998 raise
1000 # If the code compiles ok, we should handle it normally
999 # If the code compiles ok, we should handle it normally
1001 return normal_handler.handle(line_info)
1000 return normal_handler.handle(line_info)
1002
1001
1003
1002
1004 class EmacsHandler(PrefilterHandler):
1003 class EmacsHandler(PrefilterHandler):
1005
1004
1006 handler_name = Str('emacs')
1005 handler_name = Str('emacs')
1007 esc_strings = List([])
1006 esc_strings = List([])
1008
1007
1009 def handle(self, line_info):
1008 def handle(self, line_info):
1010 """Handle input lines marked by python-mode."""
1009 """Handle input lines marked by python-mode."""
1011
1010
1012 # Currently, nothing is done. Later more functionality can be added
1011 # Currently, nothing is done. Later more functionality can be added
1013 # here if needed.
1012 # here if needed.
1014
1013
1015 # The input cache shouldn't be updated
1014 # The input cache shouldn't be updated
1016 return line_info.line
1015 return line_info.line
1017
1016
1018
1017
1019 #-----------------------------------------------------------------------------
1018 #-----------------------------------------------------------------------------
1020 # Defaults
1019 # Defaults
1021 #-----------------------------------------------------------------------------
1020 #-----------------------------------------------------------------------------
1022
1021
1023
1022
1024 _default_transformers = [
1023 _default_transformers = [
1025 AssignSystemTransformer,
1024 AssignSystemTransformer,
1026 AssignMagicTransformer,
1025 AssignMagicTransformer,
1027 PyPromptTransformer,
1026 PyPromptTransformer,
1028 IPyPromptTransformer,
1027 IPyPromptTransformer,
1029 ]
1028 ]
1030
1029
1031 _default_checkers = [
1030 _default_checkers = [
1032 EmacsChecker,
1031 EmacsChecker,
1033 ShellEscapeChecker,
1032 ShellEscapeChecker,
1034 IPyAutocallChecker,
1033 IPyAutocallChecker,
1035 MultiLineMagicChecker,
1034 MultiLineMagicChecker,
1036 EscCharsChecker,
1035 EscCharsChecker,
1037 AssignmentChecker,
1036 AssignmentChecker,
1038 AutoMagicChecker,
1037 AutoMagicChecker,
1039 AliasChecker,
1038 AliasChecker,
1040 PythonOpsChecker,
1039 PythonOpsChecker,
1041 AutocallChecker
1040 AutocallChecker
1042 ]
1041 ]
1043
1042
1044 _default_handlers = [
1043 _default_handlers = [
1045 PrefilterHandler,
1044 PrefilterHandler,
1046 AliasHandler,
1045 AliasHandler,
1047 ShellEscapeHandler,
1046 ShellEscapeHandler,
1048 MagicHandler,
1047 MagicHandler,
1049 AutoHandler,
1048 AutoHandler,
1050 HelpHandler,
1049 HelpHandler,
1051 EmacsHandler
1050 EmacsHandler
1052 ]
1051 ]
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/core/pylabtools.py to IPython/lib/pylabtools.py
NO CONTENT: file renamed from IPython/core/pylabtools.py to IPython/lib/pylabtools.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: 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: 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
General Comments 0
You need to be logged in to leave comments. Login now