##// END OF EJS Templates
Merge pull request #1502 from minrk/pyflakes...
Fernando Perez -
r6447:d13bbaf3 merge
parent child Browse files
Show More
@@ -1,702 +1,702 b''
1 """A simple configuration system.
1 """A simple configuration system.
2
2
3 Authors
3 Authors
4 -------
4 -------
5 * Brian Granger
5 * Brian Granger
6 * Fernando Perez
6 * Fernando Perez
7 * Min RK
7 * Min RK
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2011 The IPython Development Team
11 # Copyright (C) 2008-2011 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__ as builtin_mod
21 import __builtin__ as builtin_mod
22 import os
22 import os
23 import re
23 import re
24 import sys
24 import sys
25
25
26 from IPython.external import argparse
26 from IPython.external import argparse
27 from IPython.utils.path import filefind, get_ipython_dir
27 from IPython.utils.path import filefind, get_ipython_dir
28 from IPython.utils import py3compat, text, warn
28 from IPython.utils import py3compat, text, warn
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Exceptions
31 # Exceptions
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33
33
34
34
35 class ConfigError(Exception):
35 class ConfigError(Exception):
36 pass
36 pass
37
37
38 class ConfigLoaderError(ConfigError):
38 class ConfigLoaderError(ConfigError):
39 pass
39 pass
40
40
41 class ConfigFileNotFound(ConfigError):
41 class ConfigFileNotFound(ConfigError):
42 pass
42 pass
43
43
44 class ArgumentError(ConfigLoaderError):
44 class ArgumentError(ConfigLoaderError):
45 pass
45 pass
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Argparse fix
48 # Argparse fix
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51 # Unfortunately argparse by default prints help messages to stderr instead of
51 # Unfortunately argparse by default prints help messages to stderr instead of
52 # stdout. This makes it annoying to capture long help screens at the command
52 # stdout. This makes it annoying to capture long help screens at the command
53 # line, since one must know how to pipe stderr, which many users don't know how
53 # line, since one must know how to pipe stderr, which many users don't know how
54 # to do. So we override the print_help method with one that defaults to
54 # to do. So we override the print_help method with one that defaults to
55 # stdout and use our class instead.
55 # stdout and use our class instead.
56
56
57 class ArgumentParser(argparse.ArgumentParser):
57 class ArgumentParser(argparse.ArgumentParser):
58 """Simple argparse subclass that prints help to stdout by default."""
58 """Simple argparse subclass that prints help to stdout by default."""
59
59
60 def print_help(self, file=None):
60 def print_help(self, file=None):
61 if file is None:
61 if file is None:
62 file = sys.stdout
62 file = sys.stdout
63 return super(ArgumentParser, self).print_help(file)
63 return super(ArgumentParser, self).print_help(file)
64
64
65 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
65 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
66
66
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68 # Config class for holding config information
68 # Config class for holding config information
69 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
70
70
71
71
72 class Config(dict):
72 class Config(dict):
73 """An attribute based dict that can do smart merges."""
73 """An attribute based dict that can do smart merges."""
74
74
75 def __init__(self, *args, **kwds):
75 def __init__(self, *args, **kwds):
76 dict.__init__(self, *args, **kwds)
76 dict.__init__(self, *args, **kwds)
77 # This sets self.__dict__ = self, but it has to be done this way
77 # This sets self.__dict__ = self, but it has to be done this way
78 # because we are also overriding __setattr__.
78 # because we are also overriding __setattr__.
79 dict.__setattr__(self, '__dict__', self)
79 dict.__setattr__(self, '__dict__', self)
80
80
81 def _merge(self, other):
81 def _merge(self, other):
82 to_update = {}
82 to_update = {}
83 for k, v in other.iteritems():
83 for k, v in other.iteritems():
84 if not self.has_key(k):
84 if not self.has_key(k):
85 to_update[k] = v
85 to_update[k] = v
86 else: # I have this key
86 else: # I have this key
87 if isinstance(v, Config):
87 if isinstance(v, Config):
88 # Recursively merge common sub Configs
88 # Recursively merge common sub Configs
89 self[k]._merge(v)
89 self[k]._merge(v)
90 else:
90 else:
91 # Plain updates for non-Configs
91 # Plain updates for non-Configs
92 to_update[k] = v
92 to_update[k] = v
93
93
94 self.update(to_update)
94 self.update(to_update)
95
95
96 def _is_section_key(self, key):
96 def _is_section_key(self, key):
97 if key[0].upper()==key[0] and not key.startswith('_'):
97 if key[0].upper()==key[0] and not key.startswith('_'):
98 return True
98 return True
99 else:
99 else:
100 return False
100 return False
101
101
102 def __contains__(self, key):
102 def __contains__(self, key):
103 if self._is_section_key(key):
103 if self._is_section_key(key):
104 return True
104 return True
105 else:
105 else:
106 return super(Config, self).__contains__(key)
106 return super(Config, self).__contains__(key)
107 # .has_key is deprecated for dictionaries.
107 # .has_key is deprecated for dictionaries.
108 has_key = __contains__
108 has_key = __contains__
109
109
110 def _has_section(self, key):
110 def _has_section(self, key):
111 if self._is_section_key(key):
111 if self._is_section_key(key):
112 if super(Config, self).__contains__(key):
112 if super(Config, self).__contains__(key):
113 return True
113 return True
114 return False
114 return False
115
115
116 def copy(self):
116 def copy(self):
117 return type(self)(dict.copy(self))
117 return type(self)(dict.copy(self))
118
118
119 def __copy__(self):
119 def __copy__(self):
120 return self.copy()
120 return self.copy()
121
121
122 def __deepcopy__(self, memo):
122 def __deepcopy__(self, memo):
123 import copy
123 import copy
124 return type(self)(copy.deepcopy(self.items()))
124 return type(self)(copy.deepcopy(self.items()))
125
125
126 def __getitem__(self, key):
126 def __getitem__(self, key):
127 # We cannot use directly self._is_section_key, because it triggers
127 # We cannot use directly self._is_section_key, because it triggers
128 # infinite recursion on top of PyPy. Instead, we manually fish the
128 # infinite recursion on top of PyPy. Instead, we manually fish the
129 # bound method.
129 # bound method.
130 is_section_key = self.__class__._is_section_key.__get__(self)
130 is_section_key = self.__class__._is_section_key.__get__(self)
131
131
132 # Because we use this for an exec namespace, we need to delegate
132 # Because we use this for an exec namespace, we need to delegate
133 # the lookup of names in __builtin__ to itself. This means
133 # the lookup of names in __builtin__ to itself. This means
134 # that you can't have section or attribute names that are
134 # that you can't have section or attribute names that are
135 # builtins.
135 # builtins.
136 try:
136 try:
137 return getattr(builtin_mod, key)
137 return getattr(builtin_mod, key)
138 except AttributeError:
138 except AttributeError:
139 pass
139 pass
140 if is_section_key(key):
140 if is_section_key(key):
141 try:
141 try:
142 return dict.__getitem__(self, key)
142 return dict.__getitem__(self, key)
143 except KeyError:
143 except KeyError:
144 c = Config()
144 c = Config()
145 dict.__setitem__(self, key, c)
145 dict.__setitem__(self, key, c)
146 return c
146 return c
147 else:
147 else:
148 return dict.__getitem__(self, key)
148 return dict.__getitem__(self, key)
149
149
150 def __setitem__(self, key, value):
150 def __setitem__(self, key, value):
151 # Don't allow names in __builtin__ to be modified.
151 # Don't allow names in __builtin__ to be modified.
152 if hasattr(builtin_mod, key):
152 if hasattr(builtin_mod, key):
153 raise ConfigError('Config variable names cannot have the same name '
153 raise ConfigError('Config variable names cannot have the same name '
154 'as a Python builtin: %s' % key)
154 'as a Python builtin: %s' % key)
155 if self._is_section_key(key):
155 if self._is_section_key(key):
156 if not isinstance(value, Config):
156 if not isinstance(value, Config):
157 raise ValueError('values whose keys begin with an uppercase '
157 raise ValueError('values whose keys begin with an uppercase '
158 'char must be Config instances: %r, %r' % (key, value))
158 'char must be Config instances: %r, %r' % (key, value))
159 else:
159 else:
160 dict.__setitem__(self, key, value)
160 dict.__setitem__(self, key, value)
161
161
162 def __getattr__(self, key):
162 def __getattr__(self, key):
163 try:
163 try:
164 return self.__getitem__(key)
164 return self.__getitem__(key)
165 except KeyError, e:
165 except KeyError, e:
166 raise AttributeError(e)
166 raise AttributeError(e)
167
167
168 def __setattr__(self, key, value):
168 def __setattr__(self, key, value):
169 try:
169 try:
170 self.__setitem__(key, value)
170 self.__setitem__(key, value)
171 except KeyError, e:
171 except KeyError, e:
172 raise AttributeError(e)
172 raise AttributeError(e)
173
173
174 def __delattr__(self, key):
174 def __delattr__(self, key):
175 try:
175 try:
176 dict.__delitem__(self, key)
176 dict.__delitem__(self, key)
177 except KeyError, e:
177 except KeyError, e:
178 raise AttributeError(e)
178 raise AttributeError(e)
179
179
180
180
181 #-----------------------------------------------------------------------------
181 #-----------------------------------------------------------------------------
182 # Config loading classes
182 # Config loading classes
183 #-----------------------------------------------------------------------------
183 #-----------------------------------------------------------------------------
184
184
185
185
186 class ConfigLoader(object):
186 class ConfigLoader(object):
187 """A object for loading configurations from just about anywhere.
187 """A object for loading configurations from just about anywhere.
188
188
189 The resulting configuration is packaged as a :class:`Struct`.
189 The resulting configuration is packaged as a :class:`Struct`.
190
190
191 Notes
191 Notes
192 -----
192 -----
193 A :class:`ConfigLoader` does one thing: load a config from a source
193 A :class:`ConfigLoader` does one thing: load a config from a source
194 (file, command line arguments) and returns the data as a :class:`Struct`.
194 (file, command line arguments) and returns the data as a :class:`Struct`.
195 There are lots of things that :class:`ConfigLoader` does not do. It does
195 There are lots of things that :class:`ConfigLoader` does not do. It does
196 not implement complex logic for finding config files. It does not handle
196 not implement complex logic for finding config files. It does not handle
197 default values or merge multiple configs. These things need to be
197 default values or merge multiple configs. These things need to be
198 handled elsewhere.
198 handled elsewhere.
199 """
199 """
200
200
201 def __init__(self):
201 def __init__(self):
202 """A base class for config loaders.
202 """A base class for config loaders.
203
203
204 Examples
204 Examples
205 --------
205 --------
206
206
207 >>> cl = ConfigLoader()
207 >>> cl = ConfigLoader()
208 >>> config = cl.load_config()
208 >>> config = cl.load_config()
209 >>> config
209 >>> config
210 {}
210 {}
211 """
211 """
212 self.clear()
212 self.clear()
213
213
214 def clear(self):
214 def clear(self):
215 self.config = Config()
215 self.config = Config()
216
216
217 def load_config(self):
217 def load_config(self):
218 """Load a config from somewhere, return a :class:`Config` instance.
218 """Load a config from somewhere, return a :class:`Config` instance.
219
219
220 Usually, this will cause self.config to be set and then returned.
220 Usually, this will cause self.config to be set and then returned.
221 However, in most cases, :meth:`ConfigLoader.clear` should be called
221 However, in most cases, :meth:`ConfigLoader.clear` should be called
222 to erase any previous state.
222 to erase any previous state.
223 """
223 """
224 self.clear()
224 self.clear()
225 return self.config
225 return self.config
226
226
227
227
228 class FileConfigLoader(ConfigLoader):
228 class FileConfigLoader(ConfigLoader):
229 """A base class for file based configurations.
229 """A base class for file based configurations.
230
230
231 As we add more file based config loaders, the common logic should go
231 As we add more file based config loaders, the common logic should go
232 here.
232 here.
233 """
233 """
234 pass
234 pass
235
235
236
236
237 class PyFileConfigLoader(FileConfigLoader):
237 class PyFileConfigLoader(FileConfigLoader):
238 """A config loader for pure python files.
238 """A config loader for pure python files.
239
239
240 This calls execfile on a plain python file and looks for attributes
240 This calls execfile on a plain python file and looks for attributes
241 that are all caps. These attribute are added to the config Struct.
241 that are all caps. These attribute are added to the config Struct.
242 """
242 """
243
243
244 def __init__(self, filename, path=None):
244 def __init__(self, filename, path=None):
245 """Build a config loader for a filename and path.
245 """Build a config loader for a filename and path.
246
246
247 Parameters
247 Parameters
248 ----------
248 ----------
249 filename : str
249 filename : str
250 The file name of the config file.
250 The file name of the config file.
251 path : str, list, tuple
251 path : str, list, tuple
252 The path to search for the config file on, or a sequence of
252 The path to search for the config file on, or a sequence of
253 paths to try in order.
253 paths to try in order.
254 """
254 """
255 super(PyFileConfigLoader, self).__init__()
255 super(PyFileConfigLoader, self).__init__()
256 self.filename = filename
256 self.filename = filename
257 self.path = path
257 self.path = path
258 self.full_filename = ''
258 self.full_filename = ''
259 self.data = None
259 self.data = None
260
260
261 def load_config(self):
261 def load_config(self):
262 """Load the config from a file and return it as a Struct."""
262 """Load the config from a file and return it as a Struct."""
263 self.clear()
263 self.clear()
264 try:
264 try:
265 self._find_file()
265 self._find_file()
266 except IOError as e:
266 except IOError as e:
267 raise ConfigFileNotFound(str(e))
267 raise ConfigFileNotFound(str(e))
268 self._read_file_as_dict()
268 self._read_file_as_dict()
269 self._convert_to_config()
269 self._convert_to_config()
270 return self.config
270 return self.config
271
271
272 def _find_file(self):
272 def _find_file(self):
273 """Try to find the file by searching the paths."""
273 """Try to find the file by searching the paths."""
274 self.full_filename = filefind(self.filename, self.path)
274 self.full_filename = filefind(self.filename, self.path)
275
275
276 def _read_file_as_dict(self):
276 def _read_file_as_dict(self):
277 """Load the config file into self.config, with recursive loading."""
277 """Load the config file into self.config, with recursive loading."""
278 # This closure is made available in the namespace that is used
278 # This closure is made available in the namespace that is used
279 # to exec the config file. It allows users to call
279 # to exec the config file. It allows users to call
280 # load_subconfig('myconfig.py') to load config files recursively.
280 # load_subconfig('myconfig.py') to load config files recursively.
281 # It needs to be a closure because it has references to self.path
281 # It needs to be a closure because it has references to self.path
282 # and self.config. The sub-config is loaded with the same path
282 # and self.config. The sub-config is loaded with the same path
283 # as the parent, but it uses an empty config which is then merged
283 # as the parent, but it uses an empty config which is then merged
284 # with the parents.
284 # with the parents.
285
285
286 # If a profile is specified, the config file will be loaded
286 # If a profile is specified, the config file will be loaded
287 # from that profile
287 # from that profile
288
288
289 def load_subconfig(fname, profile=None):
289 def load_subconfig(fname, profile=None):
290 # import here to prevent circular imports
290 # import here to prevent circular imports
291 from IPython.core.profiledir import ProfileDir, ProfileDirError
291 from IPython.core.profiledir import ProfileDir, ProfileDirError
292 if profile is not None:
292 if profile is not None:
293 try:
293 try:
294 profile_dir = ProfileDir.find_profile_dir_by_name(
294 profile_dir = ProfileDir.find_profile_dir_by_name(
295 get_ipython_dir(),
295 get_ipython_dir(),
296 profile,
296 profile,
297 )
297 )
298 except ProfileDirError:
298 except ProfileDirError:
299 return
299 return
300 path = profile_dir.location
300 path = profile_dir.location
301 else:
301 else:
302 path = self.path
302 path = self.path
303 loader = PyFileConfigLoader(fname, path)
303 loader = PyFileConfigLoader(fname, path)
304 try:
304 try:
305 sub_config = loader.load_config()
305 sub_config = loader.load_config()
306 except ConfigFileNotFound:
306 except ConfigFileNotFound:
307 # Pass silently if the sub config is not there. This happens
307 # Pass silently if the sub config is not there. This happens
308 # when a user s using a profile, but not the default config.
308 # when a user s using a profile, but not the default config.
309 pass
309 pass
310 else:
310 else:
311 self.config._merge(sub_config)
311 self.config._merge(sub_config)
312
312
313 # Again, this needs to be a closure and should be used in config
313 # Again, this needs to be a closure and should be used in config
314 # files to get the config being loaded.
314 # files to get the config being loaded.
315 def get_config():
315 def get_config():
316 return self.config
316 return self.config
317
317
318 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
318 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
319 fs_encoding = sys.getfilesystemencoding() or 'ascii'
319 fs_encoding = sys.getfilesystemencoding() or 'ascii'
320 conf_filename = self.full_filename.encode(fs_encoding)
320 conf_filename = self.full_filename.encode(fs_encoding)
321 py3compat.execfile(conf_filename, namespace)
321 py3compat.execfile(conf_filename, namespace)
322
322
323 def _convert_to_config(self):
323 def _convert_to_config(self):
324 if self.data is None:
324 if self.data is None:
325 ConfigLoaderError('self.data does not exist')
325 ConfigLoaderError('self.data does not exist')
326
326
327
327
328 class CommandLineConfigLoader(ConfigLoader):
328 class CommandLineConfigLoader(ConfigLoader):
329 """A config loader for command line arguments.
329 """A config loader for command line arguments.
330
330
331 As we add more command line based loaders, the common logic should go
331 As we add more command line based loaders, the common logic should go
332 here.
332 here.
333 """
333 """
334
334
335 def _exec_config_str(self, lhs, rhs):
335 def _exec_config_str(self, lhs, rhs):
336 """execute self.config.<lhs>=<rhs>
336 """execute self.config.<lhs>=<rhs>
337
337
338 * expands ~ with expanduser
338 * expands ~ with expanduser
339 * tries to assign with raw exec, otherwise assigns with just the string,
339 * tries to assign with raw exec, otherwise assigns with just the string,
340 allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
340 allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
341 equivalent are `--C.a=4` and `--C.a='4'`.
341 equivalent are `--C.a=4` and `--C.a='4'`.
342 """
342 """
343 rhs = os.path.expanduser(rhs)
343 rhs = os.path.expanduser(rhs)
344 exec_str = 'self.config.' + lhs + '=' + rhs
344 exec_str = 'self.config.' + lhs + '=' + rhs
345 try:
345 try:
346 # Try to see if regular Python syntax will work. This
346 # Try to see if regular Python syntax will work. This
347 # won't handle strings as the quote marks are removed
347 # won't handle strings as the quote marks are removed
348 # by the system shell.
348 # by the system shell.
349 exec exec_str in locals(), globals()
349 exec exec_str in locals(), globals()
350 except (NameError, SyntaxError):
350 except (NameError, SyntaxError):
351 # This case happens if the rhs is a string but without
351 # This case happens if the rhs is a string but without
352 # the quote marks. Use repr, to get quote marks, and
352 # the quote marks. Use repr, to get quote marks, and
353 # 'u' prefix and see if
353 # 'u' prefix and see if
354 # it succeeds. If it still fails, we let it raise.
354 # it succeeds. If it still fails, we let it raise.
355 exec_str = u'self.config.' + lhs + '= rhs'
355 exec_str = u'self.config.' + lhs + '= rhs'
356 exec exec_str in locals(), globals()
356 exec exec_str in locals(), globals()
357
357
358 def _load_flag(self, cfg):
358 def _load_flag(self, cfg):
359 """update self.config from a flag, which can be a dict or Config"""
359 """update self.config from a flag, which can be a dict or Config"""
360 if isinstance(cfg, (dict, Config)):
360 if isinstance(cfg, (dict, Config)):
361 # don't clobber whole config sections, update
361 # don't clobber whole config sections, update
362 # each section from config:
362 # each section from config:
363 for sec,c in cfg.iteritems():
363 for sec,c in cfg.iteritems():
364 self.config[sec].update(c)
364 self.config[sec].update(c)
365 else:
365 else:
366 raise ValueError("Invalid flag: '%s'"%raw)
366 raise TypeError("Invalid flag: %r" % cfg)
367
367
368 # raw --identifier=value pattern
368 # raw --identifier=value pattern
369 # but *also* accept '-' as wordsep, for aliases
369 # but *also* accept '-' as wordsep, for aliases
370 # accepts: --foo=a
370 # accepts: --foo=a
371 # --Class.trait=value
371 # --Class.trait=value
372 # --alias-name=value
372 # --alias-name=value
373 # rejects: -foo=value
373 # rejects: -foo=value
374 # --foo
374 # --foo
375 # --Class.trait
375 # --Class.trait
376 kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*')
376 kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*')
377
377
378 # just flags, no assignments, with two *or one* leading '-'
378 # just flags, no assignments, with two *or one* leading '-'
379 # accepts: --foo
379 # accepts: --foo
380 # -foo-bar-again
380 # -foo-bar-again
381 # rejects: --anything=anything
381 # rejects: --anything=anything
382 # --two.word
382 # --two.word
383
383
384 flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
384 flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
385
385
386 class KeyValueConfigLoader(CommandLineConfigLoader):
386 class KeyValueConfigLoader(CommandLineConfigLoader):
387 """A config loader that loads key value pairs from the command line.
387 """A config loader that loads key value pairs from the command line.
388
388
389 This allows command line options to be gives in the following form::
389 This allows command line options to be gives in the following form::
390
390
391 ipython --profile="foo" --InteractiveShell.autocall=False
391 ipython --profile="foo" --InteractiveShell.autocall=False
392 """
392 """
393
393
394 def __init__(self, argv=None, aliases=None, flags=None):
394 def __init__(self, argv=None, aliases=None, flags=None):
395 """Create a key value pair config loader.
395 """Create a key value pair config loader.
396
396
397 Parameters
397 Parameters
398 ----------
398 ----------
399 argv : list
399 argv : list
400 A list that has the form of sys.argv[1:] which has unicode
400 A list that has the form of sys.argv[1:] which has unicode
401 elements of the form u"key=value". If this is None (default),
401 elements of the form u"key=value". If this is None (default),
402 then sys.argv[1:] will be used.
402 then sys.argv[1:] will be used.
403 aliases : dict
403 aliases : dict
404 A dict of aliases for configurable traits.
404 A dict of aliases for configurable traits.
405 Keys are the short aliases, Values are the resolved trait.
405 Keys are the short aliases, Values are the resolved trait.
406 Of the form: `{'alias' : 'Configurable.trait'}`
406 Of the form: `{'alias' : 'Configurable.trait'}`
407 flags : dict
407 flags : dict
408 A dict of flags, keyed by str name. Vaues can be Config objects,
408 A dict of flags, keyed by str name. Vaues can be Config objects,
409 dicts, or "key=value" strings. If Config or dict, when the flag
409 dicts, or "key=value" strings. If Config or dict, when the flag
410 is triggered, The flag is loaded as `self.config.update(m)`.
410 is triggered, The flag is loaded as `self.config.update(m)`.
411
411
412 Returns
412 Returns
413 -------
413 -------
414 config : Config
414 config : Config
415 The resulting Config object.
415 The resulting Config object.
416
416
417 Examples
417 Examples
418 --------
418 --------
419
419
420 >>> from IPython.config.loader import KeyValueConfigLoader
420 >>> from IPython.config.loader import KeyValueConfigLoader
421 >>> cl = KeyValueConfigLoader()
421 >>> cl = KeyValueConfigLoader()
422 >>> cl.load_config(["--A.name='brian'","--B.number=0"])
422 >>> cl.load_config(["--A.name='brian'","--B.number=0"])
423 {'A': {'name': 'brian'}, 'B': {'number': 0}}
423 {'A': {'name': 'brian'}, 'B': {'number': 0}}
424 """
424 """
425 self.clear()
425 self.clear()
426 if argv is None:
426 if argv is None:
427 argv = sys.argv[1:]
427 argv = sys.argv[1:]
428 self.argv = argv
428 self.argv = argv
429 self.aliases = aliases or {}
429 self.aliases = aliases or {}
430 self.flags = flags or {}
430 self.flags = flags or {}
431
431
432
432
433 def clear(self):
433 def clear(self):
434 super(KeyValueConfigLoader, self).clear()
434 super(KeyValueConfigLoader, self).clear()
435 self.extra_args = []
435 self.extra_args = []
436
436
437
437
438 def _decode_argv(self, argv, enc=None):
438 def _decode_argv(self, argv, enc=None):
439 """decode argv if bytes, using stin.encoding, falling back on default enc"""
439 """decode argv if bytes, using stin.encoding, falling back on default enc"""
440 uargv = []
440 uargv = []
441 if enc is None:
441 if enc is None:
442 enc = text.getdefaultencoding()
442 enc = text.getdefaultencoding()
443 for arg in argv:
443 for arg in argv:
444 if not isinstance(arg, unicode):
444 if not isinstance(arg, unicode):
445 # only decode if not already decoded
445 # only decode if not already decoded
446 arg = arg.decode(enc)
446 arg = arg.decode(enc)
447 uargv.append(arg)
447 uargv.append(arg)
448 return uargv
448 return uargv
449
449
450
450
451 def load_config(self, argv=None, aliases=None, flags=None):
451 def load_config(self, argv=None, aliases=None, flags=None):
452 """Parse the configuration and generate the Config object.
452 """Parse the configuration and generate the Config object.
453
453
454 After loading, any arguments that are not key-value or
454 After loading, any arguments that are not key-value or
455 flags will be stored in self.extra_args - a list of
455 flags will be stored in self.extra_args - a list of
456 unparsed command-line arguments. This is used for
456 unparsed command-line arguments. This is used for
457 arguments such as input files or subcommands.
457 arguments such as input files or subcommands.
458
458
459 Parameters
459 Parameters
460 ----------
460 ----------
461 argv : list, optional
461 argv : list, optional
462 A list that has the form of sys.argv[1:] which has unicode
462 A list that has the form of sys.argv[1:] which has unicode
463 elements of the form u"key=value". If this is None (default),
463 elements of the form u"key=value". If this is None (default),
464 then self.argv will be used.
464 then self.argv will be used.
465 aliases : dict
465 aliases : dict
466 A dict of aliases for configurable traits.
466 A dict of aliases for configurable traits.
467 Keys are the short aliases, Values are the resolved trait.
467 Keys are the short aliases, Values are the resolved trait.
468 Of the form: `{'alias' : 'Configurable.trait'}`
468 Of the form: `{'alias' : 'Configurable.trait'}`
469 flags : dict
469 flags : dict
470 A dict of flags, keyed by str name. Values can be Config objects
470 A dict of flags, keyed by str name. Values can be Config objects
471 or dicts. When the flag is triggered, The config is loaded as
471 or dicts. When the flag is triggered, The config is loaded as
472 `self.config.update(cfg)`.
472 `self.config.update(cfg)`.
473 """
473 """
474 from IPython.config.configurable import Configurable
474 from IPython.config.configurable import Configurable
475
475
476 self.clear()
476 self.clear()
477 if argv is None:
477 if argv is None:
478 argv = self.argv
478 argv = self.argv
479 if aliases is None:
479 if aliases is None:
480 aliases = self.aliases
480 aliases = self.aliases
481 if flags is None:
481 if flags is None:
482 flags = self.flags
482 flags = self.flags
483
483
484 # ensure argv is a list of unicode strings:
484 # ensure argv is a list of unicode strings:
485 uargv = self._decode_argv(argv)
485 uargv = self._decode_argv(argv)
486 for idx,raw in enumerate(uargv):
486 for idx,raw in enumerate(uargv):
487 # strip leading '-'
487 # strip leading '-'
488 item = raw.lstrip('-')
488 item = raw.lstrip('-')
489
489
490 if raw == '--':
490 if raw == '--':
491 # don't parse arguments after '--'
491 # don't parse arguments after '--'
492 # this is useful for relaying arguments to scripts, e.g.
492 # this is useful for relaying arguments to scripts, e.g.
493 # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py
493 # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py
494 self.extra_args.extend(uargv[idx+1:])
494 self.extra_args.extend(uargv[idx+1:])
495 break
495 break
496
496
497 if kv_pattern.match(raw):
497 if kv_pattern.match(raw):
498 lhs,rhs = item.split('=',1)
498 lhs,rhs = item.split('=',1)
499 # Substitute longnames for aliases.
499 # Substitute longnames for aliases.
500 if lhs in aliases:
500 if lhs in aliases:
501 lhs = aliases[lhs]
501 lhs = aliases[lhs]
502 if '.' not in lhs:
502 if '.' not in lhs:
503 # probably a mistyped alias, but not technically illegal
503 # probably a mistyped alias, but not technically illegal
504 warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs)
504 warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs)
505 try:
505 try:
506 self._exec_config_str(lhs, rhs)
506 self._exec_config_str(lhs, rhs)
507 except Exception:
507 except Exception:
508 raise ArgumentError("Invalid argument: '%s'" % raw)
508 raise ArgumentError("Invalid argument: '%s'" % raw)
509
509
510 elif flag_pattern.match(raw):
510 elif flag_pattern.match(raw):
511 if item in flags:
511 if item in flags:
512 cfg,help = flags[item]
512 cfg,help = flags[item]
513 self._load_flag(cfg)
513 self._load_flag(cfg)
514 else:
514 else:
515 raise ArgumentError("Unrecognized flag: '%s'"%raw)
515 raise ArgumentError("Unrecognized flag: '%s'"%raw)
516 elif raw.startswith('-'):
516 elif raw.startswith('-'):
517 kv = '--'+item
517 kv = '--'+item
518 if kv_pattern.match(kv):
518 if kv_pattern.match(kv):
519 raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
519 raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
520 else:
520 else:
521 raise ArgumentError("Invalid argument: '%s'"%raw)
521 raise ArgumentError("Invalid argument: '%s'"%raw)
522 else:
522 else:
523 # keep all args that aren't valid in a list,
523 # keep all args that aren't valid in a list,
524 # in case our parent knows what to do with them.
524 # in case our parent knows what to do with them.
525 self.extra_args.append(item)
525 self.extra_args.append(item)
526 return self.config
526 return self.config
527
527
528 class ArgParseConfigLoader(CommandLineConfigLoader):
528 class ArgParseConfigLoader(CommandLineConfigLoader):
529 """A loader that uses the argparse module to load from the command line."""
529 """A loader that uses the argparse module to load from the command line."""
530
530
531 def __init__(self, argv=None, aliases=None, flags=None, *parser_args, **parser_kw):
531 def __init__(self, argv=None, aliases=None, flags=None, *parser_args, **parser_kw):
532 """Create a config loader for use with argparse.
532 """Create a config loader for use with argparse.
533
533
534 Parameters
534 Parameters
535 ----------
535 ----------
536
536
537 argv : optional, list
537 argv : optional, list
538 If given, used to read command-line arguments from, otherwise
538 If given, used to read command-line arguments from, otherwise
539 sys.argv[1:] is used.
539 sys.argv[1:] is used.
540
540
541 parser_args : tuple
541 parser_args : tuple
542 A tuple of positional arguments that will be passed to the
542 A tuple of positional arguments that will be passed to the
543 constructor of :class:`argparse.ArgumentParser`.
543 constructor of :class:`argparse.ArgumentParser`.
544
544
545 parser_kw : dict
545 parser_kw : dict
546 A tuple of keyword arguments that will be passed to the
546 A tuple of keyword arguments that will be passed to the
547 constructor of :class:`argparse.ArgumentParser`.
547 constructor of :class:`argparse.ArgumentParser`.
548
548
549 Returns
549 Returns
550 -------
550 -------
551 config : Config
551 config : Config
552 The resulting Config object.
552 The resulting Config object.
553 """
553 """
554 super(CommandLineConfigLoader, self).__init__()
554 super(CommandLineConfigLoader, self).__init__()
555 self.clear()
555 self.clear()
556 if argv is None:
556 if argv is None:
557 argv = sys.argv[1:]
557 argv = sys.argv[1:]
558 self.argv = argv
558 self.argv = argv
559 self.aliases = aliases or {}
559 self.aliases = aliases or {}
560 self.flags = flags or {}
560 self.flags = flags or {}
561
561
562 self.parser_args = parser_args
562 self.parser_args = parser_args
563 self.version = parser_kw.pop("version", None)
563 self.version = parser_kw.pop("version", None)
564 kwargs = dict(argument_default=argparse.SUPPRESS)
564 kwargs = dict(argument_default=argparse.SUPPRESS)
565 kwargs.update(parser_kw)
565 kwargs.update(parser_kw)
566 self.parser_kw = kwargs
566 self.parser_kw = kwargs
567
567
568 def load_config(self, argv=None, aliases=None, flags=None):
568 def load_config(self, argv=None, aliases=None, flags=None):
569 """Parse command line arguments and return as a Config object.
569 """Parse command line arguments and return as a Config object.
570
570
571 Parameters
571 Parameters
572 ----------
572 ----------
573
573
574 args : optional, list
574 args : optional, list
575 If given, a list with the structure of sys.argv[1:] to parse
575 If given, a list with the structure of sys.argv[1:] to parse
576 arguments from. If not given, the instance's self.argv attribute
576 arguments from. If not given, the instance's self.argv attribute
577 (given at construction time) is used."""
577 (given at construction time) is used."""
578 self.clear()
578 self.clear()
579 if argv is None:
579 if argv is None:
580 argv = self.argv
580 argv = self.argv
581 if aliases is None:
581 if aliases is None:
582 aliases = self.aliases
582 aliases = self.aliases
583 if flags is None:
583 if flags is None:
584 flags = self.flags
584 flags = self.flags
585 self._create_parser(aliases, flags)
585 self._create_parser(aliases, flags)
586 self._parse_args(argv)
586 self._parse_args(argv)
587 self._convert_to_config()
587 self._convert_to_config()
588 return self.config
588 return self.config
589
589
590 def get_extra_args(self):
590 def get_extra_args(self):
591 if hasattr(self, 'extra_args'):
591 if hasattr(self, 'extra_args'):
592 return self.extra_args
592 return self.extra_args
593 else:
593 else:
594 return []
594 return []
595
595
596 def _create_parser(self, aliases=None, flags=None):
596 def _create_parser(self, aliases=None, flags=None):
597 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
597 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
598 self._add_arguments(aliases, flags)
598 self._add_arguments(aliases, flags)
599
599
600 def _add_arguments(self, aliases=None, flags=None):
600 def _add_arguments(self, aliases=None, flags=None):
601 raise NotImplementedError("subclasses must implement _add_arguments")
601 raise NotImplementedError("subclasses must implement _add_arguments")
602
602
603 def _parse_args(self, args):
603 def _parse_args(self, args):
604 """self.parser->self.parsed_data"""
604 """self.parser->self.parsed_data"""
605 # decode sys.argv to support unicode command-line options
605 # decode sys.argv to support unicode command-line options
606 enc = text.getdefaultencoding()
606 enc = text.getdefaultencoding()
607 uargs = [py3compat.cast_unicode(a, enc) for a in args]
607 uargs = [py3compat.cast_unicode(a, enc) for a in args]
608 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
608 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
609
609
610 def _convert_to_config(self):
610 def _convert_to_config(self):
611 """self.parsed_data->self.config"""
611 """self.parsed_data->self.config"""
612 for k, v in vars(self.parsed_data).iteritems():
612 for k, v in vars(self.parsed_data).iteritems():
613 exec "self.config.%s = v"%k in locals(), globals()
613 exec "self.config.%s = v"%k in locals(), globals()
614
614
615 class KVArgParseConfigLoader(ArgParseConfigLoader):
615 class KVArgParseConfigLoader(ArgParseConfigLoader):
616 """A config loader that loads aliases and flags with argparse,
616 """A config loader that loads aliases and flags with argparse,
617 but will use KVLoader for the rest. This allows better parsing
617 but will use KVLoader for the rest. This allows better parsing
618 of common args, such as `ipython -c 'print 5'`, but still gets
618 of common args, such as `ipython -c 'print 5'`, but still gets
619 arbitrary config with `ipython --InteractiveShell.use_readline=False`"""
619 arbitrary config with `ipython --InteractiveShell.use_readline=False`"""
620
620
621 def _convert_to_config(self):
621 def _convert_to_config(self):
622 """self.parsed_data->self.config"""
622 """self.parsed_data->self.config"""
623 for k, v in vars(self.parsed_data).iteritems():
623 for k, v in vars(self.parsed_data).iteritems():
624 self._exec_config_str(k, v)
624 self._exec_config_str(k, v)
625
625
626 def _add_arguments(self, aliases=None, flags=None):
626 def _add_arguments(self, aliases=None, flags=None):
627 self.alias_flags = {}
627 self.alias_flags = {}
628 # print aliases, flags
628 # print aliases, flags
629 if aliases is None:
629 if aliases is None:
630 aliases = self.aliases
630 aliases = self.aliases
631 if flags is None:
631 if flags is None:
632 flags = self.flags
632 flags = self.flags
633 paa = self.parser.add_argument
633 paa = self.parser.add_argument
634 for key,value in aliases.iteritems():
634 for key,value in aliases.iteritems():
635 if key in flags:
635 if key in flags:
636 # flags
636 # flags
637 nargs = '?'
637 nargs = '?'
638 else:
638 else:
639 nargs = None
639 nargs = None
640 if len(key) is 1:
640 if len(key) is 1:
641 paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs)
641 paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs)
642 else:
642 else:
643 paa('--'+key, type=unicode, dest=value, nargs=nargs)
643 paa('--'+key, type=unicode, dest=value, nargs=nargs)
644 for key, (value, help) in flags.iteritems():
644 for key, (value, help) in flags.iteritems():
645 if key in self.aliases:
645 if key in self.aliases:
646 #
646 #
647 self.alias_flags[self.aliases[key]] = value
647 self.alias_flags[self.aliases[key]] = value
648 continue
648 continue
649 if len(key) is 1:
649 if len(key) is 1:
650 paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value)
650 paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value)
651 else:
651 else:
652 paa('--'+key, action='append_const', dest='_flags', const=value)
652 paa('--'+key, action='append_const', dest='_flags', const=value)
653
653
654 def _convert_to_config(self):
654 def _convert_to_config(self):
655 """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
655 """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
656 # remove subconfigs list from namespace before transforming the Namespace
656 # remove subconfigs list from namespace before transforming the Namespace
657 if '_flags' in self.parsed_data:
657 if '_flags' in self.parsed_data:
658 subcs = self.parsed_data._flags
658 subcs = self.parsed_data._flags
659 del self.parsed_data._flags
659 del self.parsed_data._flags
660 else:
660 else:
661 subcs = []
661 subcs = []
662
662
663 for k, v in vars(self.parsed_data).iteritems():
663 for k, v in vars(self.parsed_data).iteritems():
664 if v is None:
664 if v is None:
665 # it was a flag that shares the name of an alias
665 # it was a flag that shares the name of an alias
666 subcs.append(self.alias_flags[k])
666 subcs.append(self.alias_flags[k])
667 else:
667 else:
668 # eval the KV assignment
668 # eval the KV assignment
669 self._exec_config_str(k, v)
669 self._exec_config_str(k, v)
670
670
671 for subc in subcs:
671 for subc in subcs:
672 self._load_flag(subc)
672 self._load_flag(subc)
673
673
674 if self.extra_args:
674 if self.extra_args:
675 sub_parser = KeyValueConfigLoader()
675 sub_parser = KeyValueConfigLoader()
676 sub_parser.load_config(self.extra_args)
676 sub_parser.load_config(self.extra_args)
677 self.config._merge(sub_parser.config)
677 self.config._merge(sub_parser.config)
678 self.extra_args = sub_parser.extra_args
678 self.extra_args = sub_parser.extra_args
679
679
680
680
681 def load_pyconfig_files(config_files, path):
681 def load_pyconfig_files(config_files, path):
682 """Load multiple Python config files, merging each of them in turn.
682 """Load multiple Python config files, merging each of them in turn.
683
683
684 Parameters
684 Parameters
685 ==========
685 ==========
686 config_files : list of str
686 config_files : list of str
687 List of config files names to load and merge into the config.
687 List of config files names to load and merge into the config.
688 path : unicode
688 path : unicode
689 The full path to the location of the config files.
689 The full path to the location of the config files.
690 """
690 """
691 config = Config()
691 config = Config()
692 for cf in config_files:
692 for cf in config_files:
693 loader = PyFileConfigLoader(cf, path=path)
693 loader = PyFileConfigLoader(cf, path=path)
694 try:
694 try:
695 next_config = loader.load_config()
695 next_config = loader.load_config()
696 except ConfigFileNotFound:
696 except ConfigFileNotFound:
697 pass
697 pass
698 except:
698 except:
699 raise
699 raise
700 else:
700 else:
701 config._merge(next_config)
701 config._merge(next_config)
702 return config
702 return config
@@ -1,3813 +1,3808 b''
1 # encoding: 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-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2011 The IPython Development Team
8 # Copyright (C) 2008-2011 The IPython Development Team
9
9
10 # 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
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__ as builtin_mod
18 import __builtin__ as builtin_mod
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import imp
22 import imp
23 import os
23 import os
24 import sys
24 import sys
25 import shutil
25 import shutil
26 import re
26 import re
27 import time
27 import time
28 import gc
28 import gc
29 from StringIO import StringIO
29 from StringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32 from xmlrpclib import ServerProxy
32 from xmlrpclib import ServerProxy
33
33
34 # cProfile was added in Python2.5
34 # cProfile was added in Python2.5
35 try:
35 try:
36 import cProfile as profile
36 import cProfile as profile
37 import pstats
37 import pstats
38 except ImportError:
38 except ImportError:
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 import IPython
45 import IPython
46 from IPython.core import debugger, oinspect
46 from IPython.core import debugger, oinspect
47 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48 from IPython.core.error import UsageError
48 from IPython.core.error import UsageError
49 from IPython.core.error import StdinNotImplementedError
49 from IPython.core.error import StdinNotImplementedError
50 from IPython.core.fakemodule import FakeModule
50 from IPython.core.fakemodule import FakeModule
51 from IPython.core.profiledir import ProfileDir
51 from IPython.core.profiledir import ProfileDir
52 from IPython.core.macro import Macro
52 from IPython.core.macro import Macro
53 from IPython.core import magic_arguments, page
53 from IPython.core import magic_arguments, page
54 from IPython.core.prefilter import ESC_MAGIC
54 from IPython.core.prefilter import ESC_MAGIC
55 from IPython.core.pylabtools import mpl_runner
55 from IPython.core.pylabtools import mpl_runner
56 from IPython.testing.skipdoctest import skip_doctest
56 from IPython.testing.skipdoctest import skip_doctest
57 from IPython.utils import py3compat
57 from IPython.utils import py3compat
58 from IPython.utils.io import file_read, nlprint
58 from IPython.utils.io import file_read, nlprint
59 from IPython.utils.module_paths import find_mod
59 from IPython.utils.module_paths import find_mod
60 from IPython.utils.path import get_py_filename, unquote_filename
60 from IPython.utils.path import get_py_filename, unquote_filename
61 from IPython.utils.process import arg_split, abbrev_cwd
61 from IPython.utils.process import arg_split, abbrev_cwd
62 from IPython.utils.terminal import set_term_title
62 from IPython.utils.terminal import set_term_title
63 from IPython.utils.text import LSString, SList, format_screen
63 from IPython.utils.text import LSString, SList, format_screen
64 from IPython.utils.timing import clock, clock2
64 from IPython.utils.timing import clock, clock2
65 from IPython.utils.warn import warn, error
65 from IPython.utils.warn import warn, error
66 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
67 from IPython.config.application import Application
67 from IPython.config.application import Application
68
68
69 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
70 # Utility functions
70 # Utility functions
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72
72
73 def on_off(tag):
73 def on_off(tag):
74 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
74 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
75 return ['OFF','ON'][tag]
75 return ['OFF','ON'][tag]
76
76
77 class Bunch: pass
77 class Bunch: pass
78
78
79 def compress_dhist(dh):
79 def compress_dhist(dh):
80 head, tail = dh[:-10], dh[-10:]
80 head, tail = dh[:-10], dh[-10:]
81
81
82 newhead = []
82 newhead = []
83 done = set()
83 done = set()
84 for h in head:
84 for h in head:
85 if h in done:
85 if h in done:
86 continue
86 continue
87 newhead.append(h)
87 newhead.append(h)
88 done.add(h)
88 done.add(h)
89
89
90 return newhead + tail
90 return newhead + tail
91
91
92 def needs_local_scope(func):
92 def needs_local_scope(func):
93 """Decorator to mark magic functions which need to local scope to run."""
93 """Decorator to mark magic functions which need to local scope to run."""
94 func.needs_local_scope = True
94 func.needs_local_scope = True
95 return func
95 return func
96
96
97
97
98 # Used for exception handling in magic_edit
98 # Used for exception handling in magic_edit
99 class MacroToEdit(ValueError): pass
99 class MacroToEdit(ValueError): pass
100
100
101 # Taken from PEP 263, this is the official encoding regexp.
101 # Taken from PEP 263, this is the official encoding regexp.
102 _encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
102 _encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)")
103
103
104 #***************************************************************************
104 #***************************************************************************
105 # Main class implementing Magic functionality
105 # Main class implementing Magic functionality
106
106
107 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
107 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
108 # on construction of the main InteractiveShell object. Something odd is going
108 # on construction of the main InteractiveShell object. Something odd is going
109 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
109 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
110 # eventually this needs to be clarified.
110 # eventually this needs to be clarified.
111 # BG: This is because InteractiveShell inherits from this, but is itself a
111 # BG: This is because InteractiveShell inherits from this, but is itself a
112 # Configurable. This messes up the MRO in some way. The fix is that we need to
112 # Configurable. This messes up the MRO in some way. The fix is that we need to
113 # make Magic a configurable that InteractiveShell does not subclass.
113 # make Magic a configurable that InteractiveShell does not subclass.
114
114
115 class Magic:
115 class Magic:
116 """Magic functions for InteractiveShell.
116 """Magic functions for InteractiveShell.
117
117
118 Shell functions which can be reached as %function_name. All magic
118 Shell functions which can be reached as %function_name. All magic
119 functions should accept a string, which they can parse for their own
119 functions should accept a string, which they can parse for their own
120 needs. This can make some functions easier to type, eg `%cd ../`
120 needs. This can make some functions easier to type, eg `%cd ../`
121 vs. `%cd("../")`
121 vs. `%cd("../")`
122
122
123 ALL definitions MUST begin with the prefix magic_. The user won't need it
123 ALL definitions MUST begin with the prefix magic_. The user won't need it
124 at the command line, but it is is needed in the definition. """
124 at the command line, but it is is needed in the definition. """
125
125
126 # class globals
126 # class globals
127 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
127 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
128 'Automagic is ON, % prefix NOT needed for magic functions.']
128 'Automagic is ON, % prefix NOT needed for magic functions.']
129
129
130
130
131 configurables = None
131 configurables = None
132 #......................................................................
132 #......................................................................
133 # some utility functions
133 # some utility functions
134
134
135 def __init__(self,shell):
135 def __init__(self,shell):
136
136
137 self.options_table = {}
137 self.options_table = {}
138 if profile is None:
138 if profile is None:
139 self.magic_prun = self.profile_missing_notice
139 self.magic_prun = self.profile_missing_notice
140 self.shell = shell
140 self.shell = shell
141 if self.configurables is None:
141 if self.configurables is None:
142 self.configurables = []
142 self.configurables = []
143
143
144 # namespace for holding state we may need
144 # namespace for holding state we may need
145 self._magic_state = Bunch()
145 self._magic_state = Bunch()
146
146
147 def profile_missing_notice(self, *args, **kwargs):
147 def profile_missing_notice(self, *args, **kwargs):
148 error("""\
148 error("""\
149 The profile module could not be found. It has been removed from the standard
149 The profile module could not be found. It has been removed from the standard
150 python packages because of its non-free license. To use profiling, install the
150 python packages because of its non-free license. To use profiling, install the
151 python-profiler package from non-free.""")
151 python-profiler package from non-free.""")
152
152
153 def default_option(self,fn,optstr):
153 def default_option(self,fn,optstr):
154 """Make an entry in the options_table for fn, with value optstr"""
154 """Make an entry in the options_table for fn, with value optstr"""
155
155
156 if fn not in self.lsmagic():
156 if fn not in self.lsmagic():
157 error("%s is not a magic function" % fn)
157 error("%s is not a magic function" % fn)
158 self.options_table[fn] = optstr
158 self.options_table[fn] = optstr
159
159
160 def lsmagic(self):
160 def lsmagic(self):
161 """Return a list of currently available magic functions.
161 """Return a list of currently available magic functions.
162
162
163 Gives a list of the bare names after mangling (['ls','cd', ...], not
163 Gives a list of the bare names after mangling (['ls','cd', ...], not
164 ['magic_ls','magic_cd',...]"""
164 ['magic_ls','magic_cd',...]"""
165
165
166 # FIXME. This needs a cleanup, in the way the magics list is built.
166 # FIXME. This needs a cleanup, in the way the magics list is built.
167
167
168 # magics in class definition
168 # magics in class definition
169 class_magic = lambda fn: fn.startswith('magic_') and \
169 class_magic = lambda fn: fn.startswith('magic_') and \
170 callable(Magic.__dict__[fn])
170 callable(Magic.__dict__[fn])
171 # in instance namespace (run-time user additions)
171 # in instance namespace (run-time user additions)
172 inst_magic = lambda fn: fn.startswith('magic_') and \
172 inst_magic = lambda fn: fn.startswith('magic_') and \
173 callable(self.__dict__[fn])
173 callable(self.__dict__[fn])
174 # and bound magics by user (so they can access self):
174 # and bound magics by user (so they can access self):
175 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
175 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
176 callable(self.__class__.__dict__[fn])
176 callable(self.__class__.__dict__[fn])
177 magics = filter(class_magic,Magic.__dict__.keys()) + \
177 magics = filter(class_magic,Magic.__dict__.keys()) + \
178 filter(inst_magic,self.__dict__.keys()) + \
178 filter(inst_magic,self.__dict__.keys()) + \
179 filter(inst_bound_magic,self.__class__.__dict__.keys())
179 filter(inst_bound_magic,self.__class__.__dict__.keys())
180 out = []
180 out = []
181 for fn in set(magics):
181 for fn in set(magics):
182 out.append(fn.replace('magic_','',1))
182 out.append(fn.replace('magic_','',1))
183 out.sort()
183 out.sort()
184 return out
184 return out
185
185
186 def extract_input_lines(self, range_str, raw=False):
186 def extract_input_lines(self, range_str, raw=False):
187 """Return as a string a set of input history slices.
187 """Return as a string a set of input history slices.
188
188
189 Parameters
189 Parameters
190 ----------
190 ----------
191 range_str : string
191 range_str : string
192 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
192 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
193 since this function is for use by magic functions which get their
193 since this function is for use by magic functions which get their
194 arguments as strings. The number before the / is the session
194 arguments as strings. The number before the / is the session
195 number: ~n goes n back from the current session.
195 number: ~n goes n back from the current session.
196
196
197 Optional Parameters:
197 Optional Parameters:
198 - raw(False): by default, the processed input is used. If this is
198 - raw(False): by default, the processed input is used. If this is
199 true, the raw input history is used instead.
199 true, the raw input history is used instead.
200
200
201 Note that slices can be called with two notations:
201 Note that slices can be called with two notations:
202
202
203 N:M -> standard python form, means including items N...(M-1).
203 N:M -> standard python form, means including items N...(M-1).
204
204
205 N-M -> include items N..M (closed endpoint)."""
205 N-M -> include items N..M (closed endpoint)."""
206 lines = self.shell.history_manager.\
206 lines = self.shell.history_manager.\
207 get_range_by_str(range_str, raw=raw)
207 get_range_by_str(range_str, raw=raw)
208 return "\n".join(x for _, _, x in lines)
208 return "\n".join(x for _, _, x in lines)
209
209
210 def arg_err(self,func):
210 def arg_err(self,func):
211 """Print docstring if incorrect arguments were passed"""
211 """Print docstring if incorrect arguments were passed"""
212 print 'Error in arguments:'
212 print 'Error in arguments:'
213 print oinspect.getdoc(func)
213 print oinspect.getdoc(func)
214
214
215 def format_latex(self,strng):
215 def format_latex(self,strng):
216 """Format a string for latex inclusion."""
216 """Format a string for latex inclusion."""
217
217
218 # Characters that need to be escaped for latex:
218 # Characters that need to be escaped for latex:
219 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
219 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
220 # Magic command names as headers:
220 # Magic command names as headers:
221 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
221 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
222 re.MULTILINE)
222 re.MULTILINE)
223 # Magic commands
223 # Magic commands
224 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
224 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
225 re.MULTILINE)
225 re.MULTILINE)
226 # Paragraph continue
226 # Paragraph continue
227 par_re = re.compile(r'\\$',re.MULTILINE)
227 par_re = re.compile(r'\\$',re.MULTILINE)
228
228
229 # The "\n" symbol
229 # The "\n" symbol
230 newline_re = re.compile(r'\\n')
230 newline_re = re.compile(r'\\n')
231
231
232 # Now build the string for output:
232 # Now build the string for output:
233 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
233 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
234 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
234 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
235 strng)
235 strng)
236 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
236 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
237 strng = par_re.sub(r'\\\\',strng)
237 strng = par_re.sub(r'\\\\',strng)
238 strng = escape_re.sub(r'\\\1',strng)
238 strng = escape_re.sub(r'\\\1',strng)
239 strng = newline_re.sub(r'\\textbackslash{}n',strng)
239 strng = newline_re.sub(r'\\textbackslash{}n',strng)
240 return strng
240 return strng
241
241
242 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
242 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
243 """Parse options passed to an argument string.
243 """Parse options passed to an argument string.
244
244
245 The interface is similar to that of getopt(), but it returns back a
245 The interface is similar to that of getopt(), but it returns back a
246 Struct with the options as keys and the stripped argument string still
246 Struct with the options as keys and the stripped argument string still
247 as a string.
247 as a string.
248
248
249 arg_str is quoted as a true sys.argv vector by using shlex.split.
249 arg_str is quoted as a true sys.argv vector by using shlex.split.
250 This allows us to easily expand variables, glob files, quote
250 This allows us to easily expand variables, glob files, quote
251 arguments, etc.
251 arguments, etc.
252
252
253 Options:
253 Options:
254 -mode: default 'string'. If given as 'list', the argument string is
254 -mode: default 'string'. If given as 'list', the argument string is
255 returned as a list (split on whitespace) instead of a string.
255 returned as a list (split on whitespace) instead of a string.
256
256
257 -list_all: put all option values in lists. Normally only options
257 -list_all: put all option values in lists. Normally only options
258 appearing more than once are put in a list.
258 appearing more than once are put in a list.
259
259
260 -posix (True): whether to split the input line in POSIX mode or not,
260 -posix (True): whether to split the input line in POSIX mode or not,
261 as per the conventions outlined in the shlex module from the
261 as per the conventions outlined in the shlex module from the
262 standard library."""
262 standard library."""
263
263
264 # inject default options at the beginning of the input line
264 # inject default options at the beginning of the input line
265 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
265 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
266 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
266 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
267
267
268 mode = kw.get('mode','string')
268 mode = kw.get('mode','string')
269 if mode not in ['string','list']:
269 if mode not in ['string','list']:
270 raise ValueError,'incorrect mode given: %s' % mode
270 raise ValueError,'incorrect mode given: %s' % mode
271 # Get options
271 # Get options
272 list_all = kw.get('list_all',0)
272 list_all = kw.get('list_all',0)
273 posix = kw.get('posix', os.name == 'posix')
273 posix = kw.get('posix', os.name == 'posix')
274 strict = kw.get('strict', True)
274 strict = kw.get('strict', True)
275
275
276 # Check if we have more than one argument to warrant extra processing:
276 # Check if we have more than one argument to warrant extra processing:
277 odict = {} # Dictionary with options
277 odict = {} # Dictionary with options
278 args = arg_str.split()
278 args = arg_str.split()
279 if len(args) >= 1:
279 if len(args) >= 1:
280 # If the list of inputs only has 0 or 1 thing in it, there's no
280 # If the list of inputs only has 0 or 1 thing in it, there's no
281 # need to look for options
281 # need to look for options
282 argv = arg_split(arg_str, posix, strict)
282 argv = arg_split(arg_str, posix, strict)
283 # Do regular option processing
283 # Do regular option processing
284 try:
284 try:
285 opts,args = getopt(argv,opt_str,*long_opts)
285 opts,args = getopt(argv,opt_str,*long_opts)
286 except GetoptError,e:
286 except GetoptError,e:
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
288 " ".join(long_opts)))
288 " ".join(long_opts)))
289 for o,a in opts:
289 for o,a in opts:
290 if o.startswith('--'):
290 if o.startswith('--'):
291 o = o[2:]
291 o = o[2:]
292 else:
292 else:
293 o = o[1:]
293 o = o[1:]
294 try:
294 try:
295 odict[o].append(a)
295 odict[o].append(a)
296 except AttributeError:
296 except AttributeError:
297 odict[o] = [odict[o],a]
297 odict[o] = [odict[o],a]
298 except KeyError:
298 except KeyError:
299 if list_all:
299 if list_all:
300 odict[o] = [a]
300 odict[o] = [a]
301 else:
301 else:
302 odict[o] = a
302 odict[o] = a
303
303
304 # Prepare opts,args for return
304 # Prepare opts,args for return
305 opts = Struct(odict)
305 opts = Struct(odict)
306 if mode == 'string':
306 if mode == 'string':
307 args = ' '.join(args)
307 args = ' '.join(args)
308
308
309 return opts,args
309 return opts,args
310
310
311 #......................................................................
311 #......................................................................
312 # And now the actual magic functions
312 # And now the actual magic functions
313
313
314 # Functions for IPython shell work (vars,funcs, config, etc)
314 # Functions for IPython shell work (vars,funcs, config, etc)
315 def magic_lsmagic(self, parameter_s = ''):
315 def magic_lsmagic(self, parameter_s = ''):
316 """List currently available magic functions."""
316 """List currently available magic functions."""
317 mesc = ESC_MAGIC
317 mesc = ESC_MAGIC
318 print 'Available magic functions:\n'+mesc+\
318 print 'Available magic functions:\n'+mesc+\
319 (' '+mesc).join(self.lsmagic())
319 (' '+mesc).join(self.lsmagic())
320 print '\n' + Magic.auto_status[self.shell.automagic]
320 print '\n' + Magic.auto_status[self.shell.automagic]
321 return None
321 return None
322
322
323 def magic_magic(self, parameter_s = ''):
323 def magic_magic(self, parameter_s = ''):
324 """Print information about the magic function system.
324 """Print information about the magic function system.
325
325
326 Supported formats: -latex, -brief, -rest
326 Supported formats: -latex, -brief, -rest
327 """
327 """
328
328
329 mode = ''
329 mode = ''
330 try:
330 try:
331 if parameter_s.split()[0] == '-latex':
331 if parameter_s.split()[0] == '-latex':
332 mode = 'latex'
332 mode = 'latex'
333 if parameter_s.split()[0] == '-brief':
333 if parameter_s.split()[0] == '-brief':
334 mode = 'brief'
334 mode = 'brief'
335 if parameter_s.split()[0] == '-rest':
335 if parameter_s.split()[0] == '-rest':
336 mode = 'rest'
336 mode = 'rest'
337 rest_docs = []
337 rest_docs = []
338 except:
338 except:
339 pass
339 pass
340
340
341 magic_docs = []
341 magic_docs = []
342 for fname in self.lsmagic():
342 for fname in self.lsmagic():
343 mname = 'magic_' + fname
343 mname = 'magic_' + fname
344 for space in (Magic,self,self.__class__):
344 for space in (Magic,self,self.__class__):
345 try:
345 try:
346 fn = space.__dict__[mname]
346 fn = space.__dict__[mname]
347 except KeyError:
347 except KeyError:
348 pass
348 pass
349 else:
349 else:
350 break
350 break
351 if mode == 'brief':
351 if mode == 'brief':
352 # only first line
352 # only first line
353 if fn.__doc__:
353 if fn.__doc__:
354 fndoc = fn.__doc__.split('\n',1)[0]
354 fndoc = fn.__doc__.split('\n',1)[0]
355 else:
355 else:
356 fndoc = 'No documentation'
356 fndoc = 'No documentation'
357 else:
357 else:
358 if fn.__doc__:
358 if fn.__doc__:
359 fndoc = fn.__doc__.rstrip()
359 fndoc = fn.__doc__.rstrip()
360 else:
360 else:
361 fndoc = 'No documentation'
361 fndoc = 'No documentation'
362
362
363
363
364 if mode == 'rest':
364 if mode == 'rest':
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
366 fname,fndoc))
366 fname,fndoc))
367
367
368 else:
368 else:
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
370 fname,fndoc))
370 fname,fndoc))
371
371
372 magic_docs = ''.join(magic_docs)
372 magic_docs = ''.join(magic_docs)
373
373
374 if mode == 'rest':
374 if mode == 'rest':
375 return "".join(rest_docs)
375 return "".join(rest_docs)
376
376
377 if mode == 'latex':
377 if mode == 'latex':
378 print self.format_latex(magic_docs)
378 print self.format_latex(magic_docs)
379 return
379 return
380 else:
380 else:
381 magic_docs = format_screen(magic_docs)
381 magic_docs = format_screen(magic_docs)
382 if mode == 'brief':
382 if mode == 'brief':
383 return magic_docs
383 return magic_docs
384
384
385 outmsg = """
385 outmsg = """
386 IPython's 'magic' functions
386 IPython's 'magic' functions
387 ===========================
387 ===========================
388
388
389 The magic function system provides a series of functions which allow you to
389 The magic function system provides a series of functions which allow you to
390 control the behavior of IPython itself, plus a lot of system-type
390 control the behavior of IPython itself, plus a lot of system-type
391 features. All these functions are prefixed with a % character, but parameters
391 features. All these functions are prefixed with a % character, but parameters
392 are given without parentheses or quotes.
392 are given without parentheses or quotes.
393
393
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
395 %automagic function), you don't need to type in the % explicitly. By default,
395 %automagic function), you don't need to type in the % explicitly. By default,
396 IPython ships with automagic on, so you should only rarely need the % escape.
396 IPython ships with automagic on, so you should only rarely need the % escape.
397
397
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
399 to 'mydir', if it exists.
399 to 'mydir', if it exists.
400
400
401 For a list of the available magic functions, use %lsmagic. For a description
401 For a list of the available magic functions, use %lsmagic. For a description
402 of any of them, type %magic_name?, e.g. '%cd?'.
402 of any of them, type %magic_name?, e.g. '%cd?'.
403
403
404 Currently the magic system has the following functions:\n"""
404 Currently the magic system has the following functions:\n"""
405
405
406 mesc = ESC_MAGIC
406 mesc = ESC_MAGIC
407 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
407 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
408 "\n\n%s%s\n\n%s" % (outmsg,
408 "\n\n%s%s\n\n%s" % (outmsg,
409 magic_docs,mesc,mesc,
409 magic_docs,mesc,mesc,
410 (' '+mesc).join(self.lsmagic()),
410 (' '+mesc).join(self.lsmagic()),
411 Magic.auto_status[self.shell.automagic] ) )
411 Magic.auto_status[self.shell.automagic] ) )
412 page.page(outmsg)
412 page.page(outmsg)
413
413
414 def magic_automagic(self, parameter_s = ''):
414 def magic_automagic(self, parameter_s = ''):
415 """Make magic functions callable without having to type the initial %.
415 """Make magic functions callable without having to type the initial %.
416
416
417 Without argumentsl toggles on/off (when off, you must call it as
417 Without argumentsl toggles on/off (when off, you must call it as
418 %automagic, of course). With arguments it sets the value, and you can
418 %automagic, of course). With arguments it sets the value, and you can
419 use any of (case insensitive):
419 use any of (case insensitive):
420
420
421 - on,1,True: to activate
421 - on,1,True: to activate
422
422
423 - off,0,False: to deactivate.
423 - off,0,False: to deactivate.
424
424
425 Note that magic functions have lowest priority, so if there's a
425 Note that magic functions have lowest priority, so if there's a
426 variable whose name collides with that of a magic fn, automagic won't
426 variable whose name collides with that of a magic fn, automagic won't
427 work for that function (you get the variable instead). However, if you
427 work for that function (you get the variable instead). However, if you
428 delete the variable (del var), the previously shadowed magic function
428 delete the variable (del var), the previously shadowed magic function
429 becomes visible to automagic again."""
429 becomes visible to automagic again."""
430
430
431 arg = parameter_s.lower()
431 arg = parameter_s.lower()
432 if parameter_s in ('on','1','true'):
432 if parameter_s in ('on','1','true'):
433 self.shell.automagic = True
433 self.shell.automagic = True
434 elif parameter_s in ('off','0','false'):
434 elif parameter_s in ('off','0','false'):
435 self.shell.automagic = False
435 self.shell.automagic = False
436 else:
436 else:
437 self.shell.automagic = not self.shell.automagic
437 self.shell.automagic = not self.shell.automagic
438 print '\n' + Magic.auto_status[self.shell.automagic]
438 print '\n' + Magic.auto_status[self.shell.automagic]
439
439
440 @skip_doctest
440 @skip_doctest
441 def magic_autocall(self, parameter_s = ''):
441 def magic_autocall(self, parameter_s = ''):
442 """Make functions callable without having to type parentheses.
442 """Make functions callable without having to type parentheses.
443
443
444 Usage:
444 Usage:
445
445
446 %autocall [mode]
446 %autocall [mode]
447
447
448 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
448 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
449 value is toggled on and off (remembering the previous state).
449 value is toggled on and off (remembering the previous state).
450
450
451 In more detail, these values mean:
451 In more detail, these values mean:
452
452
453 0 -> fully disabled
453 0 -> fully disabled
454
454
455 1 -> active, but do not apply if there are no arguments on the line.
455 1 -> active, but do not apply if there are no arguments on the line.
456
456
457 In this mode, you get::
457 In this mode, you get::
458
458
459 In [1]: callable
459 In [1]: callable
460 Out[1]: <built-in function callable>
460 Out[1]: <built-in function callable>
461
461
462 In [2]: callable 'hello'
462 In [2]: callable 'hello'
463 ------> callable('hello')
463 ------> callable('hello')
464 Out[2]: False
464 Out[2]: False
465
465
466 2 -> Active always. Even if no arguments are present, the callable
466 2 -> Active always. Even if no arguments are present, the callable
467 object is called::
467 object is called::
468
468
469 In [2]: float
469 In [2]: float
470 ------> float()
470 ------> float()
471 Out[2]: 0.0
471 Out[2]: 0.0
472
472
473 Note that even with autocall off, you can still use '/' at the start of
473 Note that even with autocall off, you can still use '/' at the start of
474 a line to treat the first argument on the command line as a function
474 a line to treat the first argument on the command line as a function
475 and add parentheses to it::
475 and add parentheses to it::
476
476
477 In [8]: /str 43
477 In [8]: /str 43
478 ------> str(43)
478 ------> str(43)
479 Out[8]: '43'
479 Out[8]: '43'
480
480
481 # all-random (note for auto-testing)
481 # all-random (note for auto-testing)
482 """
482 """
483
483
484 if parameter_s:
484 if parameter_s:
485 arg = int(parameter_s)
485 arg = int(parameter_s)
486 else:
486 else:
487 arg = 'toggle'
487 arg = 'toggle'
488
488
489 if not arg in (0,1,2,'toggle'):
489 if not arg in (0,1,2,'toggle'):
490 error('Valid modes: (0->Off, 1->Smart, 2->Full')
490 error('Valid modes: (0->Off, 1->Smart, 2->Full')
491 return
491 return
492
492
493 if arg in (0,1,2):
493 if arg in (0,1,2):
494 self.shell.autocall = arg
494 self.shell.autocall = arg
495 else: # toggle
495 else: # toggle
496 if self.shell.autocall:
496 if self.shell.autocall:
497 self._magic_state.autocall_save = self.shell.autocall
497 self._magic_state.autocall_save = self.shell.autocall
498 self.shell.autocall = 0
498 self.shell.autocall = 0
499 else:
499 else:
500 try:
500 try:
501 self.shell.autocall = self._magic_state.autocall_save
501 self.shell.autocall = self._magic_state.autocall_save
502 except AttributeError:
502 except AttributeError:
503 self.shell.autocall = self._magic_state.autocall_save = 1
503 self.shell.autocall = self._magic_state.autocall_save = 1
504
504
505 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
505 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
506
506
507
507
508 def magic_page(self, parameter_s=''):
508 def magic_page(self, parameter_s=''):
509 """Pretty print the object and display it through a pager.
509 """Pretty print the object and display it through a pager.
510
510
511 %page [options] OBJECT
511 %page [options] OBJECT
512
512
513 If no object is given, use _ (last output).
513 If no object is given, use _ (last output).
514
514
515 Options:
515 Options:
516
516
517 -r: page str(object), don't pretty-print it."""
517 -r: page str(object), don't pretty-print it."""
518
518
519 # After a function contributed by Olivier Aubert, slightly modified.
519 # After a function contributed by Olivier Aubert, slightly modified.
520
520
521 # Process options/args
521 # Process options/args
522 opts,args = self.parse_options(parameter_s,'r')
522 opts,args = self.parse_options(parameter_s,'r')
523 raw = 'r' in opts
523 raw = 'r' in opts
524
524
525 oname = args and args or '_'
525 oname = args and args or '_'
526 info = self._ofind(oname)
526 info = self._ofind(oname)
527 if info['found']:
527 if info['found']:
528 txt = (raw and str or pformat)( info['obj'] )
528 txt = (raw and str or pformat)( info['obj'] )
529 page.page(txt)
529 page.page(txt)
530 else:
530 else:
531 print 'Object `%s` not found' % oname
531 print 'Object `%s` not found' % oname
532
532
533 def magic_profile(self, parameter_s=''):
533 def magic_profile(self, parameter_s=''):
534 """Print your currently active IPython profile."""
534 """Print your currently active IPython profile."""
535 from IPython.core.application import BaseIPythonApplication
535 from IPython.core.application import BaseIPythonApplication
536 if BaseIPythonApplication.initialized():
536 if BaseIPythonApplication.initialized():
537 print BaseIPythonApplication.instance().profile
537 print BaseIPythonApplication.instance().profile
538 else:
538 else:
539 error("profile is an application-level value, but you don't appear to be in an IPython application")
539 error("profile is an application-level value, but you don't appear to be in an IPython application")
540
540
541 def magic_pinfo(self, parameter_s='', namespaces=None):
541 def magic_pinfo(self, parameter_s='', namespaces=None):
542 """Provide detailed information about an object.
542 """Provide detailed information about an object.
543
543
544 '%pinfo object' is just a synonym for object? or ?object."""
544 '%pinfo object' is just a synonym for object? or ?object."""
545
545
546 #print 'pinfo par: <%s>' % parameter_s # dbg
546 #print 'pinfo par: <%s>' % parameter_s # dbg
547
547
548
548
549 # detail_level: 0 -> obj? , 1 -> obj??
549 # detail_level: 0 -> obj? , 1 -> obj??
550 detail_level = 0
550 detail_level = 0
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
552 # happen if the user types 'pinfo foo?' at the cmd line.
552 # happen if the user types 'pinfo foo?' at the cmd line.
553 pinfo,qmark1,oname,qmark2 = \
553 pinfo,qmark1,oname,qmark2 = \
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
555 if pinfo or qmark1 or qmark2:
555 if pinfo or qmark1 or qmark2:
556 detail_level = 1
556 detail_level = 1
557 if "*" in oname:
557 if "*" in oname:
558 self.magic_psearch(oname)
558 self.magic_psearch(oname)
559 else:
559 else:
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
561 namespaces=namespaces)
561 namespaces=namespaces)
562
562
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
564 """Provide extra detailed information about an object.
564 """Provide extra detailed information about an object.
565
565
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
568 namespaces=namespaces)
568 namespaces=namespaces)
569
569
570 @skip_doctest
570 @skip_doctest
571 def magic_pdef(self, parameter_s='', namespaces=None):
571 def magic_pdef(self, parameter_s='', namespaces=None):
572 """Print the definition header for any callable object.
572 """Print the definition header for any callable object.
573
573
574 If the object is a class, print the constructor information.
574 If the object is a class, print the constructor information.
575
575
576 Examples
576 Examples
577 --------
577 --------
578 ::
578 ::
579
579
580 In [3]: %pdef urllib.urlopen
580 In [3]: %pdef urllib.urlopen
581 urllib.urlopen(url, data=None, proxies=None)
581 urllib.urlopen(url, data=None, proxies=None)
582 """
582 """
583 self._inspect('pdef',parameter_s, namespaces)
583 self._inspect('pdef',parameter_s, namespaces)
584
584
585 def magic_pdoc(self, parameter_s='', namespaces=None):
585 def magic_pdoc(self, parameter_s='', namespaces=None):
586 """Print the docstring for an object.
586 """Print the docstring for an object.
587
587
588 If the given object is a class, it will print both the class and the
588 If the given object is a class, it will print both the class and the
589 constructor docstrings."""
589 constructor docstrings."""
590 self._inspect('pdoc',parameter_s, namespaces)
590 self._inspect('pdoc',parameter_s, namespaces)
591
591
592 def magic_psource(self, parameter_s='', namespaces=None):
592 def magic_psource(self, parameter_s='', namespaces=None):
593 """Print (or run through pager) the source code for an object."""
593 """Print (or run through pager) the source code for an object."""
594 self._inspect('psource',parameter_s, namespaces)
594 self._inspect('psource',parameter_s, namespaces)
595
595
596 def magic_pfile(self, parameter_s=''):
596 def magic_pfile(self, parameter_s=''):
597 """Print (or run through pager) the file where an object is defined.
597 """Print (or run through pager) the file where an object is defined.
598
598
599 The file opens at the line where the object definition begins. IPython
599 The file opens at the line where the object definition begins. IPython
600 will honor the environment variable PAGER if set, and otherwise will
600 will honor the environment variable PAGER if set, and otherwise will
601 do its best to print the file in a convenient form.
601 do its best to print the file in a convenient form.
602
602
603 If the given argument is not an object currently defined, IPython will
603 If the given argument is not an object currently defined, IPython will
604 try to interpret it as a filename (automatically adding a .py extension
604 try to interpret it as a filename (automatically adding a .py extension
605 if needed). You can thus use %pfile as a syntax highlighting code
605 if needed). You can thus use %pfile as a syntax highlighting code
606 viewer."""
606 viewer."""
607
607
608 # first interpret argument as an object name
608 # first interpret argument as an object name
609 out = self._inspect('pfile',parameter_s)
609 out = self._inspect('pfile',parameter_s)
610 # if not, try the input as a filename
610 # if not, try the input as a filename
611 if out == 'not found':
611 if out == 'not found':
612 try:
612 try:
613 filename = get_py_filename(parameter_s)
613 filename = get_py_filename(parameter_s)
614 except IOError,msg:
614 except IOError,msg:
615 print msg
615 print msg
616 return
616 return
617 page.page(self.shell.inspector.format(file(filename).read()))
617 page.page(self.shell.inspector.format(file(filename).read()))
618
618
619 def magic_psearch(self, parameter_s=''):
619 def magic_psearch(self, parameter_s=''):
620 """Search for object in namespaces by wildcard.
620 """Search for object in namespaces by wildcard.
621
621
622 %psearch [options] PATTERN [OBJECT TYPE]
622 %psearch [options] PATTERN [OBJECT TYPE]
623
623
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
626 rest of the command line must be unchanged (options come first), so
626 rest of the command line must be unchanged (options come first), so
627 for example the following forms are equivalent
627 for example the following forms are equivalent
628
628
629 %psearch -i a* function
629 %psearch -i a* function
630 -i a* function?
630 -i a* function?
631 ?-i a* function
631 ?-i a* function
632
632
633 Arguments:
633 Arguments:
634
634
635 PATTERN
635 PATTERN
636
636
637 where PATTERN is a string containing * as a wildcard similar to its
637 where PATTERN is a string containing * as a wildcard similar to its
638 use in a shell. The pattern is matched in all namespaces on the
638 use in a shell. The pattern is matched in all namespaces on the
639 search path. By default objects starting with a single _ are not
639 search path. By default objects starting with a single _ are not
640 matched, many IPython generated objects have a single
640 matched, many IPython generated objects have a single
641 underscore. The default is case insensitive matching. Matching is
641 underscore. The default is case insensitive matching. Matching is
642 also done on the attributes of objects and not only on the objects
642 also done on the attributes of objects and not only on the objects
643 in a module.
643 in a module.
644
644
645 [OBJECT TYPE]
645 [OBJECT TYPE]
646
646
647 Is the name of a python type from the types module. The name is
647 Is the name of a python type from the types module. The name is
648 given in lowercase without the ending type, ex. StringType is
648 given in lowercase without the ending type, ex. StringType is
649 written string. By adding a type here only objects matching the
649 written string. By adding a type here only objects matching the
650 given type are matched. Using all here makes the pattern match all
650 given type are matched. Using all here makes the pattern match all
651 types (this is the default).
651 types (this is the default).
652
652
653 Options:
653 Options:
654
654
655 -a: makes the pattern match even objects whose names start with a
655 -a: makes the pattern match even objects whose names start with a
656 single underscore. These names are normally omitted from the
656 single underscore. These names are normally omitted from the
657 search.
657 search.
658
658
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
660 these options are given, the default is read from your configuration
660 these options are given, the default is read from your configuration
661 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
661 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
662 If this option is not specified in your configuration file, IPython's
662 If this option is not specified in your configuration file, IPython's
663 internal default is to do a case sensitive search.
663 internal default is to do a case sensitive search.
664
664
665 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
665 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
666 specify can be searched in any of the following namespaces:
666 specify can be searched in any of the following namespaces:
667 'builtin', 'user', 'user_global','internal', 'alias', where
667 'builtin', 'user', 'user_global','internal', 'alias', where
668 'builtin' and 'user' are the search defaults. Note that you should
668 'builtin' and 'user' are the search defaults. Note that you should
669 not use quotes when specifying namespaces.
669 not use quotes when specifying namespaces.
670
670
671 'Builtin' contains the python module builtin, 'user' contains all
671 'Builtin' contains the python module builtin, 'user' contains all
672 user data, 'alias' only contain the shell aliases and no python
672 user data, 'alias' only contain the shell aliases and no python
673 objects, 'internal' contains objects used by IPython. The
673 objects, 'internal' contains objects used by IPython. The
674 'user_global' namespace is only used by embedded IPython instances,
674 'user_global' namespace is only used by embedded IPython instances,
675 and it contains module-level globals. You can add namespaces to the
675 and it contains module-level globals. You can add namespaces to the
676 search with -s or exclude them with -e (these options can be given
676 search with -s or exclude them with -e (these options can be given
677 more than once).
677 more than once).
678
678
679 Examples
679 Examples
680 --------
680 --------
681 ::
681 ::
682
682
683 %psearch a* -> objects beginning with an a
683 %psearch a* -> objects beginning with an a
684 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
684 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
685 %psearch a* function -> all functions beginning with an a
685 %psearch a* function -> all functions beginning with an a
686 %psearch re.e* -> objects beginning with an e in module re
686 %psearch re.e* -> objects beginning with an e in module re
687 %psearch r*.e* -> objects that start with e in modules starting in r
687 %psearch r*.e* -> objects that start with e in modules starting in r
688 %psearch r*.* string -> all strings in modules beginning with r
688 %psearch r*.* string -> all strings in modules beginning with r
689
689
690 Case sensitive search::
690 Case sensitive search::
691
691
692 %psearch -c a* list all object beginning with lower case a
692 %psearch -c a* list all object beginning with lower case a
693
693
694 Show objects beginning with a single _::
694 Show objects beginning with a single _::
695
695
696 %psearch -a _* list objects beginning with a single underscore"""
696 %psearch -a _* list objects beginning with a single underscore"""
697 try:
697 try:
698 parameter_s.encode('ascii')
698 parameter_s.encode('ascii')
699 except UnicodeEncodeError:
699 except UnicodeEncodeError:
700 print 'Python identifiers can only contain ascii characters.'
700 print 'Python identifiers can only contain ascii characters.'
701 return
701 return
702
702
703 # default namespaces to be searched
703 # default namespaces to be searched
704 def_search = ['user_local', 'user_global', 'builtin']
704 def_search = ['user_local', 'user_global', 'builtin']
705
705
706 # Process options/args
706 # Process options/args
707 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
707 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
708 opt = opts.get
708 opt = opts.get
709 shell = self.shell
709 shell = self.shell
710 psearch = shell.inspector.psearch
710 psearch = shell.inspector.psearch
711
711
712 # select case options
712 # select case options
713 if opts.has_key('i'):
713 if opts.has_key('i'):
714 ignore_case = True
714 ignore_case = True
715 elif opts.has_key('c'):
715 elif opts.has_key('c'):
716 ignore_case = False
716 ignore_case = False
717 else:
717 else:
718 ignore_case = not shell.wildcards_case_sensitive
718 ignore_case = not shell.wildcards_case_sensitive
719
719
720 # Build list of namespaces to search from user options
720 # Build list of namespaces to search from user options
721 def_search.extend(opt('s',[]))
721 def_search.extend(opt('s',[]))
722 ns_exclude = ns_exclude=opt('e',[])
722 ns_exclude = ns_exclude=opt('e',[])
723 ns_search = [nm for nm in def_search if nm not in ns_exclude]
723 ns_search = [nm for nm in def_search if nm not in ns_exclude]
724
724
725 # Call the actual search
725 # Call the actual search
726 try:
726 try:
727 psearch(args,shell.ns_table,ns_search,
727 psearch(args,shell.ns_table,ns_search,
728 show_all=opt('a'),ignore_case=ignore_case)
728 show_all=opt('a'),ignore_case=ignore_case)
729 except:
729 except:
730 shell.showtraceback()
730 shell.showtraceback()
731
731
732 @skip_doctest
732 @skip_doctest
733 def magic_who_ls(self, parameter_s=''):
733 def magic_who_ls(self, parameter_s=''):
734 """Return a sorted list of all interactive variables.
734 """Return a sorted list of all interactive variables.
735
735
736 If arguments are given, only variables of types matching these
736 If arguments are given, only variables of types matching these
737 arguments are returned.
737 arguments are returned.
738
738
739 Examples
739 Examples
740 --------
740 --------
741
741
742 Define two variables and list them with who_ls::
742 Define two variables and list them with who_ls::
743
743
744 In [1]: alpha = 123
744 In [1]: alpha = 123
745
745
746 In [2]: beta = 'test'
746 In [2]: beta = 'test'
747
747
748 In [3]: %who_ls
748 In [3]: %who_ls
749 Out[3]: ['alpha', 'beta']
749 Out[3]: ['alpha', 'beta']
750
750
751 In [4]: %who_ls int
751 In [4]: %who_ls int
752 Out[4]: ['alpha']
752 Out[4]: ['alpha']
753
753
754 In [5]: %who_ls str
754 In [5]: %who_ls str
755 Out[5]: ['beta']
755 Out[5]: ['beta']
756 """
756 """
757
757
758 user_ns = self.shell.user_ns
758 user_ns = self.shell.user_ns
759 user_ns_hidden = self.shell.user_ns_hidden
759 user_ns_hidden = self.shell.user_ns_hidden
760 out = [ i for i in user_ns
760 out = [ i for i in user_ns
761 if not i.startswith('_') \
761 if not i.startswith('_') \
762 and not i in user_ns_hidden ]
762 and not i in user_ns_hidden ]
763
763
764 typelist = parameter_s.split()
764 typelist = parameter_s.split()
765 if typelist:
765 if typelist:
766 typeset = set(typelist)
766 typeset = set(typelist)
767 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
767 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
768
768
769 out.sort()
769 out.sort()
770 return out
770 return out
771
771
772 @skip_doctest
772 @skip_doctest
773 def magic_who(self, parameter_s=''):
773 def magic_who(self, parameter_s=''):
774 """Print all interactive variables, with some minimal formatting.
774 """Print all interactive variables, with some minimal formatting.
775
775
776 If any arguments are given, only variables whose type matches one of
776 If any arguments are given, only variables whose type matches one of
777 these are printed. For example::
777 these are printed. For example::
778
778
779 %who function str
779 %who function str
780
780
781 will only list functions and strings, excluding all other types of
781 will only list functions and strings, excluding all other types of
782 variables. To find the proper type names, simply use type(var) at a
782 variables. To find the proper type names, simply use type(var) at a
783 command line to see how python prints type names. For example:
783 command line to see how python prints type names. For example:
784
784
785 ::
785 ::
786
786
787 In [1]: type('hello')\\
787 In [1]: type('hello')\\
788 Out[1]: <type 'str'>
788 Out[1]: <type 'str'>
789
789
790 indicates that the type name for strings is 'str'.
790 indicates that the type name for strings is 'str'.
791
791
792 ``%who`` always excludes executed names loaded through your configuration
792 ``%who`` always excludes executed names loaded through your configuration
793 file and things which are internal to IPython.
793 file and things which are internal to IPython.
794
794
795 This is deliberate, as typically you may load many modules and the
795 This is deliberate, as typically you may load many modules and the
796 purpose of %who is to show you only what you've manually defined.
796 purpose of %who is to show you only what you've manually defined.
797
797
798 Examples
798 Examples
799 --------
799 --------
800
800
801 Define two variables and list them with who::
801 Define two variables and list them with who::
802
802
803 In [1]: alpha = 123
803 In [1]: alpha = 123
804
804
805 In [2]: beta = 'test'
805 In [2]: beta = 'test'
806
806
807 In [3]: %who
807 In [3]: %who
808 alpha beta
808 alpha beta
809
809
810 In [4]: %who int
810 In [4]: %who int
811 alpha
811 alpha
812
812
813 In [5]: %who str
813 In [5]: %who str
814 beta
814 beta
815 """
815 """
816
816
817 varlist = self.magic_who_ls(parameter_s)
817 varlist = self.magic_who_ls(parameter_s)
818 if not varlist:
818 if not varlist:
819 if parameter_s:
819 if parameter_s:
820 print 'No variables match your requested type.'
820 print 'No variables match your requested type.'
821 else:
821 else:
822 print 'Interactive namespace is empty.'
822 print 'Interactive namespace is empty.'
823 return
823 return
824
824
825 # if we have variables, move on...
825 # if we have variables, move on...
826 count = 0
826 count = 0
827 for i in varlist:
827 for i in varlist:
828 print i+'\t',
828 print i+'\t',
829 count += 1
829 count += 1
830 if count > 8:
830 if count > 8:
831 count = 0
831 count = 0
832 print
832 print
833 print
833 print
834
834
835 @skip_doctest
835 @skip_doctest
836 def magic_whos(self, parameter_s=''):
836 def magic_whos(self, parameter_s=''):
837 """Like %who, but gives some extra information about each variable.
837 """Like %who, but gives some extra information about each variable.
838
838
839 The same type filtering of %who can be applied here.
839 The same type filtering of %who can be applied here.
840
840
841 For all variables, the type is printed. Additionally it prints:
841 For all variables, the type is printed. Additionally it prints:
842
842
843 - For {},[],(): their length.
843 - For {},[],(): their length.
844
844
845 - For numpy arrays, a summary with shape, number of
845 - For numpy arrays, a summary with shape, number of
846 elements, typecode and size in memory.
846 elements, typecode and size in memory.
847
847
848 - Everything else: a string representation, snipping their middle if
848 - Everything else: a string representation, snipping their middle if
849 too long.
849 too long.
850
850
851 Examples
851 Examples
852 --------
852 --------
853
853
854 Define two variables and list them with whos::
854 Define two variables and list them with whos::
855
855
856 In [1]: alpha = 123
856 In [1]: alpha = 123
857
857
858 In [2]: beta = 'test'
858 In [2]: beta = 'test'
859
859
860 In [3]: %whos
860 In [3]: %whos
861 Variable Type Data/Info
861 Variable Type Data/Info
862 --------------------------------
862 --------------------------------
863 alpha int 123
863 alpha int 123
864 beta str test
864 beta str test
865 """
865 """
866
866
867 varnames = self.magic_who_ls(parameter_s)
867 varnames = self.magic_who_ls(parameter_s)
868 if not varnames:
868 if not varnames:
869 if parameter_s:
869 if parameter_s:
870 print 'No variables match your requested type.'
870 print 'No variables match your requested type.'
871 else:
871 else:
872 print 'Interactive namespace is empty.'
872 print 'Interactive namespace is empty.'
873 return
873 return
874
874
875 # if we have variables, move on...
875 # if we have variables, move on...
876
876
877 # for these types, show len() instead of data:
877 # for these types, show len() instead of data:
878 seq_types = ['dict', 'list', 'tuple']
878 seq_types = ['dict', 'list', 'tuple']
879
879
880 # for numpy arrays, display summary info
880 # for numpy arrays, display summary info
881 ndarray_type = None
881 ndarray_type = None
882 if 'numpy' in sys.modules:
882 if 'numpy' in sys.modules:
883 try:
883 try:
884 from numpy import ndarray
884 from numpy import ndarray
885 except ImportError:
885 except ImportError:
886 pass
886 pass
887 else:
887 else:
888 ndarray_type = ndarray.__name__
888 ndarray_type = ndarray.__name__
889
889
890 # Find all variable names and types so we can figure out column sizes
890 # Find all variable names and types so we can figure out column sizes
891 def get_vars(i):
891 def get_vars(i):
892 return self.shell.user_ns[i]
892 return self.shell.user_ns[i]
893
893
894 # some types are well known and can be shorter
894 # some types are well known and can be shorter
895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
896 def type_name(v):
896 def type_name(v):
897 tn = type(v).__name__
897 tn = type(v).__name__
898 return abbrevs.get(tn,tn)
898 return abbrevs.get(tn,tn)
899
899
900 varlist = map(get_vars,varnames)
900 varlist = map(get_vars,varnames)
901
901
902 typelist = []
902 typelist = []
903 for vv in varlist:
903 for vv in varlist:
904 tt = type_name(vv)
904 tt = type_name(vv)
905
905
906 if tt=='instance':
906 if tt=='instance':
907 typelist.append( abbrevs.get(str(vv.__class__),
907 typelist.append( abbrevs.get(str(vv.__class__),
908 str(vv.__class__)))
908 str(vv.__class__)))
909 else:
909 else:
910 typelist.append(tt)
910 typelist.append(tt)
911
911
912 # column labels and # of spaces as separator
912 # column labels and # of spaces as separator
913 varlabel = 'Variable'
913 varlabel = 'Variable'
914 typelabel = 'Type'
914 typelabel = 'Type'
915 datalabel = 'Data/Info'
915 datalabel = 'Data/Info'
916 colsep = 3
916 colsep = 3
917 # variable format strings
917 # variable format strings
918 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
918 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
919 aformat = "%s: %s elems, type `%s`, %s bytes"
919 aformat = "%s: %s elems, type `%s`, %s bytes"
920 # find the size of the columns to format the output nicely
920 # find the size of the columns to format the output nicely
921 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
921 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
922 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
922 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
923 # table header
923 # table header
924 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
924 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
925 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
925 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
926 # and the table itself
926 # and the table itself
927 kb = 1024
927 kb = 1024
928 Mb = 1048576 # kb**2
928 Mb = 1048576 # kb**2
929 for vname,var,vtype in zip(varnames,varlist,typelist):
929 for vname,var,vtype in zip(varnames,varlist,typelist):
930 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
930 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
931 if vtype in seq_types:
931 if vtype in seq_types:
932 print "n="+str(len(var))
932 print "n="+str(len(var))
933 elif vtype == ndarray_type:
933 elif vtype == ndarray_type:
934 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
934 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
935 if vtype==ndarray_type:
935 if vtype==ndarray_type:
936 # numpy
936 # numpy
937 vsize = var.size
937 vsize = var.size
938 vbytes = vsize*var.itemsize
938 vbytes = vsize*var.itemsize
939 vdtype = var.dtype
939 vdtype = var.dtype
940 else:
941 # Numeric
942 vsize = Numeric.size(var)
943 vbytes = vsize*var.itemsize()
944 vdtype = var.typecode()
945
940
946 if vbytes < 100000:
941 if vbytes < 100000:
947 print aformat % (vshape,vsize,vdtype,vbytes)
942 print aformat % (vshape,vsize,vdtype,vbytes)
948 else:
943 else:
949 print aformat % (vshape,vsize,vdtype,vbytes),
944 print aformat % (vshape,vsize,vdtype,vbytes),
950 if vbytes < Mb:
945 if vbytes < Mb:
951 print '(%s kb)' % (vbytes/kb,)
946 print '(%s kb)' % (vbytes/kb,)
952 else:
947 else:
953 print '(%s Mb)' % (vbytes/Mb,)
948 print '(%s Mb)' % (vbytes/Mb,)
954 else:
949 else:
955 try:
950 try:
956 vstr = str(var)
951 vstr = str(var)
957 except UnicodeEncodeError:
952 except UnicodeEncodeError:
958 vstr = unicode(var).encode(sys.getdefaultencoding(),
953 vstr = unicode(var).encode(sys.getdefaultencoding(),
959 'backslashreplace')
954 'backslashreplace')
960 vstr = vstr.replace('\n','\\n')
955 vstr = vstr.replace('\n','\\n')
961 if len(vstr) < 50:
956 if len(vstr) < 50:
962 print vstr
957 print vstr
963 else:
958 else:
964 print vstr[:25] + "<...>" + vstr[-25:]
959 print vstr[:25] + "<...>" + vstr[-25:]
965
960
966 def magic_reset(self, parameter_s=''):
961 def magic_reset(self, parameter_s=''):
967 """Resets the namespace by removing all names defined by the user, if
962 """Resets the namespace by removing all names defined by the user, if
968 called without arguments, or by removing some types of objects, such
963 called without arguments, or by removing some types of objects, such
969 as everything currently in IPython's In[] and Out[] containers (see
964 as everything currently in IPython's In[] and Out[] containers (see
970 the parameters for details).
965 the parameters for details).
971
966
972 Parameters
967 Parameters
973 ----------
968 ----------
974 -f : force reset without asking for confirmation.
969 -f : force reset without asking for confirmation.
975
970
976 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
971 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
977 References to objects may be kept. By default (without this option),
972 References to objects may be kept. By default (without this option),
978 we do a 'hard' reset, giving you a new session and removing all
973 we do a 'hard' reset, giving you a new session and removing all
979 references to objects from the current session.
974 references to objects from the current session.
980
975
981 in : reset input history
976 in : reset input history
982
977
983 out : reset output history
978 out : reset output history
984
979
985 dhist : reset directory history
980 dhist : reset directory history
986
981
987 array : reset only variables that are NumPy arrays
982 array : reset only variables that are NumPy arrays
988
983
989 See Also
984 See Also
990 --------
985 --------
991 magic_reset_selective : invoked as ``%reset_selective``
986 magic_reset_selective : invoked as ``%reset_selective``
992
987
993 Examples
988 Examples
994 --------
989 --------
995 ::
990 ::
996
991
997 In [6]: a = 1
992 In [6]: a = 1
998
993
999 In [7]: a
994 In [7]: a
1000 Out[7]: 1
995 Out[7]: 1
1001
996
1002 In [8]: 'a' in _ip.user_ns
997 In [8]: 'a' in _ip.user_ns
1003 Out[8]: True
998 Out[8]: True
1004
999
1005 In [9]: %reset -f
1000 In [9]: %reset -f
1006
1001
1007 In [1]: 'a' in _ip.user_ns
1002 In [1]: 'a' in _ip.user_ns
1008 Out[1]: False
1003 Out[1]: False
1009
1004
1010 In [2]: %reset -f in
1005 In [2]: %reset -f in
1011 Flushing input history
1006 Flushing input history
1012
1007
1013 In [3]: %reset -f dhist in
1008 In [3]: %reset -f dhist in
1014 Flushing directory history
1009 Flushing directory history
1015 Flushing input history
1010 Flushing input history
1016
1011
1017 Notes
1012 Notes
1018 -----
1013 -----
1019 Calling this magic from clients that do not implement standard input,
1014 Calling this magic from clients that do not implement standard input,
1020 such as the ipython notebook interface, will reset the namespace
1015 such as the ipython notebook interface, will reset the namespace
1021 without confirmation.
1016 without confirmation.
1022 """
1017 """
1023 opts, args = self.parse_options(parameter_s,'sf', mode='list')
1018 opts, args = self.parse_options(parameter_s,'sf', mode='list')
1024 if 'f' in opts:
1019 if 'f' in opts:
1025 ans = True
1020 ans = True
1026 else:
1021 else:
1027 try:
1022 try:
1028 ans = self.shell.ask_yes_no(
1023 ans = self.shell.ask_yes_no(
1029 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1024 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1030 except StdinNotImplementedError:
1025 except StdinNotImplementedError:
1031 ans = True
1026 ans = True
1032 if not ans:
1027 if not ans:
1033 print 'Nothing done.'
1028 print 'Nothing done.'
1034 return
1029 return
1035
1030
1036 if 's' in opts: # Soft reset
1031 if 's' in opts: # Soft reset
1037 user_ns = self.shell.user_ns
1032 user_ns = self.shell.user_ns
1038 for i in self.magic_who_ls():
1033 for i in self.magic_who_ls():
1039 del(user_ns[i])
1034 del(user_ns[i])
1040 elif len(args) == 0: # Hard reset
1035 elif len(args) == 0: # Hard reset
1041 self.shell.reset(new_session = False)
1036 self.shell.reset(new_session = False)
1042
1037
1043 # reset in/out/dhist/array: previously extensinions/clearcmd.py
1038 # reset in/out/dhist/array: previously extensinions/clearcmd.py
1044 ip = self.shell
1039 ip = self.shell
1045 user_ns = self.user_ns # local lookup, heavily used
1040 user_ns = self.user_ns # local lookup, heavily used
1046
1041
1047 for target in args:
1042 for target in args:
1048 target = target.lower() # make matches case insensitive
1043 target = target.lower() # make matches case insensitive
1049 if target == 'out':
1044 if target == 'out':
1050 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1045 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1051 self.displayhook.flush()
1046 self.displayhook.flush()
1052
1047
1053 elif target == 'in':
1048 elif target == 'in':
1054 print "Flushing input history"
1049 print "Flushing input history"
1055 pc = self.displayhook.prompt_count + 1
1050 pc = self.displayhook.prompt_count + 1
1056 for n in range(1, pc):
1051 for n in range(1, pc):
1057 key = '_i'+repr(n)
1052 key = '_i'+repr(n)
1058 user_ns.pop(key,None)
1053 user_ns.pop(key,None)
1059 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1054 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1060 hm = ip.history_manager
1055 hm = ip.history_manager
1061 # don't delete these, as %save and %macro depending on the length
1056 # don't delete these, as %save and %macro depending on the length
1062 # of these lists to be preserved
1057 # of these lists to be preserved
1063 hm.input_hist_parsed[:] = [''] * pc
1058 hm.input_hist_parsed[:] = [''] * pc
1064 hm.input_hist_raw[:] = [''] * pc
1059 hm.input_hist_raw[:] = [''] * pc
1065 # hm has internal machinery for _i,_ii,_iii, clear it out
1060 # hm has internal machinery for _i,_ii,_iii, clear it out
1066 hm._i = hm._ii = hm._iii = hm._i00 = u''
1061 hm._i = hm._ii = hm._iii = hm._i00 = u''
1067
1062
1068 elif target == 'array':
1063 elif target == 'array':
1069 # Support cleaning up numpy arrays
1064 # Support cleaning up numpy arrays
1070 try:
1065 try:
1071 from numpy import ndarray
1066 from numpy import ndarray
1072 # This must be done with items and not iteritems because we're
1067 # This must be done with items and not iteritems because we're
1073 # going to modify the dict in-place.
1068 # going to modify the dict in-place.
1074 for x,val in user_ns.items():
1069 for x,val in user_ns.items():
1075 if isinstance(val,ndarray):
1070 if isinstance(val,ndarray):
1076 del user_ns[x]
1071 del user_ns[x]
1077 except ImportError:
1072 except ImportError:
1078 print "reset array only works if Numpy is available."
1073 print "reset array only works if Numpy is available."
1079
1074
1080 elif target == 'dhist':
1075 elif target == 'dhist':
1081 print "Flushing directory history"
1076 print "Flushing directory history"
1082 del user_ns['_dh'][:]
1077 del user_ns['_dh'][:]
1083
1078
1084 else:
1079 else:
1085 print "Don't know how to reset ",
1080 print "Don't know how to reset ",
1086 print target + ", please run `%reset?` for details"
1081 print target + ", please run `%reset?` for details"
1087
1082
1088 gc.collect()
1083 gc.collect()
1089
1084
1090 def magic_reset_selective(self, parameter_s=''):
1085 def magic_reset_selective(self, parameter_s=''):
1091 """Resets the namespace by removing names defined by the user.
1086 """Resets the namespace by removing names defined by the user.
1092
1087
1093 Input/Output history are left around in case you need them.
1088 Input/Output history are left around in case you need them.
1094
1089
1095 %reset_selective [-f] regex
1090 %reset_selective [-f] regex
1096
1091
1097 No action is taken if regex is not included
1092 No action is taken if regex is not included
1098
1093
1099 Options
1094 Options
1100 -f : force reset without asking for confirmation.
1095 -f : force reset without asking for confirmation.
1101
1096
1102 See Also
1097 See Also
1103 --------
1098 --------
1104 magic_reset : invoked as ``%reset``
1099 magic_reset : invoked as ``%reset``
1105
1100
1106 Examples
1101 Examples
1107 --------
1102 --------
1108
1103
1109 We first fully reset the namespace so your output looks identical to
1104 We first fully reset the namespace so your output looks identical to
1110 this example for pedagogical reasons; in practice you do not need a
1105 this example for pedagogical reasons; in practice you do not need a
1111 full reset::
1106 full reset::
1112
1107
1113 In [1]: %reset -f
1108 In [1]: %reset -f
1114
1109
1115 Now, with a clean namespace we can make a few variables and use
1110 Now, with a clean namespace we can make a few variables and use
1116 ``%reset_selective`` to only delete names that match our regexp::
1111 ``%reset_selective`` to only delete names that match our regexp::
1117
1112
1118 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1113 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1119
1114
1120 In [3]: who_ls
1115 In [3]: who_ls
1121 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1116 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1122
1117
1123 In [4]: %reset_selective -f b[2-3]m
1118 In [4]: %reset_selective -f b[2-3]m
1124
1119
1125 In [5]: who_ls
1120 In [5]: who_ls
1126 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1121 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1127
1122
1128 In [6]: %reset_selective -f d
1123 In [6]: %reset_selective -f d
1129
1124
1130 In [7]: who_ls
1125 In [7]: who_ls
1131 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1126 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1132
1127
1133 In [8]: %reset_selective -f c
1128 In [8]: %reset_selective -f c
1134
1129
1135 In [9]: who_ls
1130 In [9]: who_ls
1136 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1131 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1137
1132
1138 In [10]: %reset_selective -f b
1133 In [10]: %reset_selective -f b
1139
1134
1140 In [11]: who_ls
1135 In [11]: who_ls
1141 Out[11]: ['a']
1136 Out[11]: ['a']
1142
1137
1143 Notes
1138 Notes
1144 -----
1139 -----
1145 Calling this magic from clients that do not implement standard input,
1140 Calling this magic from clients that do not implement standard input,
1146 such as the ipython notebook interface, will reset the namespace
1141 such as the ipython notebook interface, will reset the namespace
1147 without confirmation.
1142 without confirmation.
1148 """
1143 """
1149
1144
1150 opts, regex = self.parse_options(parameter_s,'f')
1145 opts, regex = self.parse_options(parameter_s,'f')
1151
1146
1152 if opts.has_key('f'):
1147 if opts.has_key('f'):
1153 ans = True
1148 ans = True
1154 else:
1149 else:
1155 try:
1150 try:
1156 ans = self.shell.ask_yes_no(
1151 ans = self.shell.ask_yes_no(
1157 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1152 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1158 default='n')
1153 default='n')
1159 except StdinNotImplementedError:
1154 except StdinNotImplementedError:
1160 ans = True
1155 ans = True
1161 if not ans:
1156 if not ans:
1162 print 'Nothing done.'
1157 print 'Nothing done.'
1163 return
1158 return
1164 user_ns = self.shell.user_ns
1159 user_ns = self.shell.user_ns
1165 if not regex:
1160 if not regex:
1166 print 'No regex pattern specified. Nothing done.'
1161 print 'No regex pattern specified. Nothing done.'
1167 return
1162 return
1168 else:
1163 else:
1169 try:
1164 try:
1170 m = re.compile(regex)
1165 m = re.compile(regex)
1171 except TypeError:
1166 except TypeError:
1172 raise TypeError('regex must be a string or compiled pattern')
1167 raise TypeError('regex must be a string or compiled pattern')
1173 for i in self.magic_who_ls():
1168 for i in self.magic_who_ls():
1174 if m.search(i):
1169 if m.search(i):
1175 del(user_ns[i])
1170 del(user_ns[i])
1176
1171
1177 def magic_xdel(self, parameter_s=''):
1172 def magic_xdel(self, parameter_s=''):
1178 """Delete a variable, trying to clear it from anywhere that
1173 """Delete a variable, trying to clear it from anywhere that
1179 IPython's machinery has references to it. By default, this uses
1174 IPython's machinery has references to it. By default, this uses
1180 the identity of the named object in the user namespace to remove
1175 the identity of the named object in the user namespace to remove
1181 references held under other names. The object is also removed
1176 references held under other names. The object is also removed
1182 from the output history.
1177 from the output history.
1183
1178
1184 Options
1179 Options
1185 -n : Delete the specified name from all namespaces, without
1180 -n : Delete the specified name from all namespaces, without
1186 checking their identity.
1181 checking their identity.
1187 """
1182 """
1188 opts, varname = self.parse_options(parameter_s,'n')
1183 opts, varname = self.parse_options(parameter_s,'n')
1189 try:
1184 try:
1190 self.shell.del_var(varname, ('n' in opts))
1185 self.shell.del_var(varname, ('n' in opts))
1191 except (NameError, ValueError) as e:
1186 except (NameError, ValueError) as e:
1192 print type(e).__name__ +": "+ str(e)
1187 print type(e).__name__ +": "+ str(e)
1193
1188
1194 def magic_logstart(self,parameter_s=''):
1189 def magic_logstart(self,parameter_s=''):
1195 """Start logging anywhere in a session.
1190 """Start logging anywhere in a session.
1196
1191
1197 %logstart [-o|-r|-t] [log_name [log_mode]]
1192 %logstart [-o|-r|-t] [log_name [log_mode]]
1198
1193
1199 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 If no name is given, it defaults to a file named 'ipython_log.py' in your
1200 current directory, in 'rotate' mode (see below).
1195 current directory, in 'rotate' mode (see below).
1201
1196
1202 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1203 history up to that point and then continues logging.
1198 history up to that point and then continues logging.
1204
1199
1205 %logstart takes a second optional parameter: logging mode. This can be one
1200 %logstart takes a second optional parameter: logging mode. This can be one
1206 of (note that the modes are given unquoted):\\
1201 of (note that the modes are given unquoted):\\
1207 append: well, that says it.\\
1202 append: well, that says it.\\
1208 backup: rename (if exists) to name~ and start name.\\
1203 backup: rename (if exists) to name~ and start name.\\
1209 global: single logfile in your home dir, appended to.\\
1204 global: single logfile in your home dir, appended to.\\
1210 over : overwrite existing log.\\
1205 over : overwrite existing log.\\
1211 rotate: create rotating logs name.1~, name.2~, etc.
1206 rotate: create rotating logs name.1~, name.2~, etc.
1212
1207
1213 Options:
1208 Options:
1214
1209
1215 -o: log also IPython's output. In this mode, all commands which
1210 -o: log also IPython's output. In this mode, all commands which
1216 generate an Out[NN] prompt are recorded to the logfile, right after
1211 generate an Out[NN] prompt are recorded to the logfile, right after
1217 their corresponding input line. The output lines are always
1212 their corresponding input line. The output lines are always
1218 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 prepended with a '#[Out]# ' marker, so that the log remains valid
1219 Python code.
1214 Python code.
1220
1215
1221 Since this marker is always the same, filtering only the output from
1216 Since this marker is always the same, filtering only the output from
1222 a log is very easy, using for example a simple awk call::
1217 a log is very easy, using for example a simple awk call::
1223
1218
1224 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1225
1220
1226 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 -r: log 'raw' input. Normally, IPython's logs contain the processed
1227 input, so that user lines are logged in their final form, converted
1222 input, so that user lines are logged in their final form, converted
1228 into valid Python. For example, %Exit is logged as
1223 into valid Python. For example, %Exit is logged as
1229 _ip.magic("Exit"). If the -r flag is given, all input is logged
1224 _ip.magic("Exit"). If the -r flag is given, all input is logged
1230 exactly as typed, with no transformations applied.
1225 exactly as typed, with no transformations applied.
1231
1226
1232 -t: put timestamps before each input line logged (these are put in
1227 -t: put timestamps before each input line logged (these are put in
1233 comments)."""
1228 comments)."""
1234
1229
1235 opts,par = self.parse_options(parameter_s,'ort')
1230 opts,par = self.parse_options(parameter_s,'ort')
1236 log_output = 'o' in opts
1231 log_output = 'o' in opts
1237 log_raw_input = 'r' in opts
1232 log_raw_input = 'r' in opts
1238 timestamp = 't' in opts
1233 timestamp = 't' in opts
1239
1234
1240 logger = self.shell.logger
1235 logger = self.shell.logger
1241
1236
1242 # if no args are given, the defaults set in the logger constructor by
1237 # if no args are given, the defaults set in the logger constructor by
1243 # ipython remain valid
1238 # ipython remain valid
1244 if par:
1239 if par:
1245 try:
1240 try:
1246 logfname,logmode = par.split()
1241 logfname,logmode = par.split()
1247 except:
1242 except:
1248 logfname = par
1243 logfname = par
1249 logmode = 'backup'
1244 logmode = 'backup'
1250 else:
1245 else:
1251 logfname = logger.logfname
1246 logfname = logger.logfname
1252 logmode = logger.logmode
1247 logmode = logger.logmode
1253 # put logfname into rc struct as if it had been called on the command
1248 # put logfname into rc struct as if it had been called on the command
1254 # line, so it ends up saved in the log header Save it in case we need
1249 # line, so it ends up saved in the log header Save it in case we need
1255 # to restore it...
1250 # to restore it...
1256 old_logfile = self.shell.logfile
1251 old_logfile = self.shell.logfile
1257 if logfname:
1252 if logfname:
1258 logfname = os.path.expanduser(logfname)
1253 logfname = os.path.expanduser(logfname)
1259 self.shell.logfile = logfname
1254 self.shell.logfile = logfname
1260
1255
1261 loghead = '# IPython log file\n\n'
1256 loghead = '# IPython log file\n\n'
1262 try:
1257 try:
1263 started = logger.logstart(logfname,loghead,logmode,
1258 started = logger.logstart(logfname,loghead,logmode,
1264 log_output,timestamp,log_raw_input)
1259 log_output,timestamp,log_raw_input)
1265 except:
1260 except:
1266 self.shell.logfile = old_logfile
1261 self.shell.logfile = old_logfile
1267 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 warn("Couldn't start log: %s" % sys.exc_info()[1])
1268 else:
1263 else:
1269 # log input history up to this point, optionally interleaving
1264 # log input history up to this point, optionally interleaving
1270 # output if requested
1265 # output if requested
1271
1266
1272 if timestamp:
1267 if timestamp:
1273 # disable timestamping for the previous history, since we've
1268 # disable timestamping for the previous history, since we've
1274 # lost those already (no time machine here).
1269 # lost those already (no time machine here).
1275 logger.timestamp = False
1270 logger.timestamp = False
1276
1271
1277 if log_raw_input:
1272 if log_raw_input:
1278 input_hist = self.shell.history_manager.input_hist_raw
1273 input_hist = self.shell.history_manager.input_hist_raw
1279 else:
1274 else:
1280 input_hist = self.shell.history_manager.input_hist_parsed
1275 input_hist = self.shell.history_manager.input_hist_parsed
1281
1276
1282 if log_output:
1277 if log_output:
1283 log_write = logger.log_write
1278 log_write = logger.log_write
1284 output_hist = self.shell.history_manager.output_hist
1279 output_hist = self.shell.history_manager.output_hist
1285 for n in range(1,len(input_hist)-1):
1280 for n in range(1,len(input_hist)-1):
1286 log_write(input_hist[n].rstrip() + '\n')
1281 log_write(input_hist[n].rstrip() + '\n')
1287 if n in output_hist:
1282 if n in output_hist:
1288 log_write(repr(output_hist[n]),'output')
1283 log_write(repr(output_hist[n]),'output')
1289 else:
1284 else:
1290 logger.log_write('\n'.join(input_hist[1:]))
1285 logger.log_write('\n'.join(input_hist[1:]))
1291 logger.log_write('\n')
1286 logger.log_write('\n')
1292 if timestamp:
1287 if timestamp:
1293 # re-enable timestamping
1288 # re-enable timestamping
1294 logger.timestamp = True
1289 logger.timestamp = True
1295
1290
1296 print ('Activating auto-logging. '
1291 print ('Activating auto-logging. '
1297 'Current session state plus future input saved.')
1292 'Current session state plus future input saved.')
1298 logger.logstate()
1293 logger.logstate()
1299
1294
1300 def magic_logstop(self,parameter_s=''):
1295 def magic_logstop(self,parameter_s=''):
1301 """Fully stop logging and close log file.
1296 """Fully stop logging and close log file.
1302
1297
1303 In order to start logging again, a new %logstart call needs to be made,
1298 In order to start logging again, a new %logstart call needs to be made,
1304 possibly (though not necessarily) with a new filename, mode and other
1299 possibly (though not necessarily) with a new filename, mode and other
1305 options."""
1300 options."""
1306 self.logger.logstop()
1301 self.logger.logstop()
1307
1302
1308 def magic_logoff(self,parameter_s=''):
1303 def magic_logoff(self,parameter_s=''):
1309 """Temporarily stop logging.
1304 """Temporarily stop logging.
1310
1305
1311 You must have previously started logging."""
1306 You must have previously started logging."""
1312 self.shell.logger.switch_log(0)
1307 self.shell.logger.switch_log(0)
1313
1308
1314 def magic_logon(self,parameter_s=''):
1309 def magic_logon(self,parameter_s=''):
1315 """Restart logging.
1310 """Restart logging.
1316
1311
1317 This function is for restarting logging which you've temporarily
1312 This function is for restarting logging which you've temporarily
1318 stopped with %logoff. For starting logging for the first time, you
1313 stopped with %logoff. For starting logging for the first time, you
1319 must use the %logstart function, which allows you to specify an
1314 must use the %logstart function, which allows you to specify an
1320 optional log filename."""
1315 optional log filename."""
1321
1316
1322 self.shell.logger.switch_log(1)
1317 self.shell.logger.switch_log(1)
1323
1318
1324 def magic_logstate(self,parameter_s=''):
1319 def magic_logstate(self,parameter_s=''):
1325 """Print the status of the logging system."""
1320 """Print the status of the logging system."""
1326
1321
1327 self.shell.logger.logstate()
1322 self.shell.logger.logstate()
1328
1323
1329 def magic_pdb(self, parameter_s=''):
1324 def magic_pdb(self, parameter_s=''):
1330 """Control the automatic calling of the pdb interactive debugger.
1325 """Control the automatic calling of the pdb interactive debugger.
1331
1326
1332 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1327 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1333 argument it works as a toggle.
1328 argument it works as a toggle.
1334
1329
1335 When an exception is triggered, IPython can optionally call the
1330 When an exception is triggered, IPython can optionally call the
1336 interactive pdb debugger after the traceback printout. %pdb toggles
1331 interactive pdb debugger after the traceback printout. %pdb toggles
1337 this feature on and off.
1332 this feature on and off.
1338
1333
1339 The initial state of this feature is set in your configuration
1334 The initial state of this feature is set in your configuration
1340 file (the option is ``InteractiveShell.pdb``).
1335 file (the option is ``InteractiveShell.pdb``).
1341
1336
1342 If you want to just activate the debugger AFTER an exception has fired,
1337 If you want to just activate the debugger AFTER an exception has fired,
1343 without having to type '%pdb on' and rerunning your code, you can use
1338 without having to type '%pdb on' and rerunning your code, you can use
1344 the %debug magic."""
1339 the %debug magic."""
1345
1340
1346 par = parameter_s.strip().lower()
1341 par = parameter_s.strip().lower()
1347
1342
1348 if par:
1343 if par:
1349 try:
1344 try:
1350 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1345 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1351 except KeyError:
1346 except KeyError:
1352 print ('Incorrect argument. Use on/1, off/0, '
1347 print ('Incorrect argument. Use on/1, off/0, '
1353 'or nothing for a toggle.')
1348 'or nothing for a toggle.')
1354 return
1349 return
1355 else:
1350 else:
1356 # toggle
1351 # toggle
1357 new_pdb = not self.shell.call_pdb
1352 new_pdb = not self.shell.call_pdb
1358
1353
1359 # set on the shell
1354 # set on the shell
1360 self.shell.call_pdb = new_pdb
1355 self.shell.call_pdb = new_pdb
1361 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1356 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1362
1357
1363 def magic_debug(self, parameter_s=''):
1358 def magic_debug(self, parameter_s=''):
1364 """Activate the interactive debugger in post-mortem mode.
1359 """Activate the interactive debugger in post-mortem mode.
1365
1360
1366 If an exception has just occurred, this lets you inspect its stack
1361 If an exception has just occurred, this lets you inspect its stack
1367 frames interactively. Note that this will always work only on the last
1362 frames interactively. Note that this will always work only on the last
1368 traceback that occurred, so you must call this quickly after an
1363 traceback that occurred, so you must call this quickly after an
1369 exception that you wish to inspect has fired, because if another one
1364 exception that you wish to inspect has fired, because if another one
1370 occurs, it clobbers the previous one.
1365 occurs, it clobbers the previous one.
1371
1366
1372 If you want IPython to automatically do this on every exception, see
1367 If you want IPython to automatically do this on every exception, see
1373 the %pdb magic for more details.
1368 the %pdb magic for more details.
1374 """
1369 """
1375 self.shell.debugger(force=True)
1370 self.shell.debugger(force=True)
1376
1371
1377 @skip_doctest
1372 @skip_doctest
1378 def magic_prun(self, parameter_s ='',user_mode=1,
1373 def magic_prun(self, parameter_s ='',user_mode=1,
1379 opts=None,arg_lst=None,prog_ns=None):
1374 opts=None,arg_lst=None,prog_ns=None):
1380
1375
1381 """Run a statement through the python code profiler.
1376 """Run a statement through the python code profiler.
1382
1377
1383 Usage:
1378 Usage:
1384 %prun [options] statement
1379 %prun [options] statement
1385
1380
1386 The given statement (which doesn't require quote marks) is run via the
1381 The given statement (which doesn't require quote marks) is run via the
1387 python profiler in a manner similar to the profile.run() function.
1382 python profiler in a manner similar to the profile.run() function.
1388 Namespaces are internally managed to work correctly; profile.run
1383 Namespaces are internally managed to work correctly; profile.run
1389 cannot be used in IPython because it makes certain assumptions about
1384 cannot be used in IPython because it makes certain assumptions about
1390 namespaces which do not hold under IPython.
1385 namespaces which do not hold under IPython.
1391
1386
1392 Options:
1387 Options:
1393
1388
1394 -l <limit>: you can place restrictions on what or how much of the
1389 -l <limit>: you can place restrictions on what or how much of the
1395 profile gets printed. The limit value can be:
1390 profile gets printed. The limit value can be:
1396
1391
1397 * A string: only information for function names containing this string
1392 * A string: only information for function names containing this string
1398 is printed.
1393 is printed.
1399
1394
1400 * An integer: only these many lines are printed.
1395 * An integer: only these many lines are printed.
1401
1396
1402 * A float (between 0 and 1): this fraction of the report is printed
1397 * A float (between 0 and 1): this fraction of the report is printed
1403 (for example, use a limit of 0.4 to see the topmost 40% only).
1398 (for example, use a limit of 0.4 to see the topmost 40% only).
1404
1399
1405 You can combine several limits with repeated use of the option. For
1400 You can combine several limits with repeated use of the option. For
1406 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1401 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1407 information about class constructors.
1402 information about class constructors.
1408
1403
1409 -r: return the pstats.Stats object generated by the profiling. This
1404 -r: return the pstats.Stats object generated by the profiling. This
1410 object has all the information about the profile in it, and you can
1405 object has all the information about the profile in it, and you can
1411 later use it for further analysis or in other functions.
1406 later use it for further analysis or in other functions.
1412
1407
1413 -s <key>: sort profile by given key. You can provide more than one key
1408 -s <key>: sort profile by given key. You can provide more than one key
1414 by using the option several times: '-s key1 -s key2 -s key3...'. The
1409 by using the option several times: '-s key1 -s key2 -s key3...'. The
1415 default sorting key is 'time'.
1410 default sorting key is 'time'.
1416
1411
1417 The following is copied verbatim from the profile documentation
1412 The following is copied verbatim from the profile documentation
1418 referenced below:
1413 referenced below:
1419
1414
1420 When more than one key is provided, additional keys are used as
1415 When more than one key is provided, additional keys are used as
1421 secondary criteria when the there is equality in all keys selected
1416 secondary criteria when the there is equality in all keys selected
1422 before them.
1417 before them.
1423
1418
1424 Abbreviations can be used for any key names, as long as the
1419 Abbreviations can be used for any key names, as long as the
1425 abbreviation is unambiguous. The following are the keys currently
1420 abbreviation is unambiguous. The following are the keys currently
1426 defined:
1421 defined:
1427
1422
1428 Valid Arg Meaning
1423 Valid Arg Meaning
1429 "calls" call count
1424 "calls" call count
1430 "cumulative" cumulative time
1425 "cumulative" cumulative time
1431 "file" file name
1426 "file" file name
1432 "module" file name
1427 "module" file name
1433 "pcalls" primitive call count
1428 "pcalls" primitive call count
1434 "line" line number
1429 "line" line number
1435 "name" function name
1430 "name" function name
1436 "nfl" name/file/line
1431 "nfl" name/file/line
1437 "stdname" standard name
1432 "stdname" standard name
1438 "time" internal time
1433 "time" internal time
1439
1434
1440 Note that all sorts on statistics are in descending order (placing
1435 Note that all sorts on statistics are in descending order (placing
1441 most time consuming items first), where as name, file, and line number
1436 most time consuming items first), where as name, file, and line number
1442 searches are in ascending order (i.e., alphabetical). The subtle
1437 searches are in ascending order (i.e., alphabetical). The subtle
1443 distinction between "nfl" and "stdname" is that the standard name is a
1438 distinction between "nfl" and "stdname" is that the standard name is a
1444 sort of the name as printed, which means that the embedded line
1439 sort of the name as printed, which means that the embedded line
1445 numbers get compared in an odd way. For example, lines 3, 20, and 40
1440 numbers get compared in an odd way. For example, lines 3, 20, and 40
1446 would (if the file names were the same) appear in the string order
1441 would (if the file names were the same) appear in the string order
1447 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1442 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1448 line numbers. In fact, sort_stats("nfl") is the same as
1443 line numbers. In fact, sort_stats("nfl") is the same as
1449 sort_stats("name", "file", "line").
1444 sort_stats("name", "file", "line").
1450
1445
1451 -T <filename>: save profile results as shown on screen to a text
1446 -T <filename>: save profile results as shown on screen to a text
1452 file. The profile is still shown on screen.
1447 file. The profile is still shown on screen.
1453
1448
1454 -D <filename>: save (via dump_stats) profile statistics to given
1449 -D <filename>: save (via dump_stats) profile statistics to given
1455 filename. This data is in a format understood by the pstats module, and
1450 filename. This data is in a format understood by the pstats module, and
1456 is generated by a call to the dump_stats() method of profile
1451 is generated by a call to the dump_stats() method of profile
1457 objects. The profile is still shown on screen.
1452 objects. The profile is still shown on screen.
1458
1453
1459 -q: suppress output to the pager. Best used with -T and/or -D above.
1454 -q: suppress output to the pager. Best used with -T and/or -D above.
1460
1455
1461 If you want to run complete programs under the profiler's control, use
1456 If you want to run complete programs under the profiler's control, use
1462 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1457 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1463 contains profiler specific options as described here.
1458 contains profiler specific options as described here.
1464
1459
1465 You can read the complete documentation for the profile module with::
1460 You can read the complete documentation for the profile module with::
1466
1461
1467 In [1]: import profile; profile.help()
1462 In [1]: import profile; profile.help()
1468 """
1463 """
1469
1464
1470 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1465 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1471
1466
1472 if user_mode: # regular user call
1467 if user_mode: # regular user call
1473 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1468 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1474 list_all=1, posix=False)
1469 list_all=1, posix=False)
1475 namespace = self.shell.user_ns
1470 namespace = self.shell.user_ns
1476 else: # called to run a program by %run -p
1471 else: # called to run a program by %run -p
1477 try:
1472 try:
1478 filename = get_py_filename(arg_lst[0])
1473 filename = get_py_filename(arg_lst[0])
1479 except IOError as e:
1474 except IOError as e:
1480 try:
1475 try:
1481 msg = str(e)
1476 msg = str(e)
1482 except UnicodeError:
1477 except UnicodeError:
1483 msg = e.message
1478 msg = e.message
1484 error(msg)
1479 error(msg)
1485 return
1480 return
1486
1481
1487 arg_str = 'execfile(filename,prog_ns)'
1482 arg_str = 'execfile(filename,prog_ns)'
1488 namespace = {
1483 namespace = {
1489 'execfile': self.shell.safe_execfile,
1484 'execfile': self.shell.safe_execfile,
1490 'prog_ns': prog_ns,
1485 'prog_ns': prog_ns,
1491 'filename': filename
1486 'filename': filename
1492 }
1487 }
1493
1488
1494 opts.merge(opts_def)
1489 opts.merge(opts_def)
1495
1490
1496 prof = profile.Profile()
1491 prof = profile.Profile()
1497 try:
1492 try:
1498 prof = prof.runctx(arg_str,namespace,namespace)
1493 prof = prof.runctx(arg_str,namespace,namespace)
1499 sys_exit = ''
1494 sys_exit = ''
1500 except SystemExit:
1495 except SystemExit:
1501 sys_exit = """*** SystemExit exception caught in code being profiled."""
1496 sys_exit = """*** SystemExit exception caught in code being profiled."""
1502
1497
1503 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1498 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1504
1499
1505 lims = opts.l
1500 lims = opts.l
1506 if lims:
1501 if lims:
1507 lims = [] # rebuild lims with ints/floats/strings
1502 lims = [] # rebuild lims with ints/floats/strings
1508 for lim in opts.l:
1503 for lim in opts.l:
1509 try:
1504 try:
1510 lims.append(int(lim))
1505 lims.append(int(lim))
1511 except ValueError:
1506 except ValueError:
1512 try:
1507 try:
1513 lims.append(float(lim))
1508 lims.append(float(lim))
1514 except ValueError:
1509 except ValueError:
1515 lims.append(lim)
1510 lims.append(lim)
1516
1511
1517 # Trap output.
1512 # Trap output.
1518 stdout_trap = StringIO()
1513 stdout_trap = StringIO()
1519
1514
1520 if hasattr(stats,'stream'):
1515 if hasattr(stats,'stream'):
1521 # In newer versions of python, the stats object has a 'stream'
1516 # In newer versions of python, the stats object has a 'stream'
1522 # attribute to write into.
1517 # attribute to write into.
1523 stats.stream = stdout_trap
1518 stats.stream = stdout_trap
1524 stats.print_stats(*lims)
1519 stats.print_stats(*lims)
1525 else:
1520 else:
1526 # For older versions, we manually redirect stdout during printing
1521 # For older versions, we manually redirect stdout during printing
1527 sys_stdout = sys.stdout
1522 sys_stdout = sys.stdout
1528 try:
1523 try:
1529 sys.stdout = stdout_trap
1524 sys.stdout = stdout_trap
1530 stats.print_stats(*lims)
1525 stats.print_stats(*lims)
1531 finally:
1526 finally:
1532 sys.stdout = sys_stdout
1527 sys.stdout = sys_stdout
1533
1528
1534 output = stdout_trap.getvalue()
1529 output = stdout_trap.getvalue()
1535 output = output.rstrip()
1530 output = output.rstrip()
1536
1531
1537 if 'q' not in opts:
1532 if 'q' not in opts:
1538 page.page(output)
1533 page.page(output)
1539 print sys_exit,
1534 print sys_exit,
1540
1535
1541 dump_file = opts.D[0]
1536 dump_file = opts.D[0]
1542 text_file = opts.T[0]
1537 text_file = opts.T[0]
1543 if dump_file:
1538 if dump_file:
1544 dump_file = unquote_filename(dump_file)
1539 dump_file = unquote_filename(dump_file)
1545 prof.dump_stats(dump_file)
1540 prof.dump_stats(dump_file)
1546 print '\n*** Profile stats marshalled to file',\
1541 print '\n*** Profile stats marshalled to file',\
1547 `dump_file`+'.',sys_exit
1542 `dump_file`+'.',sys_exit
1548 if text_file:
1543 if text_file:
1549 text_file = unquote_filename(text_file)
1544 text_file = unquote_filename(text_file)
1550 pfile = file(text_file,'w')
1545 pfile = file(text_file,'w')
1551 pfile.write(output)
1546 pfile.write(output)
1552 pfile.close()
1547 pfile.close()
1553 print '\n*** Profile printout saved to text file',\
1548 print '\n*** Profile printout saved to text file',\
1554 `text_file`+'.',sys_exit
1549 `text_file`+'.',sys_exit
1555
1550
1556 if opts.has_key('r'):
1551 if opts.has_key('r'):
1557 return stats
1552 return stats
1558 else:
1553 else:
1559 return None
1554 return None
1560
1555
1561 @skip_doctest
1556 @skip_doctest
1562 def magic_run(self, parameter_s ='', runner=None,
1557 def magic_run(self, parameter_s ='', runner=None,
1563 file_finder=get_py_filename):
1558 file_finder=get_py_filename):
1564 """Run the named file inside IPython as a program.
1559 """Run the named file inside IPython as a program.
1565
1560
1566 Usage:\\
1561 Usage:\\
1567 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1562 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1568
1563
1569 Parameters after the filename are passed as command-line arguments to
1564 Parameters after the filename are passed as command-line arguments to
1570 the program (put in sys.argv). Then, control returns to IPython's
1565 the program (put in sys.argv). Then, control returns to IPython's
1571 prompt.
1566 prompt.
1572
1567
1573 This is similar to running at a system prompt:\\
1568 This is similar to running at a system prompt:\\
1574 $ python file args\\
1569 $ python file args\\
1575 but with the advantage of giving you IPython's tracebacks, and of
1570 but with the advantage of giving you IPython's tracebacks, and of
1576 loading all variables into your interactive namespace for further use
1571 loading all variables into your interactive namespace for further use
1577 (unless -p is used, see below).
1572 (unless -p is used, see below).
1578
1573
1579 The file is executed in a namespace initially consisting only of
1574 The file is executed in a namespace initially consisting only of
1580 __name__=='__main__' and sys.argv constructed as indicated. It thus
1575 __name__=='__main__' and sys.argv constructed as indicated. It thus
1581 sees its environment as if it were being run as a stand-alone program
1576 sees its environment as if it were being run as a stand-alone program
1582 (except for sharing global objects such as previously imported
1577 (except for sharing global objects such as previously imported
1583 modules). But after execution, the IPython interactive namespace gets
1578 modules). But after execution, the IPython interactive namespace gets
1584 updated with all variables defined in the program (except for __name__
1579 updated with all variables defined in the program (except for __name__
1585 and sys.argv). This allows for very convenient loading of code for
1580 and sys.argv). This allows for very convenient loading of code for
1586 interactive work, while giving each program a 'clean sheet' to run in.
1581 interactive work, while giving each program a 'clean sheet' to run in.
1587
1582
1588 Options:
1583 Options:
1589
1584
1590 -n: __name__ is NOT set to '__main__', but to the running file's name
1585 -n: __name__ is NOT set to '__main__', but to the running file's name
1591 without extension (as python does under import). This allows running
1586 without extension (as python does under import). This allows running
1592 scripts and reloading the definitions in them without calling code
1587 scripts and reloading the definitions in them without calling code
1593 protected by an ' if __name__ == "__main__" ' clause.
1588 protected by an ' if __name__ == "__main__" ' clause.
1594
1589
1595 -i: run the file in IPython's namespace instead of an empty one. This
1590 -i: run the file in IPython's namespace instead of an empty one. This
1596 is useful if you are experimenting with code written in a text editor
1591 is useful if you are experimenting with code written in a text editor
1597 which depends on variables defined interactively.
1592 which depends on variables defined interactively.
1598
1593
1599 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1594 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1600 being run. This is particularly useful if IPython is being used to
1595 being run. This is particularly useful if IPython is being used to
1601 run unittests, which always exit with a sys.exit() call. In such
1596 run unittests, which always exit with a sys.exit() call. In such
1602 cases you are interested in the output of the test results, not in
1597 cases you are interested in the output of the test results, not in
1603 seeing a traceback of the unittest module.
1598 seeing a traceback of the unittest module.
1604
1599
1605 -t: print timing information at the end of the run. IPython will give
1600 -t: print timing information at the end of the run. IPython will give
1606 you an estimated CPU time consumption for your script, which under
1601 you an estimated CPU time consumption for your script, which under
1607 Unix uses the resource module to avoid the wraparound problems of
1602 Unix uses the resource module to avoid the wraparound problems of
1608 time.clock(). Under Unix, an estimate of time spent on system tasks
1603 time.clock(). Under Unix, an estimate of time spent on system tasks
1609 is also given (for Windows platforms this is reported as 0.0).
1604 is also given (for Windows platforms this is reported as 0.0).
1610
1605
1611 If -t is given, an additional -N<N> option can be given, where <N>
1606 If -t is given, an additional -N<N> option can be given, where <N>
1612 must be an integer indicating how many times you want the script to
1607 must be an integer indicating how many times you want the script to
1613 run. The final timing report will include total and per run results.
1608 run. The final timing report will include total and per run results.
1614
1609
1615 For example (testing the script uniq_stable.py)::
1610 For example (testing the script uniq_stable.py)::
1616
1611
1617 In [1]: run -t uniq_stable
1612 In [1]: run -t uniq_stable
1618
1613
1619 IPython CPU timings (estimated):\\
1614 IPython CPU timings (estimated):\\
1620 User : 0.19597 s.\\
1615 User : 0.19597 s.\\
1621 System: 0.0 s.\\
1616 System: 0.0 s.\\
1622
1617
1623 In [2]: run -t -N5 uniq_stable
1618 In [2]: run -t -N5 uniq_stable
1624
1619
1625 IPython CPU timings (estimated):\\
1620 IPython CPU timings (estimated):\\
1626 Total runs performed: 5\\
1621 Total runs performed: 5\\
1627 Times : Total Per run\\
1622 Times : Total Per run\\
1628 User : 0.910862 s, 0.1821724 s.\\
1623 User : 0.910862 s, 0.1821724 s.\\
1629 System: 0.0 s, 0.0 s.
1624 System: 0.0 s, 0.0 s.
1630
1625
1631 -d: run your program under the control of pdb, the Python debugger.
1626 -d: run your program under the control of pdb, the Python debugger.
1632 This allows you to execute your program step by step, watch variables,
1627 This allows you to execute your program step by step, watch variables,
1633 etc. Internally, what IPython does is similar to calling:
1628 etc. Internally, what IPython does is similar to calling:
1634
1629
1635 pdb.run('execfile("YOURFILENAME")')
1630 pdb.run('execfile("YOURFILENAME")')
1636
1631
1637 with a breakpoint set on line 1 of your file. You can change the line
1632 with a breakpoint set on line 1 of your file. You can change the line
1638 number for this automatic breakpoint to be <N> by using the -bN option
1633 number for this automatic breakpoint to be <N> by using the -bN option
1639 (where N must be an integer). For example::
1634 (where N must be an integer). For example::
1640
1635
1641 %run -d -b40 myscript
1636 %run -d -b40 myscript
1642
1637
1643 will set the first breakpoint at line 40 in myscript.py. Note that
1638 will set the first breakpoint at line 40 in myscript.py. Note that
1644 the first breakpoint must be set on a line which actually does
1639 the first breakpoint must be set on a line which actually does
1645 something (not a comment or docstring) for it to stop execution.
1640 something (not a comment or docstring) for it to stop execution.
1646
1641
1647 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1642 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1648 first enter 'c' (without quotes) to start execution up to the first
1643 first enter 'c' (without quotes) to start execution up to the first
1649 breakpoint.
1644 breakpoint.
1650
1645
1651 Entering 'help' gives information about the use of the debugger. You
1646 Entering 'help' gives information about the use of the debugger. You
1652 can easily see pdb's full documentation with "import pdb;pdb.help()"
1647 can easily see pdb's full documentation with "import pdb;pdb.help()"
1653 at a prompt.
1648 at a prompt.
1654
1649
1655 -p: run program under the control of the Python profiler module (which
1650 -p: run program under the control of the Python profiler module (which
1656 prints a detailed report of execution times, function calls, etc).
1651 prints a detailed report of execution times, function calls, etc).
1657
1652
1658 You can pass other options after -p which affect the behavior of the
1653 You can pass other options after -p which affect the behavior of the
1659 profiler itself. See the docs for %prun for details.
1654 profiler itself. See the docs for %prun for details.
1660
1655
1661 In this mode, the program's variables do NOT propagate back to the
1656 In this mode, the program's variables do NOT propagate back to the
1662 IPython interactive namespace (because they remain in the namespace
1657 IPython interactive namespace (because they remain in the namespace
1663 where the profiler executes them).
1658 where the profiler executes them).
1664
1659
1665 Internally this triggers a call to %prun, see its documentation for
1660 Internally this triggers a call to %prun, see its documentation for
1666 details on the options available specifically for profiling.
1661 details on the options available specifically for profiling.
1667
1662
1668 There is one special usage for which the text above doesn't apply:
1663 There is one special usage for which the text above doesn't apply:
1669 if the filename ends with .ipy, the file is run as ipython script,
1664 if the filename ends with .ipy, the file is run as ipython script,
1670 just as if the commands were written on IPython prompt.
1665 just as if the commands were written on IPython prompt.
1671
1666
1672 -m: specify module name to load instead of script path. Similar to
1667 -m: specify module name to load instead of script path. Similar to
1673 the -m option for the python interpreter. Use this option last if you
1668 the -m option for the python interpreter. Use this option last if you
1674 want to combine with other %run options. Unlike the python interpreter
1669 want to combine with other %run options. Unlike the python interpreter
1675 only source modules are allowed no .pyc or .pyo files.
1670 only source modules are allowed no .pyc or .pyo files.
1676 For example::
1671 For example::
1677
1672
1678 %run -m example
1673 %run -m example
1679
1674
1680 will run the example module.
1675 will run the example module.
1681
1676
1682 """
1677 """
1683
1678
1684 # get arguments and set sys.argv for program to be run.
1679 # get arguments and set sys.argv for program to be run.
1685 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1680 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1686 mode='list', list_all=1)
1681 mode='list', list_all=1)
1687 if "m" in opts:
1682 if "m" in opts:
1688 modulename = opts["m"][0]
1683 modulename = opts["m"][0]
1689 modpath = find_mod(modulename)
1684 modpath = find_mod(modulename)
1690 if modpath is None:
1685 if modpath is None:
1691 warn('%r is not a valid modulename on sys.path'%modulename)
1686 warn('%r is not a valid modulename on sys.path'%modulename)
1692 return
1687 return
1693 arg_lst = [modpath] + arg_lst
1688 arg_lst = [modpath] + arg_lst
1694 try:
1689 try:
1695 filename = file_finder(arg_lst[0])
1690 filename = file_finder(arg_lst[0])
1696 except IndexError:
1691 except IndexError:
1697 warn('you must provide at least a filename.')
1692 warn('you must provide at least a filename.')
1698 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1693 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1699 return
1694 return
1700 except IOError as e:
1695 except IOError as e:
1701 try:
1696 try:
1702 msg = str(e)
1697 msg = str(e)
1703 except UnicodeError:
1698 except UnicodeError:
1704 msg = e.message
1699 msg = e.message
1705 error(msg)
1700 error(msg)
1706 return
1701 return
1707
1702
1708 if filename.lower().endswith('.ipy'):
1703 if filename.lower().endswith('.ipy'):
1709 self.shell.safe_execfile_ipy(filename)
1704 self.shell.safe_execfile_ipy(filename)
1710 return
1705 return
1711
1706
1712 # Control the response to exit() calls made by the script being run
1707 # Control the response to exit() calls made by the script being run
1713 exit_ignore = 'e' in opts
1708 exit_ignore = 'e' in opts
1714
1709
1715 # Make sure that the running script gets a proper sys.argv as if it
1710 # Make sure that the running script gets a proper sys.argv as if it
1716 # were run from a system shell.
1711 # were run from a system shell.
1717 save_argv = sys.argv # save it for later restoring
1712 save_argv = sys.argv # save it for later restoring
1718
1713
1719 # simulate shell expansion on arguments, at least tilde expansion
1714 # simulate shell expansion on arguments, at least tilde expansion
1720 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1715 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1721
1716
1722 sys.argv = [filename] + args # put in the proper filename
1717 sys.argv = [filename] + args # put in the proper filename
1723 # protect sys.argv from potential unicode strings on Python 2:
1718 # protect sys.argv from potential unicode strings on Python 2:
1724 if not py3compat.PY3:
1719 if not py3compat.PY3:
1725 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1720 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1726
1721
1727 if 'i' in opts:
1722 if 'i' in opts:
1728 # Run in user's interactive namespace
1723 # Run in user's interactive namespace
1729 prog_ns = self.shell.user_ns
1724 prog_ns = self.shell.user_ns
1730 __name__save = self.shell.user_ns['__name__']
1725 __name__save = self.shell.user_ns['__name__']
1731 prog_ns['__name__'] = '__main__'
1726 prog_ns['__name__'] = '__main__'
1732 main_mod = self.shell.new_main_mod(prog_ns)
1727 main_mod = self.shell.new_main_mod(prog_ns)
1733 else:
1728 else:
1734 # Run in a fresh, empty namespace
1729 # Run in a fresh, empty namespace
1735 if 'n' in opts:
1730 if 'n' in opts:
1736 name = os.path.splitext(os.path.basename(filename))[0]
1731 name = os.path.splitext(os.path.basename(filename))[0]
1737 else:
1732 else:
1738 name = '__main__'
1733 name = '__main__'
1739
1734
1740 main_mod = self.shell.new_main_mod()
1735 main_mod = self.shell.new_main_mod()
1741 prog_ns = main_mod.__dict__
1736 prog_ns = main_mod.__dict__
1742 prog_ns['__name__'] = name
1737 prog_ns['__name__'] = name
1743
1738
1744 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1739 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1745 # set the __file__ global in the script's namespace
1740 # set the __file__ global in the script's namespace
1746 prog_ns['__file__'] = filename
1741 prog_ns['__file__'] = filename
1747
1742
1748 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1743 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1749 # that, if we overwrite __main__, we replace it at the end
1744 # that, if we overwrite __main__, we replace it at the end
1750 main_mod_name = prog_ns['__name__']
1745 main_mod_name = prog_ns['__name__']
1751
1746
1752 if main_mod_name == '__main__':
1747 if main_mod_name == '__main__':
1753 restore_main = sys.modules['__main__']
1748 restore_main = sys.modules['__main__']
1754 else:
1749 else:
1755 restore_main = False
1750 restore_main = False
1756
1751
1757 # This needs to be undone at the end to prevent holding references to
1752 # This needs to be undone at the end to prevent holding references to
1758 # every single object ever created.
1753 # every single object ever created.
1759 sys.modules[main_mod_name] = main_mod
1754 sys.modules[main_mod_name] = main_mod
1760
1755
1761 try:
1756 try:
1762 stats = None
1757 stats = None
1763 with self.readline_no_record:
1758 with self.readline_no_record:
1764 if 'p' in opts:
1759 if 'p' in opts:
1765 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1760 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1766 else:
1761 else:
1767 if 'd' in opts:
1762 if 'd' in opts:
1768 deb = debugger.Pdb(self.shell.colors)
1763 deb = debugger.Pdb(self.shell.colors)
1769 # reset Breakpoint state, which is moronically kept
1764 # reset Breakpoint state, which is moronically kept
1770 # in a class
1765 # in a class
1771 bdb.Breakpoint.next = 1
1766 bdb.Breakpoint.next = 1
1772 bdb.Breakpoint.bplist = {}
1767 bdb.Breakpoint.bplist = {}
1773 bdb.Breakpoint.bpbynumber = [None]
1768 bdb.Breakpoint.bpbynumber = [None]
1774 # Set an initial breakpoint to stop execution
1769 # Set an initial breakpoint to stop execution
1775 maxtries = 10
1770 maxtries = 10
1776 bp = int(opts.get('b', [1])[0])
1771 bp = int(opts.get('b', [1])[0])
1777 checkline = deb.checkline(filename, bp)
1772 checkline = deb.checkline(filename, bp)
1778 if not checkline:
1773 if not checkline:
1779 for bp in range(bp + 1, bp + maxtries + 1):
1774 for bp in range(bp + 1, bp + maxtries + 1):
1780 if deb.checkline(filename, bp):
1775 if deb.checkline(filename, bp):
1781 break
1776 break
1782 else:
1777 else:
1783 msg = ("\nI failed to find a valid line to set "
1778 msg = ("\nI failed to find a valid line to set "
1784 "a breakpoint\n"
1779 "a breakpoint\n"
1785 "after trying up to line: %s.\n"
1780 "after trying up to line: %s.\n"
1786 "Please set a valid breakpoint manually "
1781 "Please set a valid breakpoint manually "
1787 "with the -b option." % bp)
1782 "with the -b option." % bp)
1788 error(msg)
1783 error(msg)
1789 return
1784 return
1790 # if we find a good linenumber, set the breakpoint
1785 # if we find a good linenumber, set the breakpoint
1791 deb.do_break('%s:%s' % (filename, bp))
1786 deb.do_break('%s:%s' % (filename, bp))
1792 # Start file run
1787 # Start file run
1793 print "NOTE: Enter 'c' at the",
1788 print "NOTE: Enter 'c' at the",
1794 print "%s prompt to start your script." % deb.prompt
1789 print "%s prompt to start your script." % deb.prompt
1795 try:
1790 try:
1796 deb.run('execfile("%s")' % filename, prog_ns)
1791 deb.run('execfile("%s")' % filename, prog_ns)
1797
1792
1798 except:
1793 except:
1799 etype, value, tb = sys.exc_info()
1794 etype, value, tb = sys.exc_info()
1800 # Skip three frames in the traceback: the %run one,
1795 # Skip three frames in the traceback: the %run one,
1801 # one inside bdb.py, and the command-line typed by the
1796 # one inside bdb.py, and the command-line typed by the
1802 # user (run by exec in pdb itself).
1797 # user (run by exec in pdb itself).
1803 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1798 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1804 else:
1799 else:
1805 if runner is None:
1800 if runner is None:
1806 runner = self.shell.safe_execfile
1801 runner = self.shell.safe_execfile
1807 if 't' in opts:
1802 if 't' in opts:
1808 # timed execution
1803 # timed execution
1809 try:
1804 try:
1810 nruns = int(opts['N'][0])
1805 nruns = int(opts['N'][0])
1811 if nruns < 1:
1806 if nruns < 1:
1812 error('Number of runs must be >=1')
1807 error('Number of runs must be >=1')
1813 return
1808 return
1814 except (KeyError):
1809 except (KeyError):
1815 nruns = 1
1810 nruns = 1
1816 twall0 = time.time()
1811 twall0 = time.time()
1817 if nruns == 1:
1812 if nruns == 1:
1818 t0 = clock2()
1813 t0 = clock2()
1819 runner(filename, prog_ns, prog_ns,
1814 runner(filename, prog_ns, prog_ns,
1820 exit_ignore=exit_ignore)
1815 exit_ignore=exit_ignore)
1821 t1 = clock2()
1816 t1 = clock2()
1822 t_usr = t1[0] - t0[0]
1817 t_usr = t1[0] - t0[0]
1823 t_sys = t1[1] - t0[1]
1818 t_sys = t1[1] - t0[1]
1824 print "\nIPython CPU timings (estimated):"
1819 print "\nIPython CPU timings (estimated):"
1825 print " User : %10.2f s." % t_usr
1820 print " User : %10.2f s." % t_usr
1826 print " System : %10.2f s." % t_sys
1821 print " System : %10.2f s." % t_sys
1827 else:
1822 else:
1828 runs = range(nruns)
1823 runs = range(nruns)
1829 t0 = clock2()
1824 t0 = clock2()
1830 for nr in runs:
1825 for nr in runs:
1831 runner(filename, prog_ns, prog_ns,
1826 runner(filename, prog_ns, prog_ns,
1832 exit_ignore=exit_ignore)
1827 exit_ignore=exit_ignore)
1833 t1 = clock2()
1828 t1 = clock2()
1834 t_usr = t1[0] - t0[0]
1829 t_usr = t1[0] - t0[0]
1835 t_sys = t1[1] - t0[1]
1830 t_sys = t1[1] - t0[1]
1836 print "\nIPython CPU timings (estimated):"
1831 print "\nIPython CPU timings (estimated):"
1837 print "Total runs performed:", nruns
1832 print "Total runs performed:", nruns
1838 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1833 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1839 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1834 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1840 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1835 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1841 twall1 = time.time()
1836 twall1 = time.time()
1842 print "Wall time: %10.2f s." % (twall1 - twall0)
1837 print "Wall time: %10.2f s." % (twall1 - twall0)
1843
1838
1844 else:
1839 else:
1845 # regular execution
1840 # regular execution
1846 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1841 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1847
1842
1848 if 'i' in opts:
1843 if 'i' in opts:
1849 self.shell.user_ns['__name__'] = __name__save
1844 self.shell.user_ns['__name__'] = __name__save
1850 else:
1845 else:
1851 # The shell MUST hold a reference to prog_ns so after %run
1846 # The shell MUST hold a reference to prog_ns so after %run
1852 # exits, the python deletion mechanism doesn't zero it out
1847 # exits, the python deletion mechanism doesn't zero it out
1853 # (leaving dangling references).
1848 # (leaving dangling references).
1854 self.shell.cache_main_mod(prog_ns, filename)
1849 self.shell.cache_main_mod(prog_ns, filename)
1855 # update IPython interactive namespace
1850 # update IPython interactive namespace
1856
1851
1857 # Some forms of read errors on the file may mean the
1852 # Some forms of read errors on the file may mean the
1858 # __name__ key was never set; using pop we don't have to
1853 # __name__ key was never set; using pop we don't have to
1859 # worry about a possible KeyError.
1854 # worry about a possible KeyError.
1860 prog_ns.pop('__name__', None)
1855 prog_ns.pop('__name__', None)
1861
1856
1862 self.shell.user_ns.update(prog_ns)
1857 self.shell.user_ns.update(prog_ns)
1863 finally:
1858 finally:
1864 # It's a bit of a mystery why, but __builtins__ can change from
1859 # It's a bit of a mystery why, but __builtins__ can change from
1865 # being a module to becoming a dict missing some key data after
1860 # being a module to becoming a dict missing some key data after
1866 # %run. As best I can see, this is NOT something IPython is doing
1861 # %run. As best I can see, this is NOT something IPython is doing
1867 # at all, and similar problems have been reported before:
1862 # at all, and similar problems have been reported before:
1868 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1863 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1869 # Since this seems to be done by the interpreter itself, the best
1864 # Since this seems to be done by the interpreter itself, the best
1870 # we can do is to at least restore __builtins__ for the user on
1865 # we can do is to at least restore __builtins__ for the user on
1871 # exit.
1866 # exit.
1872 self.shell.user_ns['__builtins__'] = builtin_mod
1867 self.shell.user_ns['__builtins__'] = builtin_mod
1873
1868
1874 # Ensure key global structures are restored
1869 # Ensure key global structures are restored
1875 sys.argv = save_argv
1870 sys.argv = save_argv
1876 if restore_main:
1871 if restore_main:
1877 sys.modules['__main__'] = restore_main
1872 sys.modules['__main__'] = restore_main
1878 else:
1873 else:
1879 # Remove from sys.modules the reference to main_mod we'd
1874 # Remove from sys.modules the reference to main_mod we'd
1880 # added. Otherwise it will trap references to objects
1875 # added. Otherwise it will trap references to objects
1881 # contained therein.
1876 # contained therein.
1882 del sys.modules[main_mod_name]
1877 del sys.modules[main_mod_name]
1883
1878
1884 return stats
1879 return stats
1885
1880
1886 @skip_doctest
1881 @skip_doctest
1887 def magic_timeit(self, parameter_s =''):
1882 def magic_timeit(self, parameter_s =''):
1888 """Time execution of a Python statement or expression
1883 """Time execution of a Python statement or expression
1889
1884
1890 Usage:\\
1885 Usage:\\
1891 %timeit [-n<N> -r<R> [-t|-c]] statement
1886 %timeit [-n<N> -r<R> [-t|-c]] statement
1892
1887
1893 Time execution of a Python statement or expression using the timeit
1888 Time execution of a Python statement or expression using the timeit
1894 module.
1889 module.
1895
1890
1896 Options:
1891 Options:
1897 -n<N>: execute the given statement <N> times in a loop. If this value
1892 -n<N>: execute the given statement <N> times in a loop. If this value
1898 is not given, a fitting value is chosen.
1893 is not given, a fitting value is chosen.
1899
1894
1900 -r<R>: repeat the loop iteration <R> times and take the best result.
1895 -r<R>: repeat the loop iteration <R> times and take the best result.
1901 Default: 3
1896 Default: 3
1902
1897
1903 -t: use time.time to measure the time, which is the default on Unix.
1898 -t: use time.time to measure the time, which is the default on Unix.
1904 This function measures wall time.
1899 This function measures wall time.
1905
1900
1906 -c: use time.clock to measure the time, which is the default on
1901 -c: use time.clock to measure the time, which is the default on
1907 Windows and measures wall time. On Unix, resource.getrusage is used
1902 Windows and measures wall time. On Unix, resource.getrusage is used
1908 instead and returns the CPU user time.
1903 instead and returns the CPU user time.
1909
1904
1910 -p<P>: use a precision of <P> digits to display the timing result.
1905 -p<P>: use a precision of <P> digits to display the timing result.
1911 Default: 3
1906 Default: 3
1912
1907
1913
1908
1914 Examples
1909 Examples
1915 --------
1910 --------
1916 ::
1911 ::
1917
1912
1918 In [1]: %timeit pass
1913 In [1]: %timeit pass
1919 10000000 loops, best of 3: 53.3 ns per loop
1914 10000000 loops, best of 3: 53.3 ns per loop
1920
1915
1921 In [2]: u = None
1916 In [2]: u = None
1922
1917
1923 In [3]: %timeit u is None
1918 In [3]: %timeit u is None
1924 10000000 loops, best of 3: 184 ns per loop
1919 10000000 loops, best of 3: 184 ns per loop
1925
1920
1926 In [4]: %timeit -r 4 u == None
1921 In [4]: %timeit -r 4 u == None
1927 1000000 loops, best of 4: 242 ns per loop
1922 1000000 loops, best of 4: 242 ns per loop
1928
1923
1929 In [5]: import time
1924 In [5]: import time
1930
1925
1931 In [6]: %timeit -n1 time.sleep(2)
1926 In [6]: %timeit -n1 time.sleep(2)
1932 1 loops, best of 3: 2 s per loop
1927 1 loops, best of 3: 2 s per loop
1933
1928
1934
1929
1935 The times reported by %timeit will be slightly higher than those
1930 The times reported by %timeit will be slightly higher than those
1936 reported by the timeit.py script when variables are accessed. This is
1931 reported by the timeit.py script when variables are accessed. This is
1937 due to the fact that %timeit executes the statement in the namespace
1932 due to the fact that %timeit executes the statement in the namespace
1938 of the shell, compared with timeit.py, which uses a single setup
1933 of the shell, compared with timeit.py, which uses a single setup
1939 statement to import function or create variables. Generally, the bias
1934 statement to import function or create variables. Generally, the bias
1940 does not matter as long as results from timeit.py are not mixed with
1935 does not matter as long as results from timeit.py are not mixed with
1941 those from %timeit."""
1936 those from %timeit."""
1942
1937
1943 import timeit
1938 import timeit
1944 import math
1939 import math
1945
1940
1946 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1941 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1947 # certain terminals. Until we figure out a robust way of
1942 # certain terminals. Until we figure out a robust way of
1948 # auto-detecting if the terminal can deal with it, use plain 'us' for
1943 # auto-detecting if the terminal can deal with it, use plain 'us' for
1949 # microseconds. I am really NOT happy about disabling the proper
1944 # microseconds. I am really NOT happy about disabling the proper
1950 # 'micro' prefix, but crashing is worse... If anyone knows what the
1945 # 'micro' prefix, but crashing is worse... If anyone knows what the
1951 # right solution for this is, I'm all ears...
1946 # right solution for this is, I'm all ears...
1952 #
1947 #
1953 # Note: using
1948 # Note: using
1954 #
1949 #
1955 # s = u'\xb5'
1950 # s = u'\xb5'
1956 # s.encode(sys.getdefaultencoding())
1951 # s.encode(sys.getdefaultencoding())
1957 #
1952 #
1958 # is not sufficient, as I've seen terminals where that fails but
1953 # is not sufficient, as I've seen terminals where that fails but
1959 # print s
1954 # print s
1960 #
1955 #
1961 # succeeds
1956 # succeeds
1962 #
1957 #
1963 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1958 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1964
1959
1965 #units = [u"s", u"ms",u'\xb5',"ns"]
1960 #units = [u"s", u"ms",u'\xb5',"ns"]
1966 units = [u"s", u"ms",u'us',"ns"]
1961 units = [u"s", u"ms",u'us',"ns"]
1967
1962
1968 scaling = [1, 1e3, 1e6, 1e9]
1963 scaling = [1, 1e3, 1e6, 1e9]
1969
1964
1970 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1965 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1971 posix=False, strict=False)
1966 posix=False, strict=False)
1972 if stmt == "":
1967 if stmt == "":
1973 return
1968 return
1974 timefunc = timeit.default_timer
1969 timefunc = timeit.default_timer
1975 number = int(getattr(opts, "n", 0))
1970 number = int(getattr(opts, "n", 0))
1976 repeat = int(getattr(opts, "r", timeit.default_repeat))
1971 repeat = int(getattr(opts, "r", timeit.default_repeat))
1977 precision = int(getattr(opts, "p", 3))
1972 precision = int(getattr(opts, "p", 3))
1978 if hasattr(opts, "t"):
1973 if hasattr(opts, "t"):
1979 timefunc = time.time
1974 timefunc = time.time
1980 if hasattr(opts, "c"):
1975 if hasattr(opts, "c"):
1981 timefunc = clock
1976 timefunc = clock
1982
1977
1983 timer = timeit.Timer(timer=timefunc)
1978 timer = timeit.Timer(timer=timefunc)
1984 # this code has tight coupling to the inner workings of timeit.Timer,
1979 # this code has tight coupling to the inner workings of timeit.Timer,
1985 # but is there a better way to achieve that the code stmt has access
1980 # but is there a better way to achieve that the code stmt has access
1986 # to the shell namespace?
1981 # to the shell namespace?
1987
1982
1988 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1983 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1989 'setup': "pass"}
1984 'setup': "pass"}
1990 # Track compilation time so it can be reported if too long
1985 # Track compilation time so it can be reported if too long
1991 # Minimum time above which compilation time will be reported
1986 # Minimum time above which compilation time will be reported
1992 tc_min = 0.1
1987 tc_min = 0.1
1993
1988
1994 t0 = clock()
1989 t0 = clock()
1995 code = compile(src, "<magic-timeit>", "exec")
1990 code = compile(src, "<magic-timeit>", "exec")
1996 tc = clock()-t0
1991 tc = clock()-t0
1997
1992
1998 ns = {}
1993 ns = {}
1999 exec code in self.shell.user_ns, ns
1994 exec code in self.shell.user_ns, ns
2000 timer.inner = ns["inner"]
1995 timer.inner = ns["inner"]
2001
1996
2002 if number == 0:
1997 if number == 0:
2003 # determine number so that 0.2 <= total time < 2.0
1998 # determine number so that 0.2 <= total time < 2.0
2004 number = 1
1999 number = 1
2005 for i in range(1, 10):
2000 for i in range(1, 10):
2006 if timer.timeit(number) >= 0.2:
2001 if timer.timeit(number) >= 0.2:
2007 break
2002 break
2008 number *= 10
2003 number *= 10
2009
2004
2010 best = min(timer.repeat(repeat, number)) / number
2005 best = min(timer.repeat(repeat, number)) / number
2011
2006
2012 if best > 0.0 and best < 1000.0:
2007 if best > 0.0 and best < 1000.0:
2013 order = min(-int(math.floor(math.log10(best)) // 3), 3)
2008 order = min(-int(math.floor(math.log10(best)) // 3), 3)
2014 elif best >= 1000.0:
2009 elif best >= 1000.0:
2015 order = 0
2010 order = 0
2016 else:
2011 else:
2017 order = 3
2012 order = 3
2018 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
2013 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
2019 precision,
2014 precision,
2020 best * scaling[order],
2015 best * scaling[order],
2021 units[order])
2016 units[order])
2022 if tc > tc_min:
2017 if tc > tc_min:
2023 print "Compiler time: %.2f s" % tc
2018 print "Compiler time: %.2f s" % tc
2024
2019
2025 @skip_doctest
2020 @skip_doctest
2026 @needs_local_scope
2021 @needs_local_scope
2027 def magic_time(self,parameter_s = ''):
2022 def magic_time(self,parameter_s = ''):
2028 """Time execution of a Python statement or expression.
2023 """Time execution of a Python statement or expression.
2029
2024
2030 The CPU and wall clock times are printed, and the value of the
2025 The CPU and wall clock times are printed, and the value of the
2031 expression (if any) is returned. Note that under Win32, system time
2026 expression (if any) is returned. Note that under Win32, system time
2032 is always reported as 0, since it can not be measured.
2027 is always reported as 0, since it can not be measured.
2033
2028
2034 This function provides very basic timing functionality. In Python
2029 This function provides very basic timing functionality. In Python
2035 2.3, the timeit module offers more control and sophistication, so this
2030 2.3, the timeit module offers more control and sophistication, so this
2036 could be rewritten to use it (patches welcome).
2031 could be rewritten to use it (patches welcome).
2037
2032
2038 Examples
2033 Examples
2039 --------
2034 --------
2040 ::
2035 ::
2041
2036
2042 In [1]: time 2**128
2037 In [1]: time 2**128
2043 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2038 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2044 Wall time: 0.00
2039 Wall time: 0.00
2045 Out[1]: 340282366920938463463374607431768211456L
2040 Out[1]: 340282366920938463463374607431768211456L
2046
2041
2047 In [2]: n = 1000000
2042 In [2]: n = 1000000
2048
2043
2049 In [3]: time sum(range(n))
2044 In [3]: time sum(range(n))
2050 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2045 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2051 Wall time: 1.37
2046 Wall time: 1.37
2052 Out[3]: 499999500000L
2047 Out[3]: 499999500000L
2053
2048
2054 In [4]: time print 'hello world'
2049 In [4]: time print 'hello world'
2055 hello world
2050 hello world
2056 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2051 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2057 Wall time: 0.00
2052 Wall time: 0.00
2058
2053
2059 Note that the time needed by Python to compile the given expression
2054 Note that the time needed by Python to compile the given expression
2060 will be reported if it is more than 0.1s. In this example, the
2055 will be reported if it is more than 0.1s. In this example, the
2061 actual exponentiation is done by Python at compilation time, so while
2056 actual exponentiation is done by Python at compilation time, so while
2062 the expression can take a noticeable amount of time to compute, that
2057 the expression can take a noticeable amount of time to compute, that
2063 time is purely due to the compilation:
2058 time is purely due to the compilation:
2064
2059
2065 In [5]: time 3**9999;
2060 In [5]: time 3**9999;
2066 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2061 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2067 Wall time: 0.00 s
2062 Wall time: 0.00 s
2068
2063
2069 In [6]: time 3**999999;
2064 In [6]: time 3**999999;
2070 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2065 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2071 Wall time: 0.00 s
2066 Wall time: 0.00 s
2072 Compiler : 0.78 s
2067 Compiler : 0.78 s
2073 """
2068 """
2074
2069
2075 # fail immediately if the given expression can't be compiled
2070 # fail immediately if the given expression can't be compiled
2076
2071
2077 expr = self.shell.prefilter(parameter_s,False)
2072 expr = self.shell.prefilter(parameter_s,False)
2078
2073
2079 # Minimum time above which compilation time will be reported
2074 # Minimum time above which compilation time will be reported
2080 tc_min = 0.1
2075 tc_min = 0.1
2081
2076
2082 try:
2077 try:
2083 mode = 'eval'
2078 mode = 'eval'
2084 t0 = clock()
2079 t0 = clock()
2085 code = compile(expr,'<timed eval>',mode)
2080 code = compile(expr,'<timed eval>',mode)
2086 tc = clock()-t0
2081 tc = clock()-t0
2087 except SyntaxError:
2082 except SyntaxError:
2088 mode = 'exec'
2083 mode = 'exec'
2089 t0 = clock()
2084 t0 = clock()
2090 code = compile(expr,'<timed exec>',mode)
2085 code = compile(expr,'<timed exec>',mode)
2091 tc = clock()-t0
2086 tc = clock()-t0
2092 # skew measurement as little as possible
2087 # skew measurement as little as possible
2093 glob = self.shell.user_ns
2088 glob = self.shell.user_ns
2094 locs = self._magic_locals
2089 locs = self._magic_locals
2095 clk = clock2
2090 clk = clock2
2096 wtime = time.time
2091 wtime = time.time
2097 # time execution
2092 # time execution
2098 wall_st = wtime()
2093 wall_st = wtime()
2099 if mode=='eval':
2094 if mode=='eval':
2100 st = clk()
2095 st = clk()
2101 out = eval(code, glob, locs)
2096 out = eval(code, glob, locs)
2102 end = clk()
2097 end = clk()
2103 else:
2098 else:
2104 st = clk()
2099 st = clk()
2105 exec code in glob, locs
2100 exec code in glob, locs
2106 end = clk()
2101 end = clk()
2107 out = None
2102 out = None
2108 wall_end = wtime()
2103 wall_end = wtime()
2109 # Compute actual times and report
2104 # Compute actual times and report
2110 wall_time = wall_end-wall_st
2105 wall_time = wall_end-wall_st
2111 cpu_user = end[0]-st[0]
2106 cpu_user = end[0]-st[0]
2112 cpu_sys = end[1]-st[1]
2107 cpu_sys = end[1]-st[1]
2113 cpu_tot = cpu_user+cpu_sys
2108 cpu_tot = cpu_user+cpu_sys
2114 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2109 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2115 (cpu_user,cpu_sys,cpu_tot)
2110 (cpu_user,cpu_sys,cpu_tot)
2116 print "Wall time: %.2f s" % wall_time
2111 print "Wall time: %.2f s" % wall_time
2117 if tc > tc_min:
2112 if tc > tc_min:
2118 print "Compiler : %.2f s" % tc
2113 print "Compiler : %.2f s" % tc
2119 return out
2114 return out
2120
2115
2121 @skip_doctest
2116 @skip_doctest
2122 def magic_macro(self,parameter_s = ''):
2117 def magic_macro(self,parameter_s = ''):
2123 """Define a macro for future re-execution. It accepts ranges of history,
2118 """Define a macro for future re-execution. It accepts ranges of history,
2124 filenames or string objects.
2119 filenames or string objects.
2125
2120
2126 Usage:\\
2121 Usage:\\
2127 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2122 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2128
2123
2129 Options:
2124 Options:
2130
2125
2131 -r: use 'raw' input. By default, the 'processed' history is used,
2126 -r: use 'raw' input. By default, the 'processed' history is used,
2132 so that magics are loaded in their transformed version to valid
2127 so that magics are loaded in their transformed version to valid
2133 Python. If this option is given, the raw input as typed as the
2128 Python. If this option is given, the raw input as typed as the
2134 command line is used instead.
2129 command line is used instead.
2135
2130
2136 This will define a global variable called `name` which is a string
2131 This will define a global variable called `name` which is a string
2137 made of joining the slices and lines you specify (n1,n2,... numbers
2132 made of joining the slices and lines you specify (n1,n2,... numbers
2138 above) from your input history into a single string. This variable
2133 above) from your input history into a single string. This variable
2139 acts like an automatic function which re-executes those lines as if
2134 acts like an automatic function which re-executes those lines as if
2140 you had typed them. You just type 'name' at the prompt and the code
2135 you had typed them. You just type 'name' at the prompt and the code
2141 executes.
2136 executes.
2142
2137
2143 The syntax for indicating input ranges is described in %history.
2138 The syntax for indicating input ranges is described in %history.
2144
2139
2145 Note: as a 'hidden' feature, you can also use traditional python slice
2140 Note: as a 'hidden' feature, you can also use traditional python slice
2146 notation, where N:M means numbers N through M-1.
2141 notation, where N:M means numbers N through M-1.
2147
2142
2148 For example, if your history contains (%hist prints it)::
2143 For example, if your history contains (%hist prints it)::
2149
2144
2150 44: x=1
2145 44: x=1
2151 45: y=3
2146 45: y=3
2152 46: z=x+y
2147 46: z=x+y
2153 47: print x
2148 47: print x
2154 48: a=5
2149 48: a=5
2155 49: print 'x',x,'y',y
2150 49: print 'x',x,'y',y
2156
2151
2157 you can create a macro with lines 44 through 47 (included) and line 49
2152 you can create a macro with lines 44 through 47 (included) and line 49
2158 called my_macro with::
2153 called my_macro with::
2159
2154
2160 In [55]: %macro my_macro 44-47 49
2155 In [55]: %macro my_macro 44-47 49
2161
2156
2162 Now, typing `my_macro` (without quotes) will re-execute all this code
2157 Now, typing `my_macro` (without quotes) will re-execute all this code
2163 in one pass.
2158 in one pass.
2164
2159
2165 You don't need to give the line-numbers in order, and any given line
2160 You don't need to give the line-numbers in order, and any given line
2166 number can appear multiple times. You can assemble macros with any
2161 number can appear multiple times. You can assemble macros with any
2167 lines from your input history in any order.
2162 lines from your input history in any order.
2168
2163
2169 The macro is a simple object which holds its value in an attribute,
2164 The macro is a simple object which holds its value in an attribute,
2170 but IPython's display system checks for macros and executes them as
2165 but IPython's display system checks for macros and executes them as
2171 code instead of printing them when you type their name.
2166 code instead of printing them when you type their name.
2172
2167
2173 You can view a macro's contents by explicitly printing it with::
2168 You can view a macro's contents by explicitly printing it with::
2174
2169
2175 print macro_name
2170 print macro_name
2176
2171
2177 """
2172 """
2178 opts,args = self.parse_options(parameter_s,'r',mode='list')
2173 opts,args = self.parse_options(parameter_s,'r',mode='list')
2179 if not args: # List existing macros
2174 if not args: # List existing macros
2180 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2175 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2181 isinstance(v, Macro))
2176 isinstance(v, Macro))
2182 if len(args) == 1:
2177 if len(args) == 1:
2183 raise UsageError(
2178 raise UsageError(
2184 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2179 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2185 name, codefrom = args[0], " ".join(args[1:])
2180 name, codefrom = args[0], " ".join(args[1:])
2186
2181
2187 #print 'rng',ranges # dbg
2182 #print 'rng',ranges # dbg
2188 try:
2183 try:
2189 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2184 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2190 except (ValueError, TypeError) as e:
2185 except (ValueError, TypeError) as e:
2191 print e.args[0]
2186 print e.args[0]
2192 return
2187 return
2193 macro = Macro(lines)
2188 macro = Macro(lines)
2194 self.shell.define_macro(name, macro)
2189 self.shell.define_macro(name, macro)
2195 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2190 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2196 print '=== Macro contents: ==='
2191 print '=== Macro contents: ==='
2197 print macro,
2192 print macro,
2198
2193
2199 def magic_save(self,parameter_s = ''):
2194 def magic_save(self,parameter_s = ''):
2200 """Save a set of lines or a macro to a given filename.
2195 """Save a set of lines or a macro to a given filename.
2201
2196
2202 Usage:\\
2197 Usage:\\
2203 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2198 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2204
2199
2205 Options:
2200 Options:
2206
2201
2207 -r: use 'raw' input. By default, the 'processed' history is used,
2202 -r: use 'raw' input. By default, the 'processed' history is used,
2208 so that magics are loaded in their transformed version to valid
2203 so that magics are loaded in their transformed version to valid
2209 Python. If this option is given, the raw input as typed as the
2204 Python. If this option is given, the raw input as typed as the
2210 command line is used instead.
2205 command line is used instead.
2211
2206
2212 This function uses the same syntax as %history for input ranges,
2207 This function uses the same syntax as %history for input ranges,
2213 then saves the lines to the filename you specify.
2208 then saves the lines to the filename you specify.
2214
2209
2215 It adds a '.py' extension to the file if you don't do so yourself, and
2210 It adds a '.py' extension to the file if you don't do so yourself, and
2216 it asks for confirmation before overwriting existing files."""
2211 it asks for confirmation before overwriting existing files."""
2217
2212
2218 opts,args = self.parse_options(parameter_s,'r',mode='list')
2213 opts,args = self.parse_options(parameter_s,'r',mode='list')
2219 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2214 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2220 if not fname.endswith('.py'):
2215 if not fname.endswith('.py'):
2221 fname += '.py'
2216 fname += '.py'
2222 if os.path.isfile(fname):
2217 if os.path.isfile(fname):
2223 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2218 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2224 if ans.lower() not in ['y','yes']:
2219 if ans.lower() not in ['y','yes']:
2225 print 'Operation cancelled.'
2220 print 'Operation cancelled.'
2226 return
2221 return
2227 try:
2222 try:
2228 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2223 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2229 except (TypeError, ValueError) as e:
2224 except (TypeError, ValueError) as e:
2230 print e.args[0]
2225 print e.args[0]
2231 return
2226 return
2232 with py3compat.open(fname,'w', encoding="utf-8") as f:
2227 with py3compat.open(fname,'w', encoding="utf-8") as f:
2233 f.write(u"# coding: utf-8\n")
2228 f.write(u"# coding: utf-8\n")
2234 f.write(py3compat.cast_unicode(cmds))
2229 f.write(py3compat.cast_unicode(cmds))
2235 print 'The following commands were written to file `%s`:' % fname
2230 print 'The following commands were written to file `%s`:' % fname
2236 print cmds
2231 print cmds
2237
2232
2238 def magic_pastebin(self, parameter_s = ''):
2233 def magic_pastebin(self, parameter_s = ''):
2239 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2234 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2240 try:
2235 try:
2241 code = self.shell.find_user_code(parameter_s)
2236 code = self.shell.find_user_code(parameter_s)
2242 except (ValueError, TypeError) as e:
2237 except (ValueError, TypeError) as e:
2243 print e.args[0]
2238 print e.args[0]
2244 return
2239 return
2245 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2240 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2246 id = pbserver.pastes.newPaste("python", code)
2241 id = pbserver.pastes.newPaste("python", code)
2247 return "http://paste.pocoo.org/show/" + id
2242 return "http://paste.pocoo.org/show/" + id
2248
2243
2249 def magic_loadpy(self, arg_s):
2244 def magic_loadpy(self, arg_s):
2250 """Load a .py python script into the GUI console.
2245 """Load a .py python script into the GUI console.
2251
2246
2252 This magic command can either take a local filename or a url::
2247 This magic command can either take a local filename or a url::
2253
2248
2254 %loadpy myscript.py
2249 %loadpy myscript.py
2255 %loadpy http://www.example.com/myscript.py
2250 %loadpy http://www.example.com/myscript.py
2256 """
2251 """
2257 arg_s = unquote_filename(arg_s)
2252 arg_s = unquote_filename(arg_s)
2258 remote_url = arg_s.startswith(('http://', 'https://'))
2253 remote_url = arg_s.startswith(('http://', 'https://'))
2259 local_url = not remote_url
2254 local_url = not remote_url
2260 if local_url and not arg_s.endswith('.py'):
2255 if local_url and not arg_s.endswith('.py'):
2261 # Local files must be .py; for remote URLs it's possible that the
2256 # Local files must be .py; for remote URLs it's possible that the
2262 # fetch URL doesn't have a .py in it (many servers have an opaque
2257 # fetch URL doesn't have a .py in it (many servers have an opaque
2263 # URL, such as scipy-central.org).
2258 # URL, such as scipy-central.org).
2264 raise ValueError('%%load only works with .py files: %s' % arg_s)
2259 raise ValueError('%%load only works with .py files: %s' % arg_s)
2265 if remote_url:
2260 if remote_url:
2266 import urllib2
2261 import urllib2
2267 fileobj = urllib2.urlopen(arg_s)
2262 fileobj = urllib2.urlopen(arg_s)
2268 # While responses have a .info().getencoding() way of asking for
2263 # While responses have a .info().getencoding() way of asking for
2269 # their encoding, in *many* cases the return value is bogus. In
2264 # their encoding, in *many* cases the return value is bogus. In
2270 # the wild, servers serving utf-8 but declaring latin-1 are
2265 # the wild, servers serving utf-8 but declaring latin-1 are
2271 # extremely common, as the old HTTP standards specify latin-1 as
2266 # extremely common, as the old HTTP standards specify latin-1 as
2272 # the default but many modern filesystems use utf-8. So we can NOT
2267 # the default but many modern filesystems use utf-8. So we can NOT
2273 # rely on the headers. Short of building complex encoding-guessing
2268 # rely on the headers. Short of building complex encoding-guessing
2274 # logic, going with utf-8 is a simple solution likely to be right
2269 # logic, going with utf-8 is a simple solution likely to be right
2275 # in most real-world cases.
2270 # in most real-world cases.
2276 linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
2271 linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
2277 fileobj.close()
2272 fileobj.close()
2278 else:
2273 else:
2279 with open(arg_s) as fileobj:
2274 with open(arg_s) as fileobj:
2280 linesource = fileobj.read().splitlines()
2275 linesource = fileobj.read().splitlines()
2281
2276
2282 # Strip out encoding declarations
2277 # Strip out encoding declarations
2283 lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
2278 lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
2284
2279
2285 self.set_next_input(os.linesep.join(lines))
2280 self.set_next_input(os.linesep.join(lines))
2286
2281
2287 def _find_edit_target(self, args, opts, last_call):
2282 def _find_edit_target(self, args, opts, last_call):
2288 """Utility method used by magic_edit to find what to edit."""
2283 """Utility method used by magic_edit to find what to edit."""
2289
2284
2290 def make_filename(arg):
2285 def make_filename(arg):
2291 "Make a filename from the given args"
2286 "Make a filename from the given args"
2292 arg = unquote_filename(arg)
2287 arg = unquote_filename(arg)
2293 try:
2288 try:
2294 filename = get_py_filename(arg)
2289 filename = get_py_filename(arg)
2295 except IOError:
2290 except IOError:
2296 # If it ends with .py but doesn't already exist, assume we want
2291 # If it ends with .py but doesn't already exist, assume we want
2297 # a new file.
2292 # a new file.
2298 if arg.endswith('.py'):
2293 if arg.endswith('.py'):
2299 filename = arg
2294 filename = arg
2300 else:
2295 else:
2301 filename = None
2296 filename = None
2302 return filename
2297 return filename
2303
2298
2304 # Set a few locals from the options for convenience:
2299 # Set a few locals from the options for convenience:
2305 opts_prev = 'p' in opts
2300 opts_prev = 'p' in opts
2306 opts_raw = 'r' in opts
2301 opts_raw = 'r' in opts
2307
2302
2308 # custom exceptions
2303 # custom exceptions
2309 class DataIsObject(Exception): pass
2304 class DataIsObject(Exception): pass
2310
2305
2311 # Default line number value
2306 # Default line number value
2312 lineno = opts.get('n',None)
2307 lineno = opts.get('n',None)
2313
2308
2314 if opts_prev:
2309 if opts_prev:
2315 args = '_%s' % last_call[0]
2310 args = '_%s' % last_call[0]
2316 if not self.shell.user_ns.has_key(args):
2311 if not self.shell.user_ns.has_key(args):
2317 args = last_call[1]
2312 args = last_call[1]
2318
2313
2319 # use last_call to remember the state of the previous call, but don't
2314 # use last_call to remember the state of the previous call, but don't
2320 # let it be clobbered by successive '-p' calls.
2315 # let it be clobbered by successive '-p' calls.
2321 try:
2316 try:
2322 last_call[0] = self.shell.displayhook.prompt_count
2317 last_call[0] = self.shell.displayhook.prompt_count
2323 if not opts_prev:
2318 if not opts_prev:
2324 last_call[1] = parameter_s
2319 last_call[1] = args
2325 except:
2320 except:
2326 pass
2321 pass
2327
2322
2328 # by default this is done with temp files, except when the given
2323 # by default this is done with temp files, except when the given
2329 # arg is a filename
2324 # arg is a filename
2330 use_temp = True
2325 use_temp = True
2331
2326
2332 data = ''
2327 data = ''
2333
2328
2334 # First, see if the arguments should be a filename.
2329 # First, see if the arguments should be a filename.
2335 filename = make_filename(args)
2330 filename = make_filename(args)
2336 if filename:
2331 if filename:
2337 use_temp = False
2332 use_temp = False
2338 elif args:
2333 elif args:
2339 # Mode where user specifies ranges of lines, like in %macro.
2334 # Mode where user specifies ranges of lines, like in %macro.
2340 data = self.extract_input_lines(args, opts_raw)
2335 data = self.extract_input_lines(args, opts_raw)
2341 if not data:
2336 if not data:
2342 try:
2337 try:
2343 # Load the parameter given as a variable. If not a string,
2338 # Load the parameter given as a variable. If not a string,
2344 # process it as an object instead (below)
2339 # process it as an object instead (below)
2345
2340
2346 #print '*** args',args,'type',type(args) # dbg
2341 #print '*** args',args,'type',type(args) # dbg
2347 data = eval(args, self.shell.user_ns)
2342 data = eval(args, self.shell.user_ns)
2348 if not isinstance(data, basestring):
2343 if not isinstance(data, basestring):
2349 raise DataIsObject
2344 raise DataIsObject
2350
2345
2351 except (NameError,SyntaxError):
2346 except (NameError,SyntaxError):
2352 # given argument is not a variable, try as a filename
2347 # given argument is not a variable, try as a filename
2353 filename = make_filename(args)
2348 filename = make_filename(args)
2354 if filename is None:
2349 if filename is None:
2355 warn("Argument given (%s) can't be found as a variable "
2350 warn("Argument given (%s) can't be found as a variable "
2356 "or as a filename." % args)
2351 "or as a filename." % args)
2357 return
2352 return
2358 use_temp = False
2353 use_temp = False
2359
2354
2360 except DataIsObject:
2355 except DataIsObject:
2361 # macros have a special edit function
2356 # macros have a special edit function
2362 if isinstance(data, Macro):
2357 if isinstance(data, Macro):
2363 raise MacroToEdit(data)
2358 raise MacroToEdit(data)
2364
2359
2365 # For objects, try to edit the file where they are defined
2360 # For objects, try to edit the file where they are defined
2366 try:
2361 try:
2367 filename = inspect.getabsfile(data)
2362 filename = inspect.getabsfile(data)
2368 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2363 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2369 # class created by %edit? Try to find source
2364 # class created by %edit? Try to find source
2370 # by looking for method definitions instead, the
2365 # by looking for method definitions instead, the
2371 # __module__ in those classes is FakeModule.
2366 # __module__ in those classes is FakeModule.
2372 attrs = [getattr(data, aname) for aname in dir(data)]
2367 attrs = [getattr(data, aname) for aname in dir(data)]
2373 for attr in attrs:
2368 for attr in attrs:
2374 if not inspect.ismethod(attr):
2369 if not inspect.ismethod(attr):
2375 continue
2370 continue
2376 filename = inspect.getabsfile(attr)
2371 filename = inspect.getabsfile(attr)
2377 if filename and 'fakemodule' not in filename.lower():
2372 if filename and 'fakemodule' not in filename.lower():
2378 # change the attribute to be the edit target instead
2373 # change the attribute to be the edit target instead
2379 data = attr
2374 data = attr
2380 break
2375 break
2381
2376
2382 datafile = 1
2377 datafile = 1
2383 except TypeError:
2378 except TypeError:
2384 filename = make_filename(args)
2379 filename = make_filename(args)
2385 datafile = 1
2380 datafile = 1
2386 warn('Could not find file where `%s` is defined.\n'
2381 warn('Could not find file where `%s` is defined.\n'
2387 'Opening a file named `%s`' % (args,filename))
2382 'Opening a file named `%s`' % (args,filename))
2388 # Now, make sure we can actually read the source (if it was in
2383 # Now, make sure we can actually read the source (if it was in
2389 # a temp file it's gone by now).
2384 # a temp file it's gone by now).
2390 if datafile:
2385 if datafile:
2391 try:
2386 try:
2392 if lineno is None:
2387 if lineno is None:
2393 lineno = inspect.getsourcelines(data)[1]
2388 lineno = inspect.getsourcelines(data)[1]
2394 except IOError:
2389 except IOError:
2395 filename = make_filename(args)
2390 filename = make_filename(args)
2396 if filename is None:
2391 if filename is None:
2397 warn('The file `%s` where `%s` was defined cannot '
2392 warn('The file `%s` where `%s` was defined cannot '
2398 'be read.' % (filename,data))
2393 'be read.' % (filename,data))
2399 return
2394 return
2400 use_temp = False
2395 use_temp = False
2401
2396
2402 if use_temp:
2397 if use_temp:
2403 filename = self.shell.mktempfile(data)
2398 filename = self.shell.mktempfile(data)
2404 print 'IPython will make a temporary file named:',filename
2399 print 'IPython will make a temporary file named:',filename
2405
2400
2406 return filename, lineno, use_temp
2401 return filename, lineno, use_temp
2407
2402
2408 def _edit_macro(self,mname,macro):
2403 def _edit_macro(self,mname,macro):
2409 """open an editor with the macro data in a file"""
2404 """open an editor with the macro data in a file"""
2410 filename = self.shell.mktempfile(macro.value)
2405 filename = self.shell.mktempfile(macro.value)
2411 self.shell.hooks.editor(filename)
2406 self.shell.hooks.editor(filename)
2412
2407
2413 # and make a new macro object, to replace the old one
2408 # and make a new macro object, to replace the old one
2414 mfile = open(filename)
2409 mfile = open(filename)
2415 mvalue = mfile.read()
2410 mvalue = mfile.read()
2416 mfile.close()
2411 mfile.close()
2417 self.shell.user_ns[mname] = Macro(mvalue)
2412 self.shell.user_ns[mname] = Macro(mvalue)
2418
2413
2419 def magic_ed(self,parameter_s=''):
2414 def magic_ed(self,parameter_s=''):
2420 """Alias to %edit."""
2415 """Alias to %edit."""
2421 return self.magic_edit(parameter_s)
2416 return self.magic_edit(parameter_s)
2422
2417
2423 @skip_doctest
2418 @skip_doctest
2424 def magic_edit(self,parameter_s='',last_call=['','']):
2419 def magic_edit(self,parameter_s='',last_call=['','']):
2425 """Bring up an editor and execute the resulting code.
2420 """Bring up an editor and execute the resulting code.
2426
2421
2427 Usage:
2422 Usage:
2428 %edit [options] [args]
2423 %edit [options] [args]
2429
2424
2430 %edit runs IPython's editor hook. The default version of this hook is
2425 %edit runs IPython's editor hook. The default version of this hook is
2431 set to call the editor specified by your $EDITOR environment variable.
2426 set to call the editor specified by your $EDITOR environment variable.
2432 If this isn't found, it will default to vi under Linux/Unix and to
2427 If this isn't found, it will default to vi under Linux/Unix and to
2433 notepad under Windows. See the end of this docstring for how to change
2428 notepad under Windows. See the end of this docstring for how to change
2434 the editor hook.
2429 the editor hook.
2435
2430
2436 You can also set the value of this editor via the
2431 You can also set the value of this editor via the
2437 ``TerminalInteractiveShell.editor`` option in your configuration file.
2432 ``TerminalInteractiveShell.editor`` option in your configuration file.
2438 This is useful if you wish to use a different editor from your typical
2433 This is useful if you wish to use a different editor from your typical
2439 default with IPython (and for Windows users who typically don't set
2434 default with IPython (and for Windows users who typically don't set
2440 environment variables).
2435 environment variables).
2441
2436
2442 This command allows you to conveniently edit multi-line code right in
2437 This command allows you to conveniently edit multi-line code right in
2443 your IPython session.
2438 your IPython session.
2444
2439
2445 If called without arguments, %edit opens up an empty editor with a
2440 If called without arguments, %edit opens up an empty editor with a
2446 temporary file and will execute the contents of this file when you
2441 temporary file and will execute the contents of this file when you
2447 close it (don't forget to save it!).
2442 close it (don't forget to save it!).
2448
2443
2449
2444
2450 Options:
2445 Options:
2451
2446
2452 -n <number>: open the editor at a specified line number. By default,
2447 -n <number>: open the editor at a specified line number. By default,
2453 the IPython editor hook uses the unix syntax 'editor +N filename', but
2448 the IPython editor hook uses the unix syntax 'editor +N filename', but
2454 you can configure this by providing your own modified hook if your
2449 you can configure this by providing your own modified hook if your
2455 favorite editor supports line-number specifications with a different
2450 favorite editor supports line-number specifications with a different
2456 syntax.
2451 syntax.
2457
2452
2458 -p: this will call the editor with the same data as the previous time
2453 -p: this will call the editor with the same data as the previous time
2459 it was used, regardless of how long ago (in your current session) it
2454 it was used, regardless of how long ago (in your current session) it
2460 was.
2455 was.
2461
2456
2462 -r: use 'raw' input. This option only applies to input taken from the
2457 -r: use 'raw' input. This option only applies to input taken from the
2463 user's history. By default, the 'processed' history is used, so that
2458 user's history. By default, the 'processed' history is used, so that
2464 magics are loaded in their transformed version to valid Python. If
2459 magics are loaded in their transformed version to valid Python. If
2465 this option is given, the raw input as typed as the command line is
2460 this option is given, the raw input as typed as the command line is
2466 used instead. When you exit the editor, it will be executed by
2461 used instead. When you exit the editor, it will be executed by
2467 IPython's own processor.
2462 IPython's own processor.
2468
2463
2469 -x: do not execute the edited code immediately upon exit. This is
2464 -x: do not execute the edited code immediately upon exit. This is
2470 mainly useful if you are editing programs which need to be called with
2465 mainly useful if you are editing programs which need to be called with
2471 command line arguments, which you can then do using %run.
2466 command line arguments, which you can then do using %run.
2472
2467
2473
2468
2474 Arguments:
2469 Arguments:
2475
2470
2476 If arguments are given, the following possibilities exist:
2471 If arguments are given, the following possibilities exist:
2477
2472
2478 - If the argument is a filename, IPython will load that into the
2473 - If the argument is a filename, IPython will load that into the
2479 editor. It will execute its contents with execfile() when you exit,
2474 editor. It will execute its contents with execfile() when you exit,
2480 loading any code in the file into your interactive namespace.
2475 loading any code in the file into your interactive namespace.
2481
2476
2482 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2477 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2483 The syntax is the same as in the %history magic.
2478 The syntax is the same as in the %history magic.
2484
2479
2485 - If the argument is a string variable, its contents are loaded
2480 - If the argument is a string variable, its contents are loaded
2486 into the editor. You can thus edit any string which contains
2481 into the editor. You can thus edit any string which contains
2487 python code (including the result of previous edits).
2482 python code (including the result of previous edits).
2488
2483
2489 - If the argument is the name of an object (other than a string),
2484 - If the argument is the name of an object (other than a string),
2490 IPython will try to locate the file where it was defined and open the
2485 IPython will try to locate the file where it was defined and open the
2491 editor at the point where it is defined. You can use `%edit function`
2486 editor at the point where it is defined. You can use `%edit function`
2492 to load an editor exactly at the point where 'function' is defined,
2487 to load an editor exactly at the point where 'function' is defined,
2493 edit it and have the file be executed automatically.
2488 edit it and have the file be executed automatically.
2494
2489
2495 - If the object is a macro (see %macro for details), this opens up your
2490 - If the object is a macro (see %macro for details), this opens up your
2496 specified editor with a temporary file containing the macro's data.
2491 specified editor with a temporary file containing the macro's data.
2497 Upon exit, the macro is reloaded with the contents of the file.
2492 Upon exit, the macro is reloaded with the contents of the file.
2498
2493
2499 Note: opening at an exact line is only supported under Unix, and some
2494 Note: opening at an exact line is only supported under Unix, and some
2500 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2495 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2501 '+NUMBER' parameter necessary for this feature. Good editors like
2496 '+NUMBER' parameter necessary for this feature. Good editors like
2502 (X)Emacs, vi, jed, pico and joe all do.
2497 (X)Emacs, vi, jed, pico and joe all do.
2503
2498
2504 After executing your code, %edit will return as output the code you
2499 After executing your code, %edit will return as output the code you
2505 typed in the editor (except when it was an existing file). This way
2500 typed in the editor (except when it was an existing file). This way
2506 you can reload the code in further invocations of %edit as a variable,
2501 you can reload the code in further invocations of %edit as a variable,
2507 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2502 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2508 the output.
2503 the output.
2509
2504
2510 Note that %edit is also available through the alias %ed.
2505 Note that %edit is also available through the alias %ed.
2511
2506
2512 This is an example of creating a simple function inside the editor and
2507 This is an example of creating a simple function inside the editor and
2513 then modifying it. First, start up the editor::
2508 then modifying it. First, start up the editor::
2514
2509
2515 In [1]: ed
2510 In [1]: ed
2516 Editing... done. Executing edited code...
2511 Editing... done. Executing edited code...
2517 Out[1]: 'def foo():\\n print "foo() was defined in an editing
2512 Out[1]: 'def foo():\\n print "foo() was defined in an editing
2518 session"\\n'
2513 session"\\n'
2519
2514
2520 We can then call the function foo()::
2515 We can then call the function foo()::
2521
2516
2522 In [2]: foo()
2517 In [2]: foo()
2523 foo() was defined in an editing session
2518 foo() was defined in an editing session
2524
2519
2525 Now we edit foo. IPython automatically loads the editor with the
2520 Now we edit foo. IPython automatically loads the editor with the
2526 (temporary) file where foo() was previously defined::
2521 (temporary) file where foo() was previously defined::
2527
2522
2528 In [3]: ed foo
2523 In [3]: ed foo
2529 Editing... done. Executing edited code...
2524 Editing... done. Executing edited code...
2530
2525
2531 And if we call foo() again we get the modified version::
2526 And if we call foo() again we get the modified version::
2532
2527
2533 In [4]: foo()
2528 In [4]: foo()
2534 foo() has now been changed!
2529 foo() has now been changed!
2535
2530
2536 Here is an example of how to edit a code snippet successive
2531 Here is an example of how to edit a code snippet successive
2537 times. First we call the editor::
2532 times. First we call the editor::
2538
2533
2539 In [5]: ed
2534 In [5]: ed
2540 Editing... done. Executing edited code...
2535 Editing... done. Executing edited code...
2541 hello
2536 hello
2542 Out[5]: "print 'hello'\\n"
2537 Out[5]: "print 'hello'\\n"
2543
2538
2544 Now we call it again with the previous output (stored in _)::
2539 Now we call it again with the previous output (stored in _)::
2545
2540
2546 In [6]: ed _
2541 In [6]: ed _
2547 Editing... done. Executing edited code...
2542 Editing... done. Executing edited code...
2548 hello world
2543 hello world
2549 Out[6]: "print 'hello world'\\n"
2544 Out[6]: "print 'hello world'\\n"
2550
2545
2551 Now we call it with the output #8 (stored in _8, also as Out[8])::
2546 Now we call it with the output #8 (stored in _8, also as Out[8])::
2552
2547
2553 In [7]: ed _8
2548 In [7]: ed _8
2554 Editing... done. Executing edited code...
2549 Editing... done. Executing edited code...
2555 hello again
2550 hello again
2556 Out[7]: "print 'hello again'\\n"
2551 Out[7]: "print 'hello again'\\n"
2557
2552
2558
2553
2559 Changing the default editor hook:
2554 Changing the default editor hook:
2560
2555
2561 If you wish to write your own editor hook, you can put it in a
2556 If you wish to write your own editor hook, you can put it in a
2562 configuration file which you load at startup time. The default hook
2557 configuration file which you load at startup time. The default hook
2563 is defined in the IPython.core.hooks module, and you can use that as a
2558 is defined in the IPython.core.hooks module, and you can use that as a
2564 starting example for further modifications. That file also has
2559 starting example for further modifications. That file also has
2565 general instructions on how to set a new hook for use once you've
2560 general instructions on how to set a new hook for use once you've
2566 defined it."""
2561 defined it."""
2567 opts,args = self.parse_options(parameter_s,'prxn:')
2562 opts,args = self.parse_options(parameter_s,'prxn:')
2568
2563
2569 try:
2564 try:
2570 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2565 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2571 except MacroToEdit as e:
2566 except MacroToEdit as e:
2572 self._edit_macro(args, e.args[0])
2567 self._edit_macro(args, e.args[0])
2573 return
2568 return
2574
2569
2575 # do actual editing here
2570 # do actual editing here
2576 print 'Editing...',
2571 print 'Editing...',
2577 sys.stdout.flush()
2572 sys.stdout.flush()
2578 try:
2573 try:
2579 # Quote filenames that may have spaces in them
2574 # Quote filenames that may have spaces in them
2580 if ' ' in filename:
2575 if ' ' in filename:
2581 filename = "'%s'" % filename
2576 filename = "'%s'" % filename
2582 self.shell.hooks.editor(filename,lineno)
2577 self.shell.hooks.editor(filename,lineno)
2583 except TryNext:
2578 except TryNext:
2584 warn('Could not open editor')
2579 warn('Could not open editor')
2585 return
2580 return
2586
2581
2587 # XXX TODO: should this be generalized for all string vars?
2582 # XXX TODO: should this be generalized for all string vars?
2588 # For now, this is special-cased to blocks created by cpaste
2583 # For now, this is special-cased to blocks created by cpaste
2589 if args.strip() == 'pasted_block':
2584 if args.strip() == 'pasted_block':
2590 self.shell.user_ns['pasted_block'] = file_read(filename)
2585 self.shell.user_ns['pasted_block'] = file_read(filename)
2591
2586
2592 if 'x' in opts: # -x prevents actual execution
2587 if 'x' in opts: # -x prevents actual execution
2593 print
2588 print
2594 else:
2589 else:
2595 print 'done. Executing edited code...'
2590 print 'done. Executing edited code...'
2596 if 'r' in opts: # Untranslated IPython code
2591 if 'r' in opts: # Untranslated IPython code
2597 self.shell.run_cell(file_read(filename),
2592 self.shell.run_cell(file_read(filename),
2598 store_history=False)
2593 store_history=False)
2599 else:
2594 else:
2600 self.shell.safe_execfile(filename,self.shell.user_ns,
2595 self.shell.safe_execfile(filename,self.shell.user_ns,
2601 self.shell.user_ns)
2596 self.shell.user_ns)
2602
2597
2603 if is_temp:
2598 if is_temp:
2604 try:
2599 try:
2605 return open(filename).read()
2600 return open(filename).read()
2606 except IOError,msg:
2601 except IOError,msg:
2607 if msg.filename == filename:
2602 if msg.filename == filename:
2608 warn('File not found. Did you forget to save?')
2603 warn('File not found. Did you forget to save?')
2609 return
2604 return
2610 else:
2605 else:
2611 self.shell.showtraceback()
2606 self.shell.showtraceback()
2612
2607
2613 def magic_xmode(self,parameter_s = ''):
2608 def magic_xmode(self,parameter_s = ''):
2614 """Switch modes for the exception handlers.
2609 """Switch modes for the exception handlers.
2615
2610
2616 Valid modes: Plain, Context and Verbose.
2611 Valid modes: Plain, Context and Verbose.
2617
2612
2618 If called without arguments, acts as a toggle."""
2613 If called without arguments, acts as a toggle."""
2619
2614
2620 def xmode_switch_err(name):
2615 def xmode_switch_err(name):
2621 warn('Error changing %s exception modes.\n%s' %
2616 warn('Error changing %s exception modes.\n%s' %
2622 (name,sys.exc_info()[1]))
2617 (name,sys.exc_info()[1]))
2623
2618
2624 shell = self.shell
2619 shell = self.shell
2625 new_mode = parameter_s.strip().capitalize()
2620 new_mode = parameter_s.strip().capitalize()
2626 try:
2621 try:
2627 shell.InteractiveTB.set_mode(mode=new_mode)
2622 shell.InteractiveTB.set_mode(mode=new_mode)
2628 print 'Exception reporting mode:',shell.InteractiveTB.mode
2623 print 'Exception reporting mode:',shell.InteractiveTB.mode
2629 except:
2624 except:
2630 xmode_switch_err('user')
2625 xmode_switch_err('user')
2631
2626
2632 def magic_colors(self,parameter_s = ''):
2627 def magic_colors(self,parameter_s = ''):
2633 """Switch color scheme for prompts, info system and exception handlers.
2628 """Switch color scheme for prompts, info system and exception handlers.
2634
2629
2635 Currently implemented schemes: NoColor, Linux, LightBG.
2630 Currently implemented schemes: NoColor, Linux, LightBG.
2636
2631
2637 Color scheme names are not case-sensitive.
2632 Color scheme names are not case-sensitive.
2638
2633
2639 Examples
2634 Examples
2640 --------
2635 --------
2641 To get a plain black and white terminal::
2636 To get a plain black and white terminal::
2642
2637
2643 %colors nocolor
2638 %colors nocolor
2644 """
2639 """
2645
2640
2646 def color_switch_err(name):
2641 def color_switch_err(name):
2647 warn('Error changing %s color schemes.\n%s' %
2642 warn('Error changing %s color schemes.\n%s' %
2648 (name,sys.exc_info()[1]))
2643 (name,sys.exc_info()[1]))
2649
2644
2650
2645
2651 new_scheme = parameter_s.strip()
2646 new_scheme = parameter_s.strip()
2652 if not new_scheme:
2647 if not new_scheme:
2653 raise UsageError(
2648 raise UsageError(
2654 "%colors: you must specify a color scheme. See '%colors?'")
2649 "%colors: you must specify a color scheme. See '%colors?'")
2655 return
2650 return
2656 # local shortcut
2651 # local shortcut
2657 shell = self.shell
2652 shell = self.shell
2658
2653
2659 import IPython.utils.rlineimpl as readline
2654 import IPython.utils.rlineimpl as readline
2660
2655
2661 if not shell.colors_force and \
2656 if not shell.colors_force and \
2662 not readline.have_readline and sys.platform == "win32":
2657 not readline.have_readline and sys.platform == "win32":
2663 msg = """\
2658 msg = """\
2664 Proper color support under MS Windows requires the pyreadline library.
2659 Proper color support under MS Windows requires the pyreadline library.
2665 You can find it at:
2660 You can find it at:
2666 http://ipython.org/pyreadline.html
2661 http://ipython.org/pyreadline.html
2667 Gary's readline needs the ctypes module, from:
2662 Gary's readline needs the ctypes module, from:
2668 http://starship.python.net/crew/theller/ctypes
2663 http://starship.python.net/crew/theller/ctypes
2669 (Note that ctypes is already part of Python versions 2.5 and newer).
2664 (Note that ctypes is already part of Python versions 2.5 and newer).
2670
2665
2671 Defaulting color scheme to 'NoColor'"""
2666 Defaulting color scheme to 'NoColor'"""
2672 new_scheme = 'NoColor'
2667 new_scheme = 'NoColor'
2673 warn(msg)
2668 warn(msg)
2674
2669
2675 # readline option is 0
2670 # readline option is 0
2676 if not shell.colors_force and not shell.has_readline:
2671 if not shell.colors_force and not shell.has_readline:
2677 new_scheme = 'NoColor'
2672 new_scheme = 'NoColor'
2678
2673
2679 # Set prompt colors
2674 # Set prompt colors
2680 try:
2675 try:
2681 shell.prompt_manager.color_scheme = new_scheme
2676 shell.prompt_manager.color_scheme = new_scheme
2682 except:
2677 except:
2683 color_switch_err('prompt')
2678 color_switch_err('prompt')
2684 else:
2679 else:
2685 shell.colors = \
2680 shell.colors = \
2686 shell.prompt_manager.color_scheme_table.active_scheme_name
2681 shell.prompt_manager.color_scheme_table.active_scheme_name
2687 # Set exception colors
2682 # Set exception colors
2688 try:
2683 try:
2689 shell.InteractiveTB.set_colors(scheme = new_scheme)
2684 shell.InteractiveTB.set_colors(scheme = new_scheme)
2690 shell.SyntaxTB.set_colors(scheme = new_scheme)
2685 shell.SyntaxTB.set_colors(scheme = new_scheme)
2691 except:
2686 except:
2692 color_switch_err('exception')
2687 color_switch_err('exception')
2693
2688
2694 # Set info (for 'object?') colors
2689 # Set info (for 'object?') colors
2695 if shell.color_info:
2690 if shell.color_info:
2696 try:
2691 try:
2697 shell.inspector.set_active_scheme(new_scheme)
2692 shell.inspector.set_active_scheme(new_scheme)
2698 except:
2693 except:
2699 color_switch_err('object inspector')
2694 color_switch_err('object inspector')
2700 else:
2695 else:
2701 shell.inspector.set_active_scheme('NoColor')
2696 shell.inspector.set_active_scheme('NoColor')
2702
2697
2703 def magic_pprint(self, parameter_s=''):
2698 def magic_pprint(self, parameter_s=''):
2704 """Toggle pretty printing on/off."""
2699 """Toggle pretty printing on/off."""
2705 ptformatter = self.shell.display_formatter.formatters['text/plain']
2700 ptformatter = self.shell.display_formatter.formatters['text/plain']
2706 ptformatter.pprint = bool(1 - ptformatter.pprint)
2701 ptformatter.pprint = bool(1 - ptformatter.pprint)
2707 print 'Pretty printing has been turned', \
2702 print 'Pretty printing has been turned', \
2708 ['OFF','ON'][ptformatter.pprint]
2703 ['OFF','ON'][ptformatter.pprint]
2709
2704
2710 #......................................................................
2705 #......................................................................
2711 # Functions to implement unix shell-type things
2706 # Functions to implement unix shell-type things
2712
2707
2713 @skip_doctest
2708 @skip_doctest
2714 def magic_alias(self, parameter_s = ''):
2709 def magic_alias(self, parameter_s = ''):
2715 """Define an alias for a system command.
2710 """Define an alias for a system command.
2716
2711
2717 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2712 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2718
2713
2719 Then, typing 'alias_name params' will execute the system command 'cmd
2714 Then, typing 'alias_name params' will execute the system command 'cmd
2720 params' (from your underlying operating system).
2715 params' (from your underlying operating system).
2721
2716
2722 Aliases have lower precedence than magic functions and Python normal
2717 Aliases have lower precedence than magic functions and Python normal
2723 variables, so if 'foo' is both a Python variable and an alias, the
2718 variables, so if 'foo' is both a Python variable and an alias, the
2724 alias can not be executed until 'del foo' removes the Python variable.
2719 alias can not be executed until 'del foo' removes the Python variable.
2725
2720
2726 You can use the %l specifier in an alias definition to represent the
2721 You can use the %l specifier in an alias definition to represent the
2727 whole line when the alias is called. For example::
2722 whole line when the alias is called. For example::
2728
2723
2729 In [2]: alias bracket echo "Input in brackets: <%l>"
2724 In [2]: alias bracket echo "Input in brackets: <%l>"
2730 In [3]: bracket hello world
2725 In [3]: bracket hello world
2731 Input in brackets: <hello world>
2726 Input in brackets: <hello world>
2732
2727
2733 You can also define aliases with parameters using %s specifiers (one
2728 You can also define aliases with parameters using %s specifiers (one
2734 per parameter)::
2729 per parameter)::
2735
2730
2736 In [1]: alias parts echo first %s second %s
2731 In [1]: alias parts echo first %s second %s
2737 In [2]: %parts A B
2732 In [2]: %parts A B
2738 first A second B
2733 first A second B
2739 In [3]: %parts A
2734 In [3]: %parts A
2740 Incorrect number of arguments: 2 expected.
2735 Incorrect number of arguments: 2 expected.
2741 parts is an alias to: 'echo first %s second %s'
2736 parts is an alias to: 'echo first %s second %s'
2742
2737
2743 Note that %l and %s are mutually exclusive. You can only use one or
2738 Note that %l and %s are mutually exclusive. You can only use one or
2744 the other in your aliases.
2739 the other in your aliases.
2745
2740
2746 Aliases expand Python variables just like system calls using ! or !!
2741 Aliases expand Python variables just like system calls using ! or !!
2747 do: all expressions prefixed with '$' get expanded. For details of
2742 do: all expressions prefixed with '$' get expanded. For details of
2748 the semantic rules, see PEP-215:
2743 the semantic rules, see PEP-215:
2749 http://www.python.org/peps/pep-0215.html. This is the library used by
2744 http://www.python.org/peps/pep-0215.html. This is the library used by
2750 IPython for variable expansion. If you want to access a true shell
2745 IPython for variable expansion. If you want to access a true shell
2751 variable, an extra $ is necessary to prevent its expansion by
2746 variable, an extra $ is necessary to prevent its expansion by
2752 IPython::
2747 IPython::
2753
2748
2754 In [6]: alias show echo
2749 In [6]: alias show echo
2755 In [7]: PATH='A Python string'
2750 In [7]: PATH='A Python string'
2756 In [8]: show $PATH
2751 In [8]: show $PATH
2757 A Python string
2752 A Python string
2758 In [9]: show $$PATH
2753 In [9]: show $$PATH
2759 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2754 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2760
2755
2761 You can use the alias facility to acess all of $PATH. See the %rehash
2756 You can use the alias facility to acess all of $PATH. See the %rehash
2762 and %rehashx functions, which automatically create aliases for the
2757 and %rehashx functions, which automatically create aliases for the
2763 contents of your $PATH.
2758 contents of your $PATH.
2764
2759
2765 If called with no parameters, %alias prints the current alias table."""
2760 If called with no parameters, %alias prints the current alias table."""
2766
2761
2767 par = parameter_s.strip()
2762 par = parameter_s.strip()
2768 if not par:
2763 if not par:
2769 stored = self.db.get('stored_aliases', {} )
2764 stored = self.db.get('stored_aliases', {} )
2770 aliases = sorted(self.shell.alias_manager.aliases)
2765 aliases = sorted(self.shell.alias_manager.aliases)
2771 # for k, v in stored:
2766 # for k, v in stored:
2772 # atab.append(k, v[0])
2767 # atab.append(k, v[0])
2773
2768
2774 print "Total number of aliases:", len(aliases)
2769 print "Total number of aliases:", len(aliases)
2775 sys.stdout.flush()
2770 sys.stdout.flush()
2776 return aliases
2771 return aliases
2777
2772
2778 # Now try to define a new one
2773 # Now try to define a new one
2779 try:
2774 try:
2780 alias,cmd = par.split(None, 1)
2775 alias,cmd = par.split(None, 1)
2781 except:
2776 except:
2782 print oinspect.getdoc(self.magic_alias)
2777 print oinspect.getdoc(self.magic_alias)
2783 else:
2778 else:
2784 self.shell.alias_manager.soft_define_alias(alias, cmd)
2779 self.shell.alias_manager.soft_define_alias(alias, cmd)
2785 # end magic_alias
2780 # end magic_alias
2786
2781
2787 def magic_unalias(self, parameter_s = ''):
2782 def magic_unalias(self, parameter_s = ''):
2788 """Remove an alias"""
2783 """Remove an alias"""
2789
2784
2790 aname = parameter_s.strip()
2785 aname = parameter_s.strip()
2791 self.shell.alias_manager.undefine_alias(aname)
2786 self.shell.alias_manager.undefine_alias(aname)
2792 stored = self.db.get('stored_aliases', {} )
2787 stored = self.db.get('stored_aliases', {} )
2793 if aname in stored:
2788 if aname in stored:
2794 print "Removing %stored alias",aname
2789 print "Removing %stored alias",aname
2795 del stored[aname]
2790 del stored[aname]
2796 self.db['stored_aliases'] = stored
2791 self.db['stored_aliases'] = stored
2797
2792
2798 def magic_rehashx(self, parameter_s = ''):
2793 def magic_rehashx(self, parameter_s = ''):
2799 """Update the alias table with all executable files in $PATH.
2794 """Update the alias table with all executable files in $PATH.
2800
2795
2801 This version explicitly checks that every entry in $PATH is a file
2796 This version explicitly checks that every entry in $PATH is a file
2802 with execute access (os.X_OK), so it is much slower than %rehash.
2797 with execute access (os.X_OK), so it is much slower than %rehash.
2803
2798
2804 Under Windows, it checks executability as a match against a
2799 Under Windows, it checks executability as a match against a
2805 '|'-separated string of extensions, stored in the IPython config
2800 '|'-separated string of extensions, stored in the IPython config
2806 variable win_exec_ext. This defaults to 'exe|com|bat'.
2801 variable win_exec_ext. This defaults to 'exe|com|bat'.
2807
2802
2808 This function also resets the root module cache of module completer,
2803 This function also resets the root module cache of module completer,
2809 used on slow filesystems.
2804 used on slow filesystems.
2810 """
2805 """
2811 from IPython.core.alias import InvalidAliasError
2806 from IPython.core.alias import InvalidAliasError
2812
2807
2813 # for the benefit of module completer in ipy_completers.py
2808 # for the benefit of module completer in ipy_completers.py
2814 del self.shell.db['rootmodules']
2809 del self.shell.db['rootmodules']
2815
2810
2816 path = [os.path.abspath(os.path.expanduser(p)) for p in
2811 path = [os.path.abspath(os.path.expanduser(p)) for p in
2817 os.environ.get('PATH','').split(os.pathsep)]
2812 os.environ.get('PATH','').split(os.pathsep)]
2818 path = filter(os.path.isdir,path)
2813 path = filter(os.path.isdir,path)
2819
2814
2820 syscmdlist = []
2815 syscmdlist = []
2821 # Now define isexec in a cross platform manner.
2816 # Now define isexec in a cross platform manner.
2822 if os.name == 'posix':
2817 if os.name == 'posix':
2823 isexec = lambda fname:os.path.isfile(fname) and \
2818 isexec = lambda fname:os.path.isfile(fname) and \
2824 os.access(fname,os.X_OK)
2819 os.access(fname,os.X_OK)
2825 else:
2820 else:
2826 try:
2821 try:
2827 winext = os.environ['pathext'].replace(';','|').replace('.','')
2822 winext = os.environ['pathext'].replace(';','|').replace('.','')
2828 except KeyError:
2823 except KeyError:
2829 winext = 'exe|com|bat|py'
2824 winext = 'exe|com|bat|py'
2830 if 'py' not in winext:
2825 if 'py' not in winext:
2831 winext += '|py'
2826 winext += '|py'
2832 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2827 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2833 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2828 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2834 savedir = os.getcwdu()
2829 savedir = os.getcwdu()
2835
2830
2836 # Now walk the paths looking for executables to alias.
2831 # Now walk the paths looking for executables to alias.
2837 try:
2832 try:
2838 # write the whole loop for posix/Windows so we don't have an if in
2833 # write the whole loop for posix/Windows so we don't have an if in
2839 # the innermost part
2834 # the innermost part
2840 if os.name == 'posix':
2835 if os.name == 'posix':
2841 for pdir in path:
2836 for pdir in path:
2842 os.chdir(pdir)
2837 os.chdir(pdir)
2843 for ff in os.listdir(pdir):
2838 for ff in os.listdir(pdir):
2844 if isexec(ff):
2839 if isexec(ff):
2845 try:
2840 try:
2846 # Removes dots from the name since ipython
2841 # Removes dots from the name since ipython
2847 # will assume names with dots to be python.
2842 # will assume names with dots to be python.
2848 self.shell.alias_manager.define_alias(
2843 self.shell.alias_manager.define_alias(
2849 ff.replace('.',''), ff)
2844 ff.replace('.',''), ff)
2850 except InvalidAliasError:
2845 except InvalidAliasError:
2851 pass
2846 pass
2852 else:
2847 else:
2853 syscmdlist.append(ff)
2848 syscmdlist.append(ff)
2854 else:
2849 else:
2855 no_alias = self.shell.alias_manager.no_alias
2850 no_alias = self.shell.alias_manager.no_alias
2856 for pdir in path:
2851 for pdir in path:
2857 os.chdir(pdir)
2852 os.chdir(pdir)
2858 for ff in os.listdir(pdir):
2853 for ff in os.listdir(pdir):
2859 base, ext = os.path.splitext(ff)
2854 base, ext = os.path.splitext(ff)
2860 if isexec(ff) and base.lower() not in no_alias:
2855 if isexec(ff) and base.lower() not in no_alias:
2861 if ext.lower() == '.exe':
2856 if ext.lower() == '.exe':
2862 ff = base
2857 ff = base
2863 try:
2858 try:
2864 # Removes dots from the name since ipython
2859 # Removes dots from the name since ipython
2865 # will assume names with dots to be python.
2860 # will assume names with dots to be python.
2866 self.shell.alias_manager.define_alias(
2861 self.shell.alias_manager.define_alias(
2867 base.lower().replace('.',''), ff)
2862 base.lower().replace('.',''), ff)
2868 except InvalidAliasError:
2863 except InvalidAliasError:
2869 pass
2864 pass
2870 syscmdlist.append(ff)
2865 syscmdlist.append(ff)
2871 self.shell.db['syscmdlist'] = syscmdlist
2866 self.shell.db['syscmdlist'] = syscmdlist
2872 finally:
2867 finally:
2873 os.chdir(savedir)
2868 os.chdir(savedir)
2874
2869
2875 @skip_doctest
2870 @skip_doctest
2876 def magic_pwd(self, parameter_s = ''):
2871 def magic_pwd(self, parameter_s = ''):
2877 """Return the current working directory path.
2872 """Return the current working directory path.
2878
2873
2879 Examples
2874 Examples
2880 --------
2875 --------
2881 ::
2876 ::
2882
2877
2883 In [9]: pwd
2878 In [9]: pwd
2884 Out[9]: '/home/tsuser/sprint/ipython'
2879 Out[9]: '/home/tsuser/sprint/ipython'
2885 """
2880 """
2886 return os.getcwdu()
2881 return os.getcwdu()
2887
2882
2888 @skip_doctest
2883 @skip_doctest
2889 def magic_cd(self, parameter_s=''):
2884 def magic_cd(self, parameter_s=''):
2890 """Change the current working directory.
2885 """Change the current working directory.
2891
2886
2892 This command automatically maintains an internal list of directories
2887 This command automatically maintains an internal list of directories
2893 you visit during your IPython session, in the variable _dh. The
2888 you visit during your IPython session, in the variable _dh. The
2894 command %dhist shows this history nicely formatted. You can also
2889 command %dhist shows this history nicely formatted. You can also
2895 do 'cd -<tab>' to see directory history conveniently.
2890 do 'cd -<tab>' to see directory history conveniently.
2896
2891
2897 Usage:
2892 Usage:
2898
2893
2899 cd 'dir': changes to directory 'dir'.
2894 cd 'dir': changes to directory 'dir'.
2900
2895
2901 cd -: changes to the last visited directory.
2896 cd -: changes to the last visited directory.
2902
2897
2903 cd -<n>: changes to the n-th directory in the directory history.
2898 cd -<n>: changes to the n-th directory in the directory history.
2904
2899
2905 cd --foo: change to directory that matches 'foo' in history
2900 cd --foo: change to directory that matches 'foo' in history
2906
2901
2907 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2902 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2908 (note: cd <bookmark_name> is enough if there is no
2903 (note: cd <bookmark_name> is enough if there is no
2909 directory <bookmark_name>, but a bookmark with the name exists.)
2904 directory <bookmark_name>, but a bookmark with the name exists.)
2910 'cd -b <tab>' allows you to tab-complete bookmark names.
2905 'cd -b <tab>' allows you to tab-complete bookmark names.
2911
2906
2912 Options:
2907 Options:
2913
2908
2914 -q: quiet. Do not print the working directory after the cd command is
2909 -q: quiet. Do not print the working directory after the cd command is
2915 executed. By default IPython's cd command does print this directory,
2910 executed. By default IPython's cd command does print this directory,
2916 since the default prompts do not display path information.
2911 since the default prompts do not display path information.
2917
2912
2918 Note that !cd doesn't work for this purpose because the shell where
2913 Note that !cd doesn't work for this purpose because the shell where
2919 !command runs is immediately discarded after executing 'command'.
2914 !command runs is immediately discarded after executing 'command'.
2920
2915
2921 Examples
2916 Examples
2922 --------
2917 --------
2923 ::
2918 ::
2924
2919
2925 In [10]: cd parent/child
2920 In [10]: cd parent/child
2926 /home/tsuser/parent/child
2921 /home/tsuser/parent/child
2927 """
2922 """
2928
2923
2929 parameter_s = parameter_s.strip()
2924 parameter_s = parameter_s.strip()
2930 #bkms = self.shell.persist.get("bookmarks",{})
2925 #bkms = self.shell.persist.get("bookmarks",{})
2931
2926
2932 oldcwd = os.getcwdu()
2927 oldcwd = os.getcwdu()
2933 numcd = re.match(r'(-)(\d+)$',parameter_s)
2928 numcd = re.match(r'(-)(\d+)$',parameter_s)
2934 # jump in directory history by number
2929 # jump in directory history by number
2935 if numcd:
2930 if numcd:
2936 nn = int(numcd.group(2))
2931 nn = int(numcd.group(2))
2937 try:
2932 try:
2938 ps = self.shell.user_ns['_dh'][nn]
2933 ps = self.shell.user_ns['_dh'][nn]
2939 except IndexError:
2934 except IndexError:
2940 print 'The requested directory does not exist in history.'
2935 print 'The requested directory does not exist in history.'
2941 return
2936 return
2942 else:
2937 else:
2943 opts = {}
2938 opts = {}
2944 elif parameter_s.startswith('--'):
2939 elif parameter_s.startswith('--'):
2945 ps = None
2940 ps = None
2946 fallback = None
2941 fallback = None
2947 pat = parameter_s[2:]
2942 pat = parameter_s[2:]
2948 dh = self.shell.user_ns['_dh']
2943 dh = self.shell.user_ns['_dh']
2949 # first search only by basename (last component)
2944 # first search only by basename (last component)
2950 for ent in reversed(dh):
2945 for ent in reversed(dh):
2951 if pat in os.path.basename(ent) and os.path.isdir(ent):
2946 if pat in os.path.basename(ent) and os.path.isdir(ent):
2952 ps = ent
2947 ps = ent
2953 break
2948 break
2954
2949
2955 if fallback is None and pat in ent and os.path.isdir(ent):
2950 if fallback is None and pat in ent and os.path.isdir(ent):
2956 fallback = ent
2951 fallback = ent
2957
2952
2958 # if we have no last part match, pick the first full path match
2953 # if we have no last part match, pick the first full path match
2959 if ps is None:
2954 if ps is None:
2960 ps = fallback
2955 ps = fallback
2961
2956
2962 if ps is None:
2957 if ps is None:
2963 print "No matching entry in directory history"
2958 print "No matching entry in directory history"
2964 return
2959 return
2965 else:
2960 else:
2966 opts = {}
2961 opts = {}
2967
2962
2968
2963
2969 else:
2964 else:
2970 #turn all non-space-escaping backslashes to slashes,
2965 #turn all non-space-escaping backslashes to slashes,
2971 # for c:\windows\directory\names\
2966 # for c:\windows\directory\names\
2972 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2967 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2973 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2968 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2974 # jump to previous
2969 # jump to previous
2975 if ps == '-':
2970 if ps == '-':
2976 try:
2971 try:
2977 ps = self.shell.user_ns['_dh'][-2]
2972 ps = self.shell.user_ns['_dh'][-2]
2978 except IndexError:
2973 except IndexError:
2979 raise UsageError('%cd -: No previous directory to change to.')
2974 raise UsageError('%cd -: No previous directory to change to.')
2980 # jump to bookmark if needed
2975 # jump to bookmark if needed
2981 else:
2976 else:
2982 if not os.path.isdir(ps) or opts.has_key('b'):
2977 if not os.path.isdir(ps) or opts.has_key('b'):
2983 bkms = self.db.get('bookmarks', {})
2978 bkms = self.db.get('bookmarks', {})
2984
2979
2985 if bkms.has_key(ps):
2980 if bkms.has_key(ps):
2986 target = bkms[ps]
2981 target = bkms[ps]
2987 print '(bookmark:%s) -> %s' % (ps,target)
2982 print '(bookmark:%s) -> %s' % (ps,target)
2988 ps = target
2983 ps = target
2989 else:
2984 else:
2990 if opts.has_key('b'):
2985 if opts.has_key('b'):
2991 raise UsageError("Bookmark '%s' not found. "
2986 raise UsageError("Bookmark '%s' not found. "
2992 "Use '%%bookmark -l' to see your bookmarks." % ps)
2987 "Use '%%bookmark -l' to see your bookmarks." % ps)
2993
2988
2994 # strip extra quotes on Windows, because os.chdir doesn't like them
2989 # strip extra quotes on Windows, because os.chdir doesn't like them
2995 ps = unquote_filename(ps)
2990 ps = unquote_filename(ps)
2996 # at this point ps should point to the target dir
2991 # at this point ps should point to the target dir
2997 if ps:
2992 if ps:
2998 try:
2993 try:
2999 os.chdir(os.path.expanduser(ps))
2994 os.chdir(os.path.expanduser(ps))
3000 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2995 if hasattr(self.shell, 'term_title') and self.shell.term_title:
3001 set_term_title('IPython: ' + abbrev_cwd())
2996 set_term_title('IPython: ' + abbrev_cwd())
3002 except OSError:
2997 except OSError:
3003 print sys.exc_info()[1]
2998 print sys.exc_info()[1]
3004 else:
2999 else:
3005 cwd = os.getcwdu()
3000 cwd = os.getcwdu()
3006 dhist = self.shell.user_ns['_dh']
3001 dhist = self.shell.user_ns['_dh']
3007 if oldcwd != cwd:
3002 if oldcwd != cwd:
3008 dhist.append(cwd)
3003 dhist.append(cwd)
3009 self.db['dhist'] = compress_dhist(dhist)[-100:]
3004 self.db['dhist'] = compress_dhist(dhist)[-100:]
3010
3005
3011 else:
3006 else:
3012 os.chdir(self.shell.home_dir)
3007 os.chdir(self.shell.home_dir)
3013 if hasattr(self.shell, 'term_title') and self.shell.term_title:
3008 if hasattr(self.shell, 'term_title') and self.shell.term_title:
3014 set_term_title('IPython: ' + '~')
3009 set_term_title('IPython: ' + '~')
3015 cwd = os.getcwdu()
3010 cwd = os.getcwdu()
3016 dhist = self.shell.user_ns['_dh']
3011 dhist = self.shell.user_ns['_dh']
3017
3012
3018 if oldcwd != cwd:
3013 if oldcwd != cwd:
3019 dhist.append(cwd)
3014 dhist.append(cwd)
3020 self.db['dhist'] = compress_dhist(dhist)[-100:]
3015 self.db['dhist'] = compress_dhist(dhist)[-100:]
3021 if not 'q' in opts and self.shell.user_ns['_dh']:
3016 if not 'q' in opts and self.shell.user_ns['_dh']:
3022 print self.shell.user_ns['_dh'][-1]
3017 print self.shell.user_ns['_dh'][-1]
3023
3018
3024
3019
3025 def magic_env(self, parameter_s=''):
3020 def magic_env(self, parameter_s=''):
3026 """List environment variables."""
3021 """List environment variables."""
3027
3022
3028 return os.environ.data
3023 return os.environ.data
3029
3024
3030 def magic_pushd(self, parameter_s=''):
3025 def magic_pushd(self, parameter_s=''):
3031 """Place the current dir on stack and change directory.
3026 """Place the current dir on stack and change directory.
3032
3027
3033 Usage:\\
3028 Usage:\\
3034 %pushd ['dirname']
3029 %pushd ['dirname']
3035 """
3030 """
3036
3031
3037 dir_s = self.shell.dir_stack
3032 dir_s = self.shell.dir_stack
3038 tgt = os.path.expanduser(unquote_filename(parameter_s))
3033 tgt = os.path.expanduser(unquote_filename(parameter_s))
3039 cwd = os.getcwdu().replace(self.home_dir,'~')
3034 cwd = os.getcwdu().replace(self.home_dir,'~')
3040 if tgt:
3035 if tgt:
3041 self.magic_cd(parameter_s)
3036 self.magic_cd(parameter_s)
3042 dir_s.insert(0,cwd)
3037 dir_s.insert(0,cwd)
3043 return self.magic_dirs()
3038 return self.magic_dirs()
3044
3039
3045 def magic_popd(self, parameter_s=''):
3040 def magic_popd(self, parameter_s=''):
3046 """Change to directory popped off the top of the stack.
3041 """Change to directory popped off the top of the stack.
3047 """
3042 """
3048 if not self.shell.dir_stack:
3043 if not self.shell.dir_stack:
3049 raise UsageError("%popd on empty stack")
3044 raise UsageError("%popd on empty stack")
3050 top = self.shell.dir_stack.pop(0)
3045 top = self.shell.dir_stack.pop(0)
3051 self.magic_cd(top)
3046 self.magic_cd(top)
3052 print "popd ->",top
3047 print "popd ->",top
3053
3048
3054 def magic_dirs(self, parameter_s=''):
3049 def magic_dirs(self, parameter_s=''):
3055 """Return the current directory stack."""
3050 """Return the current directory stack."""
3056
3051
3057 return self.shell.dir_stack
3052 return self.shell.dir_stack
3058
3053
3059 def magic_dhist(self, parameter_s=''):
3054 def magic_dhist(self, parameter_s=''):
3060 """Print your history of visited directories.
3055 """Print your history of visited directories.
3061
3056
3062 %dhist -> print full history\\
3057 %dhist -> print full history\\
3063 %dhist n -> print last n entries only\\
3058 %dhist n -> print last n entries only\\
3064 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
3059 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
3065
3060
3066 This history is automatically maintained by the %cd command, and
3061 This history is automatically maintained by the %cd command, and
3067 always available as the global list variable _dh. You can use %cd -<n>
3062 always available as the global list variable _dh. You can use %cd -<n>
3068 to go to directory number <n>.
3063 to go to directory number <n>.
3069
3064
3070 Note that most of time, you should view directory history by entering
3065 Note that most of time, you should view directory history by entering
3071 cd -<TAB>.
3066 cd -<TAB>.
3072
3067
3073 """
3068 """
3074
3069
3075 dh = self.shell.user_ns['_dh']
3070 dh = self.shell.user_ns['_dh']
3076 if parameter_s:
3071 if parameter_s:
3077 try:
3072 try:
3078 args = map(int,parameter_s.split())
3073 args = map(int,parameter_s.split())
3079 except:
3074 except:
3080 self.arg_err(Magic.magic_dhist)
3075 self.arg_err(Magic.magic_dhist)
3081 return
3076 return
3082 if len(args) == 1:
3077 if len(args) == 1:
3083 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3078 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3084 elif len(args) == 2:
3079 elif len(args) == 2:
3085 ini,fin = args
3080 ini,fin = args
3086 else:
3081 else:
3087 self.arg_err(Magic.magic_dhist)
3082 self.arg_err(Magic.magic_dhist)
3088 return
3083 return
3089 else:
3084 else:
3090 ini,fin = 0,len(dh)
3085 ini,fin = 0,len(dh)
3091 nlprint(dh,
3086 nlprint(dh,
3092 header = 'Directory history (kept in _dh)',
3087 header = 'Directory history (kept in _dh)',
3093 start=ini,stop=fin)
3088 start=ini,stop=fin)
3094
3089
3095 @skip_doctest
3090 @skip_doctest
3096 def magic_sc(self, parameter_s=''):
3091 def magic_sc(self, parameter_s=''):
3097 """Shell capture - execute a shell command and capture its output.
3092 """Shell capture - execute a shell command and capture its output.
3098
3093
3099 DEPRECATED. Suboptimal, retained for backwards compatibility.
3094 DEPRECATED. Suboptimal, retained for backwards compatibility.
3100
3095
3101 You should use the form 'var = !command' instead. Example:
3096 You should use the form 'var = !command' instead. Example:
3102
3097
3103 "%sc -l myfiles = ls ~" should now be written as
3098 "%sc -l myfiles = ls ~" should now be written as
3104
3099
3105 "myfiles = !ls ~"
3100 "myfiles = !ls ~"
3106
3101
3107 myfiles.s, myfiles.l and myfiles.n still apply as documented
3102 myfiles.s, myfiles.l and myfiles.n still apply as documented
3108 below.
3103 below.
3109
3104
3110 --
3105 --
3111 %sc [options] varname=command
3106 %sc [options] varname=command
3112
3107
3113 IPython will run the given command using commands.getoutput(), and
3108 IPython will run the given command using commands.getoutput(), and
3114 will then update the user's interactive namespace with a variable
3109 will then update the user's interactive namespace with a variable
3115 called varname, containing the value of the call. Your command can
3110 called varname, containing the value of the call. Your command can
3116 contain shell wildcards, pipes, etc.
3111 contain shell wildcards, pipes, etc.
3117
3112
3118 The '=' sign in the syntax is mandatory, and the variable name you
3113 The '=' sign in the syntax is mandatory, and the variable name you
3119 supply must follow Python's standard conventions for valid names.
3114 supply must follow Python's standard conventions for valid names.
3120
3115
3121 (A special format without variable name exists for internal use)
3116 (A special format without variable name exists for internal use)
3122
3117
3123 Options:
3118 Options:
3124
3119
3125 -l: list output. Split the output on newlines into a list before
3120 -l: list output. Split the output on newlines into a list before
3126 assigning it to the given variable. By default the output is stored
3121 assigning it to the given variable. By default the output is stored
3127 as a single string.
3122 as a single string.
3128
3123
3129 -v: verbose. Print the contents of the variable.
3124 -v: verbose. Print the contents of the variable.
3130
3125
3131 In most cases you should not need to split as a list, because the
3126 In most cases you should not need to split as a list, because the
3132 returned value is a special type of string which can automatically
3127 returned value is a special type of string which can automatically
3133 provide its contents either as a list (split on newlines) or as a
3128 provide its contents either as a list (split on newlines) or as a
3134 space-separated string. These are convenient, respectively, either
3129 space-separated string. These are convenient, respectively, either
3135 for sequential processing or to be passed to a shell command.
3130 for sequential processing or to be passed to a shell command.
3136
3131
3137 For example::
3132 For example::
3138
3133
3139 # Capture into variable a
3134 # Capture into variable a
3140 In [1]: sc a=ls *py
3135 In [1]: sc a=ls *py
3141
3136
3142 # a is a string with embedded newlines
3137 # a is a string with embedded newlines
3143 In [2]: a
3138 In [2]: a
3144 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3139 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3145
3140
3146 # which can be seen as a list:
3141 # which can be seen as a list:
3147 In [3]: a.l
3142 In [3]: a.l
3148 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3143 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3149
3144
3150 # or as a whitespace-separated string:
3145 # or as a whitespace-separated string:
3151 In [4]: a.s
3146 In [4]: a.s
3152 Out[4]: 'setup.py win32_manual_post_install.py'
3147 Out[4]: 'setup.py win32_manual_post_install.py'
3153
3148
3154 # a.s is useful to pass as a single command line:
3149 # a.s is useful to pass as a single command line:
3155 In [5]: !wc -l $a.s
3150 In [5]: !wc -l $a.s
3156 146 setup.py
3151 146 setup.py
3157 130 win32_manual_post_install.py
3152 130 win32_manual_post_install.py
3158 276 total
3153 276 total
3159
3154
3160 # while the list form is useful to loop over:
3155 # while the list form is useful to loop over:
3161 In [6]: for f in a.l:
3156 In [6]: for f in a.l:
3162 ...: !wc -l $f
3157 ...: !wc -l $f
3163 ...:
3158 ...:
3164 146 setup.py
3159 146 setup.py
3165 130 win32_manual_post_install.py
3160 130 win32_manual_post_install.py
3166
3161
3167 Similarly, the lists returned by the -l option are also special, in
3162 Similarly, the lists returned by the -l option are also special, in
3168 the sense that you can equally invoke the .s attribute on them to
3163 the sense that you can equally invoke the .s attribute on them to
3169 automatically get a whitespace-separated string from their contents::
3164 automatically get a whitespace-separated string from their contents::
3170
3165
3171 In [7]: sc -l b=ls *py
3166 In [7]: sc -l b=ls *py
3172
3167
3173 In [8]: b
3168 In [8]: b
3174 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3169 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3175
3170
3176 In [9]: b.s
3171 In [9]: b.s
3177 Out[9]: 'setup.py win32_manual_post_install.py'
3172 Out[9]: 'setup.py win32_manual_post_install.py'
3178
3173
3179 In summary, both the lists and strings used for output capture have
3174 In summary, both the lists and strings used for output capture have
3180 the following special attributes::
3175 the following special attributes::
3181
3176
3182 .l (or .list) : value as list.
3177 .l (or .list) : value as list.
3183 .n (or .nlstr): value as newline-separated string.
3178 .n (or .nlstr): value as newline-separated string.
3184 .s (or .spstr): value as space-separated string.
3179 .s (or .spstr): value as space-separated string.
3185 """
3180 """
3186
3181
3187 opts,args = self.parse_options(parameter_s,'lv')
3182 opts,args = self.parse_options(parameter_s,'lv')
3188 # Try to get a variable name and command to run
3183 # Try to get a variable name and command to run
3189 try:
3184 try:
3190 # the variable name must be obtained from the parse_options
3185 # the variable name must be obtained from the parse_options
3191 # output, which uses shlex.split to strip options out.
3186 # output, which uses shlex.split to strip options out.
3192 var,_ = args.split('=',1)
3187 var,_ = args.split('=',1)
3193 var = var.strip()
3188 var = var.strip()
3194 # But the command has to be extracted from the original input
3189 # But the command has to be extracted from the original input
3195 # parameter_s, not on what parse_options returns, to avoid the
3190 # parameter_s, not on what parse_options returns, to avoid the
3196 # quote stripping which shlex.split performs on it.
3191 # quote stripping which shlex.split performs on it.
3197 _,cmd = parameter_s.split('=',1)
3192 _,cmd = parameter_s.split('=',1)
3198 except ValueError:
3193 except ValueError:
3199 var,cmd = '',''
3194 var,cmd = '',''
3200 # If all looks ok, proceed
3195 # If all looks ok, proceed
3201 split = 'l' in opts
3196 split = 'l' in opts
3202 out = self.shell.getoutput(cmd, split=split)
3197 out = self.shell.getoutput(cmd, split=split)
3203 if opts.has_key('v'):
3198 if opts.has_key('v'):
3204 print '%s ==\n%s' % (var,pformat(out))
3199 print '%s ==\n%s' % (var,pformat(out))
3205 if var:
3200 if var:
3206 self.shell.user_ns.update({var:out})
3201 self.shell.user_ns.update({var:out})
3207 else:
3202 else:
3208 return out
3203 return out
3209
3204
3210 def magic_sx(self, parameter_s=''):
3205 def magic_sx(self, parameter_s=''):
3211 """Shell execute - run a shell command and capture its output.
3206 """Shell execute - run a shell command and capture its output.
3212
3207
3213 %sx command
3208 %sx command
3214
3209
3215 IPython will run the given command using commands.getoutput(), and
3210 IPython will run the given command using commands.getoutput(), and
3216 return the result formatted as a list (split on '\\n'). Since the
3211 return the result formatted as a list (split on '\\n'). Since the
3217 output is _returned_, it will be stored in ipython's regular output
3212 output is _returned_, it will be stored in ipython's regular output
3218 cache Out[N] and in the '_N' automatic variables.
3213 cache Out[N] and in the '_N' automatic variables.
3219
3214
3220 Notes:
3215 Notes:
3221
3216
3222 1) If an input line begins with '!!', then %sx is automatically
3217 1) If an input line begins with '!!', then %sx is automatically
3223 invoked. That is, while::
3218 invoked. That is, while::
3224
3219
3225 !ls
3220 !ls
3226
3221
3227 causes ipython to simply issue system('ls'), typing::
3222 causes ipython to simply issue system('ls'), typing::
3228
3223
3229 !!ls
3224 !!ls
3230
3225
3231 is a shorthand equivalent to::
3226 is a shorthand equivalent to::
3232
3227
3233 %sx ls
3228 %sx ls
3234
3229
3235 2) %sx differs from %sc in that %sx automatically splits into a list,
3230 2) %sx differs from %sc in that %sx automatically splits into a list,
3236 like '%sc -l'. The reason for this is to make it as easy as possible
3231 like '%sc -l'. The reason for this is to make it as easy as possible
3237 to process line-oriented shell output via further python commands.
3232 to process line-oriented shell output via further python commands.
3238 %sc is meant to provide much finer control, but requires more
3233 %sc is meant to provide much finer control, but requires more
3239 typing.
3234 typing.
3240
3235
3241 3) Just like %sc -l, this is a list with special attributes:
3236 3) Just like %sc -l, this is a list with special attributes:
3242 ::
3237 ::
3243
3238
3244 .l (or .list) : value as list.
3239 .l (or .list) : value as list.
3245 .n (or .nlstr): value as newline-separated string.
3240 .n (or .nlstr): value as newline-separated string.
3246 .s (or .spstr): value as whitespace-separated string.
3241 .s (or .spstr): value as whitespace-separated string.
3247
3242
3248 This is very useful when trying to use such lists as arguments to
3243 This is very useful when trying to use such lists as arguments to
3249 system commands."""
3244 system commands."""
3250
3245
3251 if parameter_s:
3246 if parameter_s:
3252 return self.shell.getoutput(parameter_s)
3247 return self.shell.getoutput(parameter_s)
3253
3248
3254
3249
3255 def magic_bookmark(self, parameter_s=''):
3250 def magic_bookmark(self, parameter_s=''):
3256 """Manage IPython's bookmark system.
3251 """Manage IPython's bookmark system.
3257
3252
3258 %bookmark <name> - set bookmark to current dir
3253 %bookmark <name> - set bookmark to current dir
3259 %bookmark <name> <dir> - set bookmark to <dir>
3254 %bookmark <name> <dir> - set bookmark to <dir>
3260 %bookmark -l - list all bookmarks
3255 %bookmark -l - list all bookmarks
3261 %bookmark -d <name> - remove bookmark
3256 %bookmark -d <name> - remove bookmark
3262 %bookmark -r - remove all bookmarks
3257 %bookmark -r - remove all bookmarks
3263
3258
3264 You can later on access a bookmarked folder with::
3259 You can later on access a bookmarked folder with::
3265
3260
3266 %cd -b <name>
3261 %cd -b <name>
3267
3262
3268 or simply '%cd <name>' if there is no directory called <name> AND
3263 or simply '%cd <name>' if there is no directory called <name> AND
3269 there is such a bookmark defined.
3264 there is such a bookmark defined.
3270
3265
3271 Your bookmarks persist through IPython sessions, but they are
3266 Your bookmarks persist through IPython sessions, but they are
3272 associated with each profile."""
3267 associated with each profile."""
3273
3268
3274 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3269 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3275 if len(args) > 2:
3270 if len(args) > 2:
3276 raise UsageError("%bookmark: too many arguments")
3271 raise UsageError("%bookmark: too many arguments")
3277
3272
3278 bkms = self.db.get('bookmarks',{})
3273 bkms = self.db.get('bookmarks',{})
3279
3274
3280 if opts.has_key('d'):
3275 if opts.has_key('d'):
3281 try:
3276 try:
3282 todel = args[0]
3277 todel = args[0]
3283 except IndexError:
3278 except IndexError:
3284 raise UsageError(
3279 raise UsageError(
3285 "%bookmark -d: must provide a bookmark to delete")
3280 "%bookmark -d: must provide a bookmark to delete")
3286 else:
3281 else:
3287 try:
3282 try:
3288 del bkms[todel]
3283 del bkms[todel]
3289 except KeyError:
3284 except KeyError:
3290 raise UsageError(
3285 raise UsageError(
3291 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3286 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3292
3287
3293 elif opts.has_key('r'):
3288 elif opts.has_key('r'):
3294 bkms = {}
3289 bkms = {}
3295 elif opts.has_key('l'):
3290 elif opts.has_key('l'):
3296 bks = bkms.keys()
3291 bks = bkms.keys()
3297 bks.sort()
3292 bks.sort()
3298 if bks:
3293 if bks:
3299 size = max(map(len,bks))
3294 size = max(map(len,bks))
3300 else:
3295 else:
3301 size = 0
3296 size = 0
3302 fmt = '%-'+str(size)+'s -> %s'
3297 fmt = '%-'+str(size)+'s -> %s'
3303 print 'Current bookmarks:'
3298 print 'Current bookmarks:'
3304 for bk in bks:
3299 for bk in bks:
3305 print fmt % (bk,bkms[bk])
3300 print fmt % (bk,bkms[bk])
3306 else:
3301 else:
3307 if not args:
3302 if not args:
3308 raise UsageError("%bookmark: You must specify the bookmark name")
3303 raise UsageError("%bookmark: You must specify the bookmark name")
3309 elif len(args)==1:
3304 elif len(args)==1:
3310 bkms[args[0]] = os.getcwdu()
3305 bkms[args[0]] = os.getcwdu()
3311 elif len(args)==2:
3306 elif len(args)==2:
3312 bkms[args[0]] = args[1]
3307 bkms[args[0]] = args[1]
3313 self.db['bookmarks'] = bkms
3308 self.db['bookmarks'] = bkms
3314
3309
3315 def magic_pycat(self, parameter_s=''):
3310 def magic_pycat(self, parameter_s=''):
3316 """Show a syntax-highlighted file through a pager.
3311 """Show a syntax-highlighted file through a pager.
3317
3312
3318 This magic is similar to the cat utility, but it will assume the file
3313 This magic is similar to the cat utility, but it will assume the file
3319 to be Python source and will show it with syntax highlighting. """
3314 to be Python source and will show it with syntax highlighting. """
3320
3315
3321 try:
3316 try:
3322 filename = get_py_filename(parameter_s)
3317 filename = get_py_filename(parameter_s)
3323 cont = file_read(filename)
3318 cont = file_read(filename)
3324 except IOError:
3319 except IOError:
3325 try:
3320 try:
3326 cont = eval(parameter_s,self.user_ns)
3321 cont = eval(parameter_s,self.user_ns)
3327 except NameError:
3322 except NameError:
3328 cont = None
3323 cont = None
3329 if cont is None:
3324 if cont is None:
3330 print "Error: no such file or variable"
3325 print "Error: no such file or variable"
3331 return
3326 return
3332
3327
3333 page.page(self.shell.pycolorize(cont))
3328 page.page(self.shell.pycolorize(cont))
3334
3329
3335 def magic_quickref(self,arg):
3330 def magic_quickref(self,arg):
3336 """ Show a quick reference sheet """
3331 """ Show a quick reference sheet """
3337 import IPython.core.usage
3332 import IPython.core.usage
3338 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3333 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3339
3334
3340 page.page(qr)
3335 page.page(qr)
3341
3336
3342 def magic_doctest_mode(self,parameter_s=''):
3337 def magic_doctest_mode(self,parameter_s=''):
3343 """Toggle doctest mode on and off.
3338 """Toggle doctest mode on and off.
3344
3339
3345 This mode is intended to make IPython behave as much as possible like a
3340 This mode is intended to make IPython behave as much as possible like a
3346 plain Python shell, from the perspective of how its prompts, exceptions
3341 plain Python shell, from the perspective of how its prompts, exceptions
3347 and output look. This makes it easy to copy and paste parts of a
3342 and output look. This makes it easy to copy and paste parts of a
3348 session into doctests. It does so by:
3343 session into doctests. It does so by:
3349
3344
3350 - Changing the prompts to the classic ``>>>`` ones.
3345 - Changing the prompts to the classic ``>>>`` ones.
3351 - Changing the exception reporting mode to 'Plain'.
3346 - Changing the exception reporting mode to 'Plain'.
3352 - Disabling pretty-printing of output.
3347 - Disabling pretty-printing of output.
3353
3348
3354 Note that IPython also supports the pasting of code snippets that have
3349 Note that IPython also supports the pasting of code snippets that have
3355 leading '>>>' and '...' prompts in them. This means that you can paste
3350 leading '>>>' and '...' prompts in them. This means that you can paste
3356 doctests from files or docstrings (even if they have leading
3351 doctests from files or docstrings (even if they have leading
3357 whitespace), and the code will execute correctly. You can then use
3352 whitespace), and the code will execute correctly. You can then use
3358 '%history -t' to see the translated history; this will give you the
3353 '%history -t' to see the translated history; this will give you the
3359 input after removal of all the leading prompts and whitespace, which
3354 input after removal of all the leading prompts and whitespace, which
3360 can be pasted back into an editor.
3355 can be pasted back into an editor.
3361
3356
3362 With these features, you can switch into this mode easily whenever you
3357 With these features, you can switch into this mode easily whenever you
3363 need to do testing and changes to doctests, without having to leave
3358 need to do testing and changes to doctests, without having to leave
3364 your existing IPython session.
3359 your existing IPython session.
3365 """
3360 """
3366
3361
3367 from IPython.utils.ipstruct import Struct
3362 from IPython.utils.ipstruct import Struct
3368
3363
3369 # Shorthands
3364 # Shorthands
3370 shell = self.shell
3365 shell = self.shell
3371 pm = shell.prompt_manager
3366 pm = shell.prompt_manager
3372 meta = shell.meta
3367 meta = shell.meta
3373 disp_formatter = self.shell.display_formatter
3368 disp_formatter = self.shell.display_formatter
3374 ptformatter = disp_formatter.formatters['text/plain']
3369 ptformatter = disp_formatter.formatters['text/plain']
3375 # dstore is a data store kept in the instance metadata bag to track any
3370 # dstore is a data store kept in the instance metadata bag to track any
3376 # changes we make, so we can undo them later.
3371 # changes we make, so we can undo them later.
3377 dstore = meta.setdefault('doctest_mode',Struct())
3372 dstore = meta.setdefault('doctest_mode',Struct())
3378 save_dstore = dstore.setdefault
3373 save_dstore = dstore.setdefault
3379
3374
3380 # save a few values we'll need to recover later
3375 # save a few values we'll need to recover later
3381 mode = save_dstore('mode',False)
3376 mode = save_dstore('mode',False)
3382 save_dstore('rc_pprint',ptformatter.pprint)
3377 save_dstore('rc_pprint',ptformatter.pprint)
3383 save_dstore('xmode',shell.InteractiveTB.mode)
3378 save_dstore('xmode',shell.InteractiveTB.mode)
3384 save_dstore('rc_separate_out',shell.separate_out)
3379 save_dstore('rc_separate_out',shell.separate_out)
3385 save_dstore('rc_separate_out2',shell.separate_out2)
3380 save_dstore('rc_separate_out2',shell.separate_out2)
3386 save_dstore('rc_prompts_pad_left',pm.justify)
3381 save_dstore('rc_prompts_pad_left',pm.justify)
3387 save_dstore('rc_separate_in',shell.separate_in)
3382 save_dstore('rc_separate_in',shell.separate_in)
3388 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3383 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3389 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3384 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3390
3385
3391 if mode == False:
3386 if mode == False:
3392 # turn on
3387 # turn on
3393 pm.in_template = '>>> '
3388 pm.in_template = '>>> '
3394 pm.in2_template = '... '
3389 pm.in2_template = '... '
3395 pm.out_template = ''
3390 pm.out_template = ''
3396
3391
3397 # Prompt separators like plain python
3392 # Prompt separators like plain python
3398 shell.separate_in = ''
3393 shell.separate_in = ''
3399 shell.separate_out = ''
3394 shell.separate_out = ''
3400 shell.separate_out2 = ''
3395 shell.separate_out2 = ''
3401
3396
3402 pm.justify = False
3397 pm.justify = False
3403
3398
3404 ptformatter.pprint = False
3399 ptformatter.pprint = False
3405 disp_formatter.plain_text_only = True
3400 disp_formatter.plain_text_only = True
3406
3401
3407 shell.magic_xmode('Plain')
3402 shell.magic_xmode('Plain')
3408 else:
3403 else:
3409 # turn off
3404 # turn off
3410 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3405 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3411
3406
3412 shell.separate_in = dstore.rc_separate_in
3407 shell.separate_in = dstore.rc_separate_in
3413
3408
3414 shell.separate_out = dstore.rc_separate_out
3409 shell.separate_out = dstore.rc_separate_out
3415 shell.separate_out2 = dstore.rc_separate_out2
3410 shell.separate_out2 = dstore.rc_separate_out2
3416
3411
3417 pm.justify = dstore.rc_prompts_pad_left
3412 pm.justify = dstore.rc_prompts_pad_left
3418
3413
3419 ptformatter.pprint = dstore.rc_pprint
3414 ptformatter.pprint = dstore.rc_pprint
3420 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3415 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3421
3416
3422 shell.magic_xmode(dstore.xmode)
3417 shell.magic_xmode(dstore.xmode)
3423
3418
3424 # Store new mode and inform
3419 # Store new mode and inform
3425 dstore.mode = bool(1-int(mode))
3420 dstore.mode = bool(1-int(mode))
3426 mode_label = ['OFF','ON'][dstore.mode]
3421 mode_label = ['OFF','ON'][dstore.mode]
3427 print 'Doctest mode is:', mode_label
3422 print 'Doctest mode is:', mode_label
3428
3423
3429 def magic_gui(self, parameter_s=''):
3424 def magic_gui(self, parameter_s=''):
3430 """Enable or disable IPython GUI event loop integration.
3425 """Enable or disable IPython GUI event loop integration.
3431
3426
3432 %gui [GUINAME]
3427 %gui [GUINAME]
3433
3428
3434 This magic replaces IPython's threaded shells that were activated
3429 This magic replaces IPython's threaded shells that were activated
3435 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3430 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3436 can now be enabled at runtime and keyboard
3431 can now be enabled at runtime and keyboard
3437 interrupts should work without any problems. The following toolkits
3432 interrupts should work without any problems. The following toolkits
3438 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3433 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3439
3434
3440 %gui wx # enable wxPython event loop integration
3435 %gui wx # enable wxPython event loop integration
3441 %gui qt4|qt # enable PyQt4 event loop integration
3436 %gui qt4|qt # enable PyQt4 event loop integration
3442 %gui gtk # enable PyGTK event loop integration
3437 %gui gtk # enable PyGTK event loop integration
3443 %gui tk # enable Tk event loop integration
3438 %gui tk # enable Tk event loop integration
3444 %gui OSX # enable Cocoa event loop integration
3439 %gui OSX # enable Cocoa event loop integration
3445 # (requires %matplotlib 1.1)
3440 # (requires %matplotlib 1.1)
3446 %gui # disable all event loop integration
3441 %gui # disable all event loop integration
3447
3442
3448 WARNING: after any of these has been called you can simply create
3443 WARNING: after any of these has been called you can simply create
3449 an application object, but DO NOT start the event loop yourself, as
3444 an application object, but DO NOT start the event loop yourself, as
3450 we have already handled that.
3445 we have already handled that.
3451 """
3446 """
3452 opts, arg = self.parse_options(parameter_s, '')
3447 opts, arg = self.parse_options(parameter_s, '')
3453 if arg=='': arg = None
3448 if arg=='': arg = None
3454 try:
3449 try:
3455 return self.enable_gui(arg)
3450 return self.enable_gui(arg)
3456 except Exception as e:
3451 except Exception as e:
3457 # print simple error message, rather than traceback if we can't
3452 # print simple error message, rather than traceback if we can't
3458 # hook up the GUI
3453 # hook up the GUI
3459 error(str(e))
3454 error(str(e))
3460
3455
3461 def magic_install_ext(self, parameter_s):
3456 def magic_install_ext(self, parameter_s):
3462 """Download and install an extension from a URL, e.g.::
3457 """Download and install an extension from a URL, e.g.::
3463
3458
3464 %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py
3459 %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py
3465
3460
3466 The URL should point to an importable Python module - either a .py file
3461 The URL should point to an importable Python module - either a .py file
3467 or a .zip file.
3462 or a .zip file.
3468
3463
3469 Parameters:
3464 Parameters:
3470
3465
3471 -n filename : Specify a name for the file, rather than taking it from
3466 -n filename : Specify a name for the file, rather than taking it from
3472 the URL.
3467 the URL.
3473 """
3468 """
3474 opts, args = self.parse_options(parameter_s, 'n:')
3469 opts, args = self.parse_options(parameter_s, 'n:')
3475 try:
3470 try:
3476 filename, headers = self.extension_manager.install_extension(args, opts.get('n'))
3471 filename, headers = self.extension_manager.install_extension(args, opts.get('n'))
3477 except ValueError as e:
3472 except ValueError as e:
3478 print e
3473 print e
3479 return
3474 return
3480
3475
3481 filename = os.path.basename(filename)
3476 filename = os.path.basename(filename)
3482 print "Installed %s. To use it, type:" % filename
3477 print "Installed %s. To use it, type:" % filename
3483 print " %%load_ext %s" % os.path.splitext(filename)[0]
3478 print " %%load_ext %s" % os.path.splitext(filename)[0]
3484
3479
3485
3480
3486 def magic_load_ext(self, module_str):
3481 def magic_load_ext(self, module_str):
3487 """Load an IPython extension by its module name."""
3482 """Load an IPython extension by its module name."""
3488 return self.extension_manager.load_extension(module_str)
3483 return self.extension_manager.load_extension(module_str)
3489
3484
3490 def magic_unload_ext(self, module_str):
3485 def magic_unload_ext(self, module_str):
3491 """Unload an IPython extension by its module name."""
3486 """Unload an IPython extension by its module name."""
3492 self.extension_manager.unload_extension(module_str)
3487 self.extension_manager.unload_extension(module_str)
3493
3488
3494 def magic_reload_ext(self, module_str):
3489 def magic_reload_ext(self, module_str):
3495 """Reload an IPython extension by its module name."""
3490 """Reload an IPython extension by its module name."""
3496 self.extension_manager.reload_extension(module_str)
3491 self.extension_manager.reload_extension(module_str)
3497
3492
3498 def magic_install_profiles(self, s):
3493 def magic_install_profiles(self, s):
3499 """%install_profiles has been deprecated."""
3494 """%install_profiles has been deprecated."""
3500 print '\n'.join([
3495 print '\n'.join([
3501 "%install_profiles has been deprecated.",
3496 "%install_profiles has been deprecated.",
3502 "Use `ipython profile list` to view available profiles.",
3497 "Use `ipython profile list` to view available profiles.",
3503 "Requesting a profile with `ipython profile create <name>`",
3498 "Requesting a profile with `ipython profile create <name>`",
3504 "or `ipython --profile=<name>` will start with the bundled",
3499 "or `ipython --profile=<name>` will start with the bundled",
3505 "profile of that name if it exists."
3500 "profile of that name if it exists."
3506 ])
3501 ])
3507
3502
3508 def magic_install_default_config(self, s):
3503 def magic_install_default_config(self, s):
3509 """%install_default_config has been deprecated."""
3504 """%install_default_config has been deprecated."""
3510 print '\n'.join([
3505 print '\n'.join([
3511 "%install_default_config has been deprecated.",
3506 "%install_default_config has been deprecated.",
3512 "Use `ipython profile create <name>` to initialize a profile",
3507 "Use `ipython profile create <name>` to initialize a profile",
3513 "with the default config files.",
3508 "with the default config files.",
3514 "Add `--reset` to overwrite already existing config files with defaults."
3509 "Add `--reset` to overwrite already existing config files with defaults."
3515 ])
3510 ])
3516
3511
3517 # Pylab support: simple wrappers that activate pylab, load gui input
3512 # Pylab support: simple wrappers that activate pylab, load gui input
3518 # handling and modify slightly %run
3513 # handling and modify slightly %run
3519
3514
3520 @skip_doctest
3515 @skip_doctest
3521 def _pylab_magic_run(self, parameter_s=''):
3516 def _pylab_magic_run(self, parameter_s=''):
3522 Magic.magic_run(self, parameter_s,
3517 Magic.magic_run(self, parameter_s,
3523 runner=mpl_runner(self.shell.safe_execfile))
3518 runner=mpl_runner(self.shell.safe_execfile))
3524
3519
3525 _pylab_magic_run.__doc__ = magic_run.__doc__
3520 _pylab_magic_run.__doc__ = magic_run.__doc__
3526
3521
3527 @skip_doctest
3522 @skip_doctest
3528 def magic_pylab(self, s):
3523 def magic_pylab(self, s):
3529 """Load numpy and matplotlib to work interactively.
3524 """Load numpy and matplotlib to work interactively.
3530
3525
3531 %pylab [GUINAME]
3526 %pylab [GUINAME]
3532
3527
3533 This function lets you activate pylab (matplotlib, numpy and
3528 This function lets you activate pylab (matplotlib, numpy and
3534 interactive support) at any point during an IPython session.
3529 interactive support) at any point during an IPython session.
3535
3530
3536 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3531 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3537 pylab and mlab, as well as all names from numpy and pylab.
3532 pylab and mlab, as well as all names from numpy and pylab.
3538
3533
3539 If you are using the inline matplotlib backend for embedded figures,
3534 If you are using the inline matplotlib backend for embedded figures,
3540 you can adjust its behavior via the %config magic::
3535 you can adjust its behavior via the %config magic::
3541
3536
3542 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3537 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3543 In [1]: %config InlineBackend.figure_format = 'svg'
3538 In [1]: %config InlineBackend.figure_format = 'svg'
3544
3539
3545 # change the behavior of closing all figures at the end of each
3540 # change the behavior of closing all figures at the end of each
3546 # execution (cell), or allowing reuse of active figures across
3541 # execution (cell), or allowing reuse of active figures across
3547 # cells:
3542 # cells:
3548 In [2]: %config InlineBackend.close_figures = False
3543 In [2]: %config InlineBackend.close_figures = False
3549
3544
3550 Parameters
3545 Parameters
3551 ----------
3546 ----------
3552 guiname : optional
3547 guiname : optional
3553 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3548 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3554 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3549 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3555 used, otherwise matplotlib's default (which you can override in your
3550 used, otherwise matplotlib's default (which you can override in your
3556 matplotlib config file) is used.
3551 matplotlib config file) is used.
3557
3552
3558 Examples
3553 Examples
3559 --------
3554 --------
3560 In this case, where the MPL default is TkAgg::
3555 In this case, where the MPL default is TkAgg::
3561
3556
3562 In [2]: %pylab
3557 In [2]: %pylab
3563
3558
3564 Welcome to pylab, a matplotlib-based Python environment.
3559 Welcome to pylab, a matplotlib-based Python environment.
3565 Backend in use: TkAgg
3560 Backend in use: TkAgg
3566 For more information, type 'help(pylab)'.
3561 For more information, type 'help(pylab)'.
3567
3562
3568 But you can explicitly request a different backend::
3563 But you can explicitly request a different backend::
3569
3564
3570 In [3]: %pylab qt
3565 In [3]: %pylab qt
3571
3566
3572 Welcome to pylab, a matplotlib-based Python environment.
3567 Welcome to pylab, a matplotlib-based Python environment.
3573 Backend in use: Qt4Agg
3568 Backend in use: Qt4Agg
3574 For more information, type 'help(pylab)'.
3569 For more information, type 'help(pylab)'.
3575 """
3570 """
3576
3571
3577 if Application.initialized():
3572 if Application.initialized():
3578 app = Application.instance()
3573 app = Application.instance()
3579 try:
3574 try:
3580 import_all_status = app.pylab_import_all
3575 import_all_status = app.pylab_import_all
3581 except AttributeError:
3576 except AttributeError:
3582 import_all_status = True
3577 import_all_status = True
3583 else:
3578 else:
3584 import_all_status = True
3579 import_all_status = True
3585
3580
3586 self.shell.enable_pylab(s, import_all=import_all_status)
3581 self.shell.enable_pylab(s, import_all=import_all_status)
3587
3582
3588 def magic_tb(self, s):
3583 def magic_tb(self, s):
3589 """Print the last traceback with the currently active exception mode.
3584 """Print the last traceback with the currently active exception mode.
3590
3585
3591 See %xmode for changing exception reporting modes."""
3586 See %xmode for changing exception reporting modes."""
3592 self.shell.showtraceback()
3587 self.shell.showtraceback()
3593
3588
3594 @skip_doctest
3589 @skip_doctest
3595 def magic_precision(self, s=''):
3590 def magic_precision(self, s=''):
3596 """Set floating point precision for pretty printing.
3591 """Set floating point precision for pretty printing.
3597
3592
3598 Can set either integer precision or a format string.
3593 Can set either integer precision or a format string.
3599
3594
3600 If numpy has been imported and precision is an int,
3595 If numpy has been imported and precision is an int,
3601 numpy display precision will also be set, via ``numpy.set_printoptions``.
3596 numpy display precision will also be set, via ``numpy.set_printoptions``.
3602
3597
3603 If no argument is given, defaults will be restored.
3598 If no argument is given, defaults will be restored.
3604
3599
3605 Examples
3600 Examples
3606 --------
3601 --------
3607 ::
3602 ::
3608
3603
3609 In [1]: from math import pi
3604 In [1]: from math import pi
3610
3605
3611 In [2]: %precision 3
3606 In [2]: %precision 3
3612 Out[2]: u'%.3f'
3607 Out[2]: u'%.3f'
3613
3608
3614 In [3]: pi
3609 In [3]: pi
3615 Out[3]: 3.142
3610 Out[3]: 3.142
3616
3611
3617 In [4]: %precision %i
3612 In [4]: %precision %i
3618 Out[4]: u'%i'
3613 Out[4]: u'%i'
3619
3614
3620 In [5]: pi
3615 In [5]: pi
3621 Out[5]: 3
3616 Out[5]: 3
3622
3617
3623 In [6]: %precision %e
3618 In [6]: %precision %e
3624 Out[6]: u'%e'
3619 Out[6]: u'%e'
3625
3620
3626 In [7]: pi**10
3621 In [7]: pi**10
3627 Out[7]: 9.364805e+04
3622 Out[7]: 9.364805e+04
3628
3623
3629 In [8]: %precision
3624 In [8]: %precision
3630 Out[8]: u'%r'
3625 Out[8]: u'%r'
3631
3626
3632 In [9]: pi**10
3627 In [9]: pi**10
3633 Out[9]: 93648.047476082982
3628 Out[9]: 93648.047476082982
3634
3629
3635 """
3630 """
3636
3631
3637 ptformatter = self.shell.display_formatter.formatters['text/plain']
3632 ptformatter = self.shell.display_formatter.formatters['text/plain']
3638 ptformatter.float_precision = s
3633 ptformatter.float_precision = s
3639 return ptformatter.float_format
3634 return ptformatter.float_format
3640
3635
3641
3636
3642 @magic_arguments.magic_arguments()
3637 @magic_arguments.magic_arguments()
3643 @magic_arguments.argument(
3638 @magic_arguments.argument(
3644 '-e', '--export', action='store_true', default=False,
3639 '-e', '--export', action='store_true', default=False,
3645 help='Export IPython history as a notebook. The filename argument '
3640 help='Export IPython history as a notebook. The filename argument '
3646 'is used to specify the notebook name and format. For example '
3641 'is used to specify the notebook name and format. For example '
3647 'a filename of notebook.ipynb will result in a notebook name '
3642 'a filename of notebook.ipynb will result in a notebook name '
3648 'of "notebook" and a format of "xml". Likewise using a ".json" '
3643 'of "notebook" and a format of "xml". Likewise using a ".json" '
3649 'or ".py" file extension will write the notebook in the json '
3644 'or ".py" file extension will write the notebook in the json '
3650 'or py formats.'
3645 'or py formats.'
3651 )
3646 )
3652 @magic_arguments.argument(
3647 @magic_arguments.argument(
3653 '-f', '--format',
3648 '-f', '--format',
3654 help='Convert an existing IPython notebook to a new format. This option '
3649 help='Convert an existing IPython notebook to a new format. This option '
3655 'specifies the new format and can have the values: xml, json, py. '
3650 'specifies the new format and can have the values: xml, json, py. '
3656 'The target filename is chosen automatically based on the new '
3651 'The target filename is chosen automatically based on the new '
3657 'format. The filename argument gives the name of the source file.'
3652 'format. The filename argument gives the name of the source file.'
3658 )
3653 )
3659 @magic_arguments.argument(
3654 @magic_arguments.argument(
3660 'filename', type=unicode,
3655 'filename', type=unicode,
3661 help='Notebook name or filename'
3656 help='Notebook name or filename'
3662 )
3657 )
3663 def magic_notebook(self, s):
3658 def magic_notebook(self, s):
3664 """Export and convert IPython notebooks.
3659 """Export and convert IPython notebooks.
3665
3660
3666 This function can export the current IPython history to a notebook file
3661 This function can export the current IPython history to a notebook file
3667 or can convert an existing notebook file into a different format. For
3662 or can convert an existing notebook file into a different format. For
3668 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3663 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3669 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3664 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3670 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3665 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3671 formats include (json/ipynb, py).
3666 formats include (json/ipynb, py).
3672 """
3667 """
3673 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3668 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3674
3669
3675 from IPython.nbformat import current
3670 from IPython.nbformat import current
3676 args.filename = unquote_filename(args.filename)
3671 args.filename = unquote_filename(args.filename)
3677 if args.export:
3672 if args.export:
3678 fname, name, format = current.parse_filename(args.filename)
3673 fname, name, format = current.parse_filename(args.filename)
3679 cells = []
3674 cells = []
3680 hist = list(self.history_manager.get_range())
3675 hist = list(self.history_manager.get_range())
3681 for session, prompt_number, input in hist[:-1]:
3676 for session, prompt_number, input in hist[:-1]:
3682 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3677 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3683 worksheet = current.new_worksheet(cells=cells)
3678 worksheet = current.new_worksheet(cells=cells)
3684 nb = current.new_notebook(name=name,worksheets=[worksheet])
3679 nb = current.new_notebook(name=name,worksheets=[worksheet])
3685 with open(fname, 'w') as f:
3680 with open(fname, 'w') as f:
3686 current.write(nb, f, format);
3681 current.write(nb, f, format);
3687 elif args.format is not None:
3682 elif args.format is not None:
3688 old_fname, old_name, old_format = current.parse_filename(args.filename)
3683 old_fname, old_name, old_format = current.parse_filename(args.filename)
3689 new_format = args.format
3684 new_format = args.format
3690 if new_format == u'xml':
3685 if new_format == u'xml':
3691 raise ValueError('Notebooks cannot be written as xml.')
3686 raise ValueError('Notebooks cannot be written as xml.')
3692 elif new_format == u'ipynb' or new_format == u'json':
3687 elif new_format == u'ipynb' or new_format == u'json':
3693 new_fname = old_name + u'.ipynb'
3688 new_fname = old_name + u'.ipynb'
3694 new_format = u'json'
3689 new_format = u'json'
3695 elif new_format == u'py':
3690 elif new_format == u'py':
3696 new_fname = old_name + u'.py'
3691 new_fname = old_name + u'.py'
3697 else:
3692 else:
3698 raise ValueError('Invalid notebook format: %s' % new_format)
3693 raise ValueError('Invalid notebook format: %s' % new_format)
3699 with open(old_fname, 'r') as f:
3694 with open(old_fname, 'r') as f:
3700 s = f.read()
3695 s = f.read()
3701 try:
3696 try:
3702 nb = current.reads(s, old_format)
3697 nb = current.reads(s, old_format)
3703 except:
3698 except:
3704 nb = current.reads(s, u'xml')
3699 nb = current.reads(s, u'xml')
3705 with open(new_fname, 'w') as f:
3700 with open(new_fname, 'w') as f:
3706 current.write(nb, f, new_format)
3701 current.write(nb, f, new_format)
3707
3702
3708 def magic_config(self, s):
3703 def magic_config(self, s):
3709 """configure IPython
3704 """configure IPython
3710
3705
3711 %config Class[.trait=value]
3706 %config Class[.trait=value]
3712
3707
3713 This magic exposes most of the IPython config system. Any
3708 This magic exposes most of the IPython config system. Any
3714 Configurable class should be able to be configured with the simple
3709 Configurable class should be able to be configured with the simple
3715 line::
3710 line::
3716
3711
3717 %config Class.trait=value
3712 %config Class.trait=value
3718
3713
3719 Where `value` will be resolved in the user's namespace, if it is an
3714 Where `value` will be resolved in the user's namespace, if it is an
3720 expression or variable name.
3715 expression or variable name.
3721
3716
3722 Examples
3717 Examples
3723 --------
3718 --------
3724
3719
3725 To see what classes are available for config, pass no arguments::
3720 To see what classes are available for config, pass no arguments::
3726
3721
3727 In [1]: %config
3722 In [1]: %config
3728 Available objects for config:
3723 Available objects for config:
3729 TerminalInteractiveShell
3724 TerminalInteractiveShell
3730 HistoryManager
3725 HistoryManager
3731 PrefilterManager
3726 PrefilterManager
3732 AliasManager
3727 AliasManager
3733 IPCompleter
3728 IPCompleter
3734 PromptManager
3729 PromptManager
3735 DisplayFormatter
3730 DisplayFormatter
3736
3731
3737 To view what is configurable on a given class, just pass the class
3732 To view what is configurable on a given class, just pass the class
3738 name::
3733 name::
3739
3734
3740 In [2]: %config IPCompleter
3735 In [2]: %config IPCompleter
3741 IPCompleter options
3736 IPCompleter options
3742 -----------------
3737 -----------------
3743 IPCompleter.omit__names=<Enum>
3738 IPCompleter.omit__names=<Enum>
3744 Current: 2
3739 Current: 2
3745 Choices: (0, 1, 2)
3740 Choices: (0, 1, 2)
3746 Instruct the completer to omit private method names
3741 Instruct the completer to omit private method names
3747 Specifically, when completing on ``object.<tab>``.
3742 Specifically, when completing on ``object.<tab>``.
3748 When 2 [default]: all names that start with '_' will be excluded.
3743 When 2 [default]: all names that start with '_' will be excluded.
3749 When 1: all 'magic' names (``__foo__``) will be excluded.
3744 When 1: all 'magic' names (``__foo__``) will be excluded.
3750 When 0: nothing will be excluded.
3745 When 0: nothing will be excluded.
3751 IPCompleter.merge_completions=<CBool>
3746 IPCompleter.merge_completions=<CBool>
3752 Current: True
3747 Current: True
3753 Whether to merge completion results into a single list
3748 Whether to merge completion results into a single list
3754 If False, only the completion results from the first non-empty completer
3749 If False, only the completion results from the first non-empty completer
3755 will be returned.
3750 will be returned.
3756 IPCompleter.greedy=<CBool>
3751 IPCompleter.greedy=<CBool>
3757 Current: False
3752 Current: False
3758 Activate greedy completion
3753 Activate greedy completion
3759 This will enable completion on elements of lists, results of function calls,
3754 This will enable completion on elements of lists, results of function calls,
3760 etc., but can be unsafe because the code is actually evaluated on TAB.
3755 etc., but can be unsafe because the code is actually evaluated on TAB.
3761
3756
3762 but the real use is in setting values::
3757 but the real use is in setting values::
3763
3758
3764 In [3]: %config IPCompleter.greedy = True
3759 In [3]: %config IPCompleter.greedy = True
3765
3760
3766 and these values are read from the user_ns if they are variables::
3761 and these values are read from the user_ns if they are variables::
3767
3762
3768 In [4]: feeling_greedy=False
3763 In [4]: feeling_greedy=False
3769
3764
3770 In [5]: %config IPCompleter.greedy = feeling_greedy
3765 In [5]: %config IPCompleter.greedy = feeling_greedy
3771
3766
3772 """
3767 """
3773 from IPython.config.loader import Config
3768 from IPython.config.loader import Config
3774 # some IPython objects are Configurable, but do not yet have
3769 # some IPython objects are Configurable, but do not yet have
3775 # any configurable traits. Exclude them from the effects of
3770 # any configurable traits. Exclude them from the effects of
3776 # this magic, as their presence is just noise:
3771 # this magic, as their presence is just noise:
3777 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3772 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3778 classnames = [ c.__class__.__name__ for c in configurables ]
3773 classnames = [ c.__class__.__name__ for c in configurables ]
3779
3774
3780 line = s.strip()
3775 line = s.strip()
3781 if not line:
3776 if not line:
3782 # print available configurable names
3777 # print available configurable names
3783 print "Available objects for config:"
3778 print "Available objects for config:"
3784 for name in classnames:
3779 for name in classnames:
3785 print " ", name
3780 print " ", name
3786 return
3781 return
3787 elif line in classnames:
3782 elif line in classnames:
3788 # `%config TerminalInteractiveShell` will print trait info for
3783 # `%config TerminalInteractiveShell` will print trait info for
3789 # TerminalInteractiveShell
3784 # TerminalInteractiveShell
3790 c = configurables[classnames.index(line)]
3785 c = configurables[classnames.index(line)]
3791 cls = c.__class__
3786 cls = c.__class__
3792 help = cls.class_get_help(c)
3787 help = cls.class_get_help(c)
3793 # strip leading '--' from cl-args:
3788 # strip leading '--' from cl-args:
3794 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3789 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3795 print help
3790 print help
3796 return
3791 return
3797 elif '=' not in line:
3792 elif '=' not in line:
3798 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3793 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3799
3794
3800
3795
3801 # otherwise, assume we are setting configurables.
3796 # otherwise, assume we are setting configurables.
3802 # leave quotes on args when splitting, because we want
3797 # leave quotes on args when splitting, because we want
3803 # unquoted args to eval in user_ns
3798 # unquoted args to eval in user_ns
3804 cfg = Config()
3799 cfg = Config()
3805 exec "cfg."+line in locals(), self.user_ns
3800 exec "cfg."+line in locals(), self.user_ns
3806
3801
3807 for configurable in configurables:
3802 for configurable in configurables:
3808 try:
3803 try:
3809 configurable.update_config(cfg)
3804 configurable.update_config(cfg)
3810 except Exception as e:
3805 except Exception as e:
3811 error(e)
3806 error(e)
3812
3807
3813 # end Magic
3808 # end Magic
@@ -1,174 +1,174 b''
1 """Manage IPython.parallel clusters in the notebook.
1 """Manage IPython.parallel clusters in the notebook.
2
2
3 Authors:
3 Authors:
4
4
5 * Brian Granger
5 * Brian Granger
6 """
6 """
7
7
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2008-2011 The IPython Development Team
9 # Copyright (C) 2008-2011 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 import os
19 import os
20
20
21 from tornado import web
21 from tornado import web
22 from zmq.eventloop import ioloop
22 from zmq.eventloop import ioloop
23
23
24 from IPython.config.configurable import LoggingConfigurable
24 from IPython.config.configurable import LoggingConfigurable
25 from IPython.config.loader import load_pyconfig_files
25 from IPython.config.loader import load_pyconfig_files
26 from IPython.utils.traitlets import Dict, Instance, CFloat
26 from IPython.utils.traitlets import Dict, Instance, CFloat
27 from IPython.parallel.apps.ipclusterapp import IPClusterStart
27 from IPython.parallel.apps.ipclusterapp import IPClusterStart
28 from IPython.core.profileapp import list_profiles_in
28 from IPython.core.profileapp import list_profiles_in
29 from IPython.core.profiledir import ProfileDir
29 from IPython.core.profiledir import ProfileDir
30 from IPython.utils.path import get_ipython_dir
30 from IPython.utils.path import get_ipython_dir
31 from IPython.utils.sysinfo import num_cpus
31 from IPython.utils.sysinfo import num_cpus
32
32
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Classes
35 # Classes
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 class DummyIPClusterStart(IPClusterStart):
39 class DummyIPClusterStart(IPClusterStart):
40 """Dummy subclass to skip init steps that conflict with global app.
40 """Dummy subclass to skip init steps that conflict with global app.
41
41
42 Instantiating and initializing this class should result in fully configured
42 Instantiating and initializing this class should result in fully configured
43 launchers, but no other side effects or state.
43 launchers, but no other side effects or state.
44 """
44 """
45
45
46 def init_signal(self):
46 def init_signal(self):
47 pass
47 pass
48 def init_logging(self):
48 def init_logging(self):
49 pass
49 pass
50 def reinit_logging(self):
50 def reinit_logging(self):
51 pass
51 pass
52
52
53
53
54 class ClusterManager(LoggingConfigurable):
54 class ClusterManager(LoggingConfigurable):
55
55
56 profiles = Dict()
56 profiles = Dict()
57
57
58 delay = CFloat(1., config=True,
58 delay = CFloat(1., config=True,
59 help="delay (in s) between starting the controller and the engines")
59 help="delay (in s) between starting the controller and the engines")
60
60
61 loop = Instance('zmq.eventloop.ioloop.IOLoop')
61 loop = Instance('zmq.eventloop.ioloop.IOLoop')
62 def _loop_default(self):
62 def _loop_default(self):
63 from zmq.eventloop.ioloop import IOLoop
63 from zmq.eventloop.ioloop import IOLoop
64 return IOLoop.instance()
64 return IOLoop.instance()
65
65
66 def build_launchers(self, profile_dir):
66 def build_launchers(self, profile_dir):
67 starter = DummyIPClusterStart(log=self.log)
67 starter = DummyIPClusterStart(log=self.log)
68 starter.initialize(['--profile-dir', profile_dir])
68 starter.initialize(['--profile-dir', profile_dir])
69 cl = starter.controller_launcher
69 cl = starter.controller_launcher
70 esl = starter.engine_launcher
70 esl = starter.engine_launcher
71 n = starter.n
71 n = starter.n
72 return cl, esl, n
72 return cl, esl, n
73
73
74 def get_profile_dir(self, name, path):
74 def get_profile_dir(self, name, path):
75 p = ProfileDir.find_profile_dir_by_name(path,name=name)
75 p = ProfileDir.find_profile_dir_by_name(path,name=name)
76 return p.location
76 return p.location
77
77
78 def update_profiles(self):
78 def update_profiles(self):
79 """List all profiles in the ipython_dir and cwd.
79 """List all profiles in the ipython_dir and cwd.
80 """
80 """
81 for path in [get_ipython_dir(), os.getcwdu()]:
81 for path in [get_ipython_dir(), os.getcwdu()]:
82 for profile in list_profiles_in(path):
82 for profile in list_profiles_in(path):
83 pd = self.get_profile_dir(profile, path)
83 pd = self.get_profile_dir(profile, path)
84 if profile not in self.profiles:
84 if profile not in self.profiles:
85 self.log.debug("Overwriting profile %s" % profile)
85 self.log.debug("Overwriting profile %s" % profile)
86 self.profiles[profile] = {
86 self.profiles[profile] = {
87 'profile': profile,
87 'profile': profile,
88 'profile_dir': pd,
88 'profile_dir': pd,
89 'status': 'stopped'
89 'status': 'stopped'
90 }
90 }
91
91
92 def list_profiles(self):
92 def list_profiles(self):
93 self.update_profiles()
93 self.update_profiles()
94 result = [self.profile_info(p) for p in sorted(self.profiles.keys())]
94 result = [self.profile_info(p) for p in sorted(self.profiles.keys())]
95 return result
95 return result
96
96
97 def check_profile(self, profile):
97 def check_profile(self, profile):
98 if profile not in self.profiles:
98 if profile not in self.profiles:
99 raise web.HTTPError(404, u'profile not found')
99 raise web.HTTPError(404, u'profile not found')
100
100
101 def profile_info(self, profile):
101 def profile_info(self, profile):
102 self.check_profile(profile)
102 self.check_profile(profile)
103 result = {}
103 result = {}
104 data = self.profiles.get(profile)
104 data = self.profiles.get(profile)
105 result['profile'] = profile
105 result['profile'] = profile
106 result['profile_dir'] = data['profile_dir']
106 result['profile_dir'] = data['profile_dir']
107 result['status'] = data['status']
107 result['status'] = data['status']
108 if 'n' in data:
108 if 'n' in data:
109 result['n'] = data['n']
109 result['n'] = data['n']
110 return result
110 return result
111
111
112 def start_cluster(self, profile, n=None):
112 def start_cluster(self, profile, n=None):
113 """Start a cluster for a given profile."""
113 """Start a cluster for a given profile."""
114 self.check_profile(profile)
114 self.check_profile(profile)
115 data = self.profiles[profile]
115 data = self.profiles[profile]
116 if data['status'] == 'running':
116 if data['status'] == 'running':
117 raise web.HTTPError(409, u'cluster already running')
117 raise web.HTTPError(409, u'cluster already running')
118 cl, esl, default_n = self.build_launchers(data['profile_dir'])
118 cl, esl, default_n = self.build_launchers(data['profile_dir'])
119 n = n if n is not None else default_n
119 n = n if n is not None else default_n
120 def clean_data():
120 def clean_data():
121 data.pop('controller_launcher',None)
121 data.pop('controller_launcher',None)
122 data.pop('engine_set_launcher',None)
122 data.pop('engine_set_launcher',None)
123 data.pop('n',None)
123 data.pop('n',None)
124 data['status'] = 'stopped'
124 data['status'] = 'stopped'
125 def engines_stopped(r):
125 def engines_stopped(r):
126 self.log.debug('Engines stopped')
126 self.log.debug('Engines stopped')
127 if cl.running:
127 if cl.running:
128 cl.stop()
128 cl.stop()
129 clean_data()
129 clean_data()
130 esl.on_stop(engines_stopped)
130 esl.on_stop(engines_stopped)
131 def controller_stopped(r):
131 def controller_stopped(r):
132 self.log.debug('Controller stopped')
132 self.log.debug('Controller stopped')
133 if esl.running:
133 if esl.running:
134 esl.stop()
134 esl.stop()
135 clean_data()
135 clean_data()
136 cl.on_stop(controller_stopped)
136 cl.on_stop(controller_stopped)
137
137
138 dc = ioloop.DelayedCallback(lambda: cl.start(), 0, self.loop)
138 dc = ioloop.DelayedCallback(lambda: cl.start(), 0, self.loop)
139 dc.start()
139 dc.start()
140 dc = ioloop.DelayedCallback(lambda: esl.start(n), 1000*self.delay, self.loop)
140 dc = ioloop.DelayedCallback(lambda: esl.start(n), 1000*self.delay, self.loop)
141 dc.start()
141 dc.start()
142
142
143 self.log.debug('Cluster started')
143 self.log.debug('Cluster started')
144 data['controller_launcher'] = cl
144 data['controller_launcher'] = cl
145 data['engine_set_launcher'] = esl
145 data['engine_set_launcher'] = esl
146 data['n'] = n
146 data['n'] = n
147 data['status'] = 'running'
147 data['status'] = 'running'
148 return self.profile_info(profile)
148 return self.profile_info(profile)
149
149
150 def stop_cluster(self, profile):
150 def stop_cluster(self, profile):
151 """Stop a cluster for a given profile."""
151 """Stop a cluster for a given profile."""
152 self.check_profile(profile)
152 self.check_profile(profile)
153 data = self.profiles[profile]
153 data = self.profiles[profile]
154 if data['status'] == 'stopped':
154 if data['status'] == 'stopped':
155 raise web.HTTPError(409, u'cluster not running')
155 raise web.HTTPError(409, u'cluster not running')
156 data = self.profiles[profile]
156 data = self.profiles[profile]
157 cl = data['controller_launcher']
157 cl = data['controller_launcher']
158 esl = data['engine_set_launcher']
158 esl = data['engine_set_launcher']
159 if cl.running:
159 if cl.running:
160 cl.stop()
160 cl.stop()
161 if esl.running:
161 if esl.running:
162 esl.stop()
162 esl.stop()
163 # Return a temp info dict, the real one is updated in the on_stop
163 # Return a temp info dict, the real one is updated in the on_stop
164 # logic above.
164 # logic above.
165 result = {
165 result = {
166 'profile': data['profile'],
166 'profile': data['profile'],
167 'profile_dir': data['profile_dir'],
167 'profile_dir': data['profile_dir'],
168 'status': 'stopped'
168 'status': 'stopped'
169 }
169 }
170 return result
170 return result
171
171
172 def stop_all_clusters(self):
172 def stop_all_clusters(self):
173 for p in self.profiles.keys():
173 for p in self.profiles.keys():
174 self.stop_cluster(profile)
174 self.stop_cluster(p)
@@ -1,668 +1,668 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import os
19 import os
20 import re
20 import re
21 import sys
21 import sys
22 import textwrap
22 import textwrap
23
23
24 try:
24 try:
25 from contextlib import nested
25 from contextlib import nested
26 except:
26 except:
27 from IPython.utils.nested_context import nested
27 from IPython.utils.nested_context import nested
28
28
29 from IPython.core.error import TryNext
29 from IPython.core.error import TryNext, UsageError
30 from IPython.core.usage import interactive_usage, default_banner
30 from IPython.core.usage import interactive_usage, default_banner
31 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
31 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
32 from IPython.core.pylabtools import pylab_activate
32 from IPython.core.pylabtools import pylab_activate
33 from IPython.testing.skipdoctest import skip_doctest
33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils import py3compat
34 from IPython.utils import py3compat
35 from IPython.utils.terminal import toggle_set_term_title, set_term_title
35 from IPython.utils.terminal import toggle_set_term_title, set_term_title
36 from IPython.utils.process import abbrev_cwd
36 from IPython.utils.process import abbrev_cwd
37 from IPython.utils.warn import warn, error
37 from IPython.utils.warn import warn, error
38 from IPython.utils.text import num_ini_spaces, SList
38 from IPython.utils.text import num_ini_spaces, SList
39 from IPython.utils.traitlets import Integer, CBool, Unicode
39 from IPython.utils.traitlets import Integer, CBool, Unicode
40
40
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Utilities
42 # Utilities
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45 def get_default_editor():
45 def get_default_editor():
46 try:
46 try:
47 ed = os.environ['EDITOR']
47 ed = os.environ['EDITOR']
48 except KeyError:
48 except KeyError:
49 if os.name == 'posix':
49 if os.name == 'posix':
50 ed = 'vi' # the only one guaranteed to be there!
50 ed = 'vi' # the only one guaranteed to be there!
51 else:
51 else:
52 ed = 'notepad' # same in Windows!
52 ed = 'notepad' # same in Windows!
53 return ed
53 return ed
54
54
55
55
56 def get_pasted_lines(sentinel, l_input=py3compat.input):
56 def get_pasted_lines(sentinel, l_input=py3compat.input):
57 """ Yield pasted lines until the user enters the given sentinel value.
57 """ Yield pasted lines until the user enters the given sentinel value.
58 """
58 """
59 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
59 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
60 % sentinel
60 % sentinel
61 while True:
61 while True:
62 try:
62 try:
63 l = l_input(':')
63 l = l_input(':')
64 if l == sentinel:
64 if l == sentinel:
65 return
65 return
66 else:
66 else:
67 yield l
67 yield l
68 except EOFError:
68 except EOFError:
69 print '<EOF>'
69 print '<EOF>'
70 return
70 return
71
71
72
72
73 def strip_email_quotes(raw_lines):
73 def strip_email_quotes(raw_lines):
74 """ Strip email quotation marks at the beginning of each line.
74 """ Strip email quotation marks at the beginning of each line.
75
75
76 We don't do any more input transofrmations here because the main shell's
76 We don't do any more input transofrmations here because the main shell's
77 prefiltering handles other cases.
77 prefiltering handles other cases.
78 """
78 """
79 lines = [re.sub(r'^\s*(\s?>)+', '', l) for l in raw_lines]
79 lines = [re.sub(r'^\s*(\s?>)+', '', l) for l in raw_lines]
80 return '\n'.join(lines) + '\n'
80 return '\n'.join(lines) + '\n'
81
81
82
82
83 # These two functions are needed by the %paste/%cpaste magics. In practice
83 # These two functions are needed by the %paste/%cpaste magics. In practice
84 # they are basically methods (they take the shell as their first argument), but
84 # they are basically methods (they take the shell as their first argument), but
85 # we leave them as standalone functions because eventually the magics
85 # we leave them as standalone functions because eventually the magics
86 # themselves will become separate objects altogether. At that point, the
86 # themselves will become separate objects altogether. At that point, the
87 # magics will have access to the shell object, and these functions can be made
87 # magics will have access to the shell object, and these functions can be made
88 # methods of the magic object, but not of the shell.
88 # methods of the magic object, but not of the shell.
89
89
90 def store_or_execute(shell, block, name):
90 def store_or_execute(shell, block, name):
91 """ Execute a block, or store it in a variable, per the user's request.
91 """ Execute a block, or store it in a variable, per the user's request.
92 """
92 """
93 # Dedent and prefilter so what we store matches what is executed by
93 # Dedent and prefilter so what we store matches what is executed by
94 # run_cell.
94 # run_cell.
95 b = shell.prefilter(textwrap.dedent(block))
95 b = shell.prefilter(textwrap.dedent(block))
96
96
97 if name:
97 if name:
98 # If storing it for further editing, run the prefilter on it
98 # If storing it for further editing, run the prefilter on it
99 shell.user_ns[name] = SList(b.splitlines())
99 shell.user_ns[name] = SList(b.splitlines())
100 print "Block assigned to '%s'" % name
100 print "Block assigned to '%s'" % name
101 else:
101 else:
102 shell.user_ns['pasted_block'] = b
102 shell.user_ns['pasted_block'] = b
103 shell.run_cell(b)
103 shell.run_cell(b)
104
104
105
105
106 def rerun_pasted(shell, name='pasted_block'):
106 def rerun_pasted(shell, name='pasted_block'):
107 """ Rerun a previously pasted command.
107 """ Rerun a previously pasted command.
108 """
108 """
109 b = shell.user_ns.get(name)
109 b = shell.user_ns.get(name)
110
110
111 # Sanity checks
111 # Sanity checks
112 if b is None:
112 if b is None:
113 raise UsageError('No previous pasted block available')
113 raise UsageError('No previous pasted block available')
114 if not isinstance(b, basestring):
114 if not isinstance(b, basestring):
115 raise UsageError(
115 raise UsageError(
116 "Variable 'pasted_block' is not a string, can't execute")
116 "Variable 'pasted_block' is not a string, can't execute")
117
117
118 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
118 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
119 shell.run_cell(b)
119 shell.run_cell(b)
120
120
121
121
122 #-----------------------------------------------------------------------------
122 #-----------------------------------------------------------------------------
123 # Main class
123 # Main class
124 #-----------------------------------------------------------------------------
124 #-----------------------------------------------------------------------------
125
125
126 class TerminalInteractiveShell(InteractiveShell):
126 class TerminalInteractiveShell(InteractiveShell):
127
127
128 autoedit_syntax = CBool(False, config=True,
128 autoedit_syntax = CBool(False, config=True,
129 help="auto editing of files with syntax errors.")
129 help="auto editing of files with syntax errors.")
130 banner = Unicode('')
130 banner = Unicode('')
131 banner1 = Unicode(default_banner, config=True,
131 banner1 = Unicode(default_banner, config=True,
132 help="""The part of the banner to be printed before the profile"""
132 help="""The part of the banner to be printed before the profile"""
133 )
133 )
134 banner2 = Unicode('', config=True,
134 banner2 = Unicode('', config=True,
135 help="""The part of the banner to be printed after the profile"""
135 help="""The part of the banner to be printed after the profile"""
136 )
136 )
137 confirm_exit = CBool(True, config=True,
137 confirm_exit = CBool(True, config=True,
138 help="""
138 help="""
139 Set to confirm when you try to exit IPython with an EOF (Control-D
139 Set to confirm when you try to exit IPython with an EOF (Control-D
140 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
140 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
141 you can force a direct exit without any confirmation.""",
141 you can force a direct exit without any confirmation.""",
142 )
142 )
143 # This display_banner only controls whether or not self.show_banner()
143 # This display_banner only controls whether or not self.show_banner()
144 # is called when mainloop/interact are called. The default is False
144 # is called when mainloop/interact are called. The default is False
145 # because for the terminal based application, the banner behavior
145 # because for the terminal based application, the banner behavior
146 # is controlled by Global.display_banner, which IPythonApp looks at
146 # is controlled by Global.display_banner, which IPythonApp looks at
147 # to determine if *it* should call show_banner() by hand or not.
147 # to determine if *it* should call show_banner() by hand or not.
148 display_banner = CBool(False) # This isn't configurable!
148 display_banner = CBool(False) # This isn't configurable!
149 embedded = CBool(False)
149 embedded = CBool(False)
150 embedded_active = CBool(False)
150 embedded_active = CBool(False)
151 editor = Unicode(get_default_editor(), config=True,
151 editor = Unicode(get_default_editor(), config=True,
152 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
152 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
153 )
153 )
154 pager = Unicode('less', config=True,
154 pager = Unicode('less', config=True,
155 help="The shell program to be used for paging.")
155 help="The shell program to be used for paging.")
156
156
157 screen_length = Integer(0, config=True,
157 screen_length = Integer(0, config=True,
158 help=
158 help=
159 """Number of lines of your screen, used to control printing of very
159 """Number of lines of your screen, used to control printing of very
160 long strings. Strings longer than this number of lines will be sent
160 long strings. Strings longer than this number of lines will be sent
161 through a pager instead of directly printed. The default value for
161 through a pager instead of directly printed. The default value for
162 this is 0, which means IPython will auto-detect your screen size every
162 this is 0, which means IPython will auto-detect your screen size every
163 time it needs to print certain potentially long strings (this doesn't
163 time it needs to print certain potentially long strings (this doesn't
164 change the behavior of the 'print' keyword, it's only triggered
164 change the behavior of the 'print' keyword, it's only triggered
165 internally). If for some reason this isn't working well (it needs
165 internally). If for some reason this isn't working well (it needs
166 curses support), specify it yourself. Otherwise don't change the
166 curses support), specify it yourself. Otherwise don't change the
167 default.""",
167 default.""",
168 )
168 )
169 term_title = CBool(False, config=True,
169 term_title = CBool(False, config=True,
170 help="Enable auto setting the terminal title."
170 help="Enable auto setting the terminal title."
171 )
171 )
172
172
173 # In the terminal, GUI control is done via PyOS_InputHook
173 # In the terminal, GUI control is done via PyOS_InputHook
174 from IPython.lib.inputhook import enable_gui
174 from IPython.lib.inputhook import enable_gui
175 enable_gui = staticmethod(enable_gui)
175 enable_gui = staticmethod(enable_gui)
176
176
177 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
177 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
178 user_ns=None, user_module=None, custom_exceptions=((),None),
178 user_ns=None, user_module=None, custom_exceptions=((),None),
179 usage=None, banner1=None, banner2=None, display_banner=None):
179 usage=None, banner1=None, banner2=None, display_banner=None):
180
180
181 super(TerminalInteractiveShell, self).__init__(
181 super(TerminalInteractiveShell, self).__init__(
182 config=config, profile_dir=profile_dir, user_ns=user_ns,
182 config=config, profile_dir=profile_dir, user_ns=user_ns,
183 user_module=user_module, custom_exceptions=custom_exceptions
183 user_module=user_module, custom_exceptions=custom_exceptions
184 )
184 )
185 # use os.system instead of utils.process.system by default,
185 # use os.system instead of utils.process.system by default,
186 # because piped system doesn't make sense in the Terminal:
186 # because piped system doesn't make sense in the Terminal:
187 self.system = self.system_raw
187 self.system = self.system_raw
188
188
189 self.init_term_title()
189 self.init_term_title()
190 self.init_usage(usage)
190 self.init_usage(usage)
191 self.init_banner(banner1, banner2, display_banner)
191 self.init_banner(banner1, banner2, display_banner)
192
192
193 #-------------------------------------------------------------------------
193 #-------------------------------------------------------------------------
194 # Things related to the terminal
194 # Things related to the terminal
195 #-------------------------------------------------------------------------
195 #-------------------------------------------------------------------------
196
196
197 @property
197 @property
198 def usable_screen_length(self):
198 def usable_screen_length(self):
199 if self.screen_length == 0:
199 if self.screen_length == 0:
200 return 0
200 return 0
201 else:
201 else:
202 num_lines_bot = self.separate_in.count('\n')+1
202 num_lines_bot = self.separate_in.count('\n')+1
203 return self.screen_length - num_lines_bot
203 return self.screen_length - num_lines_bot
204
204
205 def init_term_title(self):
205 def init_term_title(self):
206 # Enable or disable the terminal title.
206 # Enable or disable the terminal title.
207 if self.term_title:
207 if self.term_title:
208 toggle_set_term_title(True)
208 toggle_set_term_title(True)
209 set_term_title('IPython: ' + abbrev_cwd())
209 set_term_title('IPython: ' + abbrev_cwd())
210 else:
210 else:
211 toggle_set_term_title(False)
211 toggle_set_term_title(False)
212
212
213 #-------------------------------------------------------------------------
213 #-------------------------------------------------------------------------
214 # Things related to aliases
214 # Things related to aliases
215 #-------------------------------------------------------------------------
215 #-------------------------------------------------------------------------
216
216
217 def init_alias(self):
217 def init_alias(self):
218 # The parent class defines aliases that can be safely used with any
218 # The parent class defines aliases that can be safely used with any
219 # frontend.
219 # frontend.
220 super(TerminalInteractiveShell, self).init_alias()
220 super(TerminalInteractiveShell, self).init_alias()
221
221
222 # Now define aliases that only make sense on the terminal, because they
222 # Now define aliases that only make sense on the terminal, because they
223 # need direct access to the console in a way that we can't emulate in
223 # need direct access to the console in a way that we can't emulate in
224 # GUI or web frontend
224 # GUI or web frontend
225 if os.name == 'posix':
225 if os.name == 'posix':
226 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
226 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
227 ('man', 'man')]
227 ('man', 'man')]
228 elif os.name == 'nt':
228 elif os.name == 'nt':
229 aliases = [('cls', 'cls')]
229 aliases = [('cls', 'cls')]
230
230
231
231
232 for name, cmd in aliases:
232 for name, cmd in aliases:
233 self.alias_manager.define_alias(name, cmd)
233 self.alias_manager.define_alias(name, cmd)
234
234
235 #-------------------------------------------------------------------------
235 #-------------------------------------------------------------------------
236 # Things related to the banner and usage
236 # Things related to the banner and usage
237 #-------------------------------------------------------------------------
237 #-------------------------------------------------------------------------
238
238
239 def _banner1_changed(self):
239 def _banner1_changed(self):
240 self.compute_banner()
240 self.compute_banner()
241
241
242 def _banner2_changed(self):
242 def _banner2_changed(self):
243 self.compute_banner()
243 self.compute_banner()
244
244
245 def _term_title_changed(self, name, new_value):
245 def _term_title_changed(self, name, new_value):
246 self.init_term_title()
246 self.init_term_title()
247
247
248 def init_banner(self, banner1, banner2, display_banner):
248 def init_banner(self, banner1, banner2, display_banner):
249 if banner1 is not None:
249 if banner1 is not None:
250 self.banner1 = banner1
250 self.banner1 = banner1
251 if banner2 is not None:
251 if banner2 is not None:
252 self.banner2 = banner2
252 self.banner2 = banner2
253 if display_banner is not None:
253 if display_banner is not None:
254 self.display_banner = display_banner
254 self.display_banner = display_banner
255 self.compute_banner()
255 self.compute_banner()
256
256
257 def show_banner(self, banner=None):
257 def show_banner(self, banner=None):
258 if banner is None:
258 if banner is None:
259 banner = self.banner
259 banner = self.banner
260 self.write(banner)
260 self.write(banner)
261
261
262 def compute_banner(self):
262 def compute_banner(self):
263 self.banner = self.banner1
263 self.banner = self.banner1
264 if self.profile and self.profile != 'default':
264 if self.profile and self.profile != 'default':
265 self.banner += '\nIPython profile: %s\n' % self.profile
265 self.banner += '\nIPython profile: %s\n' % self.profile
266 if self.banner2:
266 if self.banner2:
267 self.banner += '\n' + self.banner2
267 self.banner += '\n' + self.banner2
268
268
269 def init_usage(self, usage=None):
269 def init_usage(self, usage=None):
270 if usage is None:
270 if usage is None:
271 self.usage = interactive_usage
271 self.usage = interactive_usage
272 else:
272 else:
273 self.usage = usage
273 self.usage = usage
274
274
275 #-------------------------------------------------------------------------
275 #-------------------------------------------------------------------------
276 # Mainloop and code execution logic
276 # Mainloop and code execution logic
277 #-------------------------------------------------------------------------
277 #-------------------------------------------------------------------------
278
278
279 def mainloop(self, display_banner=None):
279 def mainloop(self, display_banner=None):
280 """Start the mainloop.
280 """Start the mainloop.
281
281
282 If an optional banner argument is given, it will override the
282 If an optional banner argument is given, it will override the
283 internally created default banner.
283 internally created default banner.
284 """
284 """
285
285
286 with nested(self.builtin_trap, self.display_trap):
286 with nested(self.builtin_trap, self.display_trap):
287
287
288 while 1:
288 while 1:
289 try:
289 try:
290 self.interact(display_banner=display_banner)
290 self.interact(display_banner=display_banner)
291 #self.interact_with_readline()
291 #self.interact_with_readline()
292 # XXX for testing of a readline-decoupled repl loop, call
292 # XXX for testing of a readline-decoupled repl loop, call
293 # interact_with_readline above
293 # interact_with_readline above
294 break
294 break
295 except KeyboardInterrupt:
295 except KeyboardInterrupt:
296 # this should not be necessary, but KeyboardInterrupt
296 # this should not be necessary, but KeyboardInterrupt
297 # handling seems rather unpredictable...
297 # handling seems rather unpredictable...
298 self.write("\nKeyboardInterrupt in interact()\n")
298 self.write("\nKeyboardInterrupt in interact()\n")
299
299
300 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
300 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
301 """Store multiple lines as a single entry in history"""
301 """Store multiple lines as a single entry in history"""
302
302
303 # do nothing without readline or disabled multiline
303 # do nothing without readline or disabled multiline
304 if not self.has_readline or not self.multiline_history:
304 if not self.has_readline or not self.multiline_history:
305 return hlen_before_cell
305 return hlen_before_cell
306
306
307 # windows rl has no remove_history_item
307 # windows rl has no remove_history_item
308 if not hasattr(self.readline, "remove_history_item"):
308 if not hasattr(self.readline, "remove_history_item"):
309 return hlen_before_cell
309 return hlen_before_cell
310
310
311 # skip empty cells
311 # skip empty cells
312 if not source_raw.rstrip():
312 if not source_raw.rstrip():
313 return hlen_before_cell
313 return hlen_before_cell
314
314
315 # nothing changed do nothing, e.g. when rl removes consecutive dups
315 # nothing changed do nothing, e.g. when rl removes consecutive dups
316 hlen = self.readline.get_current_history_length()
316 hlen = self.readline.get_current_history_length()
317 if hlen == hlen_before_cell:
317 if hlen == hlen_before_cell:
318 return hlen_before_cell
318 return hlen_before_cell
319
319
320 for i in range(hlen - hlen_before_cell):
320 for i in range(hlen - hlen_before_cell):
321 self.readline.remove_history_item(hlen - i - 1)
321 self.readline.remove_history_item(hlen - i - 1)
322 stdin_encoding = sys.stdin.encoding or "utf-8"
322 stdin_encoding = sys.stdin.encoding or "utf-8"
323 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
323 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
324 stdin_encoding))
324 stdin_encoding))
325 return self.readline.get_current_history_length()
325 return self.readline.get_current_history_length()
326
326
327 def interact(self, display_banner=None):
327 def interact(self, display_banner=None):
328 """Closely emulate the interactive Python console."""
328 """Closely emulate the interactive Python console."""
329
329
330 # batch run -> do not interact
330 # batch run -> do not interact
331 if self.exit_now:
331 if self.exit_now:
332 return
332 return
333
333
334 if display_banner is None:
334 if display_banner is None:
335 display_banner = self.display_banner
335 display_banner = self.display_banner
336
336
337 if isinstance(display_banner, basestring):
337 if isinstance(display_banner, basestring):
338 self.show_banner(display_banner)
338 self.show_banner(display_banner)
339 elif display_banner:
339 elif display_banner:
340 self.show_banner()
340 self.show_banner()
341
341
342 more = False
342 more = False
343
343
344 if self.has_readline:
344 if self.has_readline:
345 self.readline_startup_hook(self.pre_readline)
345 self.readline_startup_hook(self.pre_readline)
346 hlen_b4_cell = self.readline.get_current_history_length()
346 hlen_b4_cell = self.readline.get_current_history_length()
347 else:
347 else:
348 hlen_b4_cell = 0
348 hlen_b4_cell = 0
349 # exit_now is set by a call to %Exit or %Quit, through the
349 # exit_now is set by a call to %Exit or %Quit, through the
350 # ask_exit callback.
350 # ask_exit callback.
351
351
352 while not self.exit_now:
352 while not self.exit_now:
353 self.hooks.pre_prompt_hook()
353 self.hooks.pre_prompt_hook()
354 if more:
354 if more:
355 try:
355 try:
356 prompt = self.prompt_manager.render('in2')
356 prompt = self.prompt_manager.render('in2')
357 except:
357 except:
358 self.showtraceback()
358 self.showtraceback()
359 if self.autoindent:
359 if self.autoindent:
360 self.rl_do_indent = True
360 self.rl_do_indent = True
361
361
362 else:
362 else:
363 try:
363 try:
364 prompt = self.separate_in + self.prompt_manager.render('in')
364 prompt = self.separate_in + self.prompt_manager.render('in')
365 except:
365 except:
366 self.showtraceback()
366 self.showtraceback()
367 try:
367 try:
368 line = self.raw_input(prompt)
368 line = self.raw_input(prompt)
369 if self.exit_now:
369 if self.exit_now:
370 # quick exit on sys.std[in|out] close
370 # quick exit on sys.std[in|out] close
371 break
371 break
372 if self.autoindent:
372 if self.autoindent:
373 self.rl_do_indent = False
373 self.rl_do_indent = False
374
374
375 except KeyboardInterrupt:
375 except KeyboardInterrupt:
376 #double-guard against keyboardinterrupts during kbdint handling
376 #double-guard against keyboardinterrupts during kbdint handling
377 try:
377 try:
378 self.write('\nKeyboardInterrupt\n')
378 self.write('\nKeyboardInterrupt\n')
379 source_raw = self.input_splitter.source_raw_reset()[1]
379 source_raw = self.input_splitter.source_raw_reset()[1]
380 hlen_b4_cell = \
380 hlen_b4_cell = \
381 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
381 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
382 more = False
382 more = False
383 except KeyboardInterrupt:
383 except KeyboardInterrupt:
384 pass
384 pass
385 except EOFError:
385 except EOFError:
386 if self.autoindent:
386 if self.autoindent:
387 self.rl_do_indent = False
387 self.rl_do_indent = False
388 if self.has_readline:
388 if self.has_readline:
389 self.readline_startup_hook(None)
389 self.readline_startup_hook(None)
390 self.write('\n')
390 self.write('\n')
391 self.exit()
391 self.exit()
392 except bdb.BdbQuit:
392 except bdb.BdbQuit:
393 warn('The Python debugger has exited with a BdbQuit exception.\n'
393 warn('The Python debugger has exited with a BdbQuit exception.\n'
394 'Because of how pdb handles the stack, it is impossible\n'
394 'Because of how pdb handles the stack, it is impossible\n'
395 'for IPython to properly format this particular exception.\n'
395 'for IPython to properly format this particular exception.\n'
396 'IPython will resume normal operation.')
396 'IPython will resume normal operation.')
397 except:
397 except:
398 # exceptions here are VERY RARE, but they can be triggered
398 # exceptions here are VERY RARE, but they can be triggered
399 # asynchronously by signal handlers, for example.
399 # asynchronously by signal handlers, for example.
400 self.showtraceback()
400 self.showtraceback()
401 else:
401 else:
402 self.input_splitter.push(line)
402 self.input_splitter.push(line)
403 more = self.input_splitter.push_accepts_more()
403 more = self.input_splitter.push_accepts_more()
404 if (self.SyntaxTB.last_syntax_error and
404 if (self.SyntaxTB.last_syntax_error and
405 self.autoedit_syntax):
405 self.autoedit_syntax):
406 self.edit_syntax_error()
406 self.edit_syntax_error()
407 if not more:
407 if not more:
408 source_raw = self.input_splitter.source_raw_reset()[1]
408 source_raw = self.input_splitter.source_raw_reset()[1]
409 self.run_cell(source_raw, store_history=True)
409 self.run_cell(source_raw, store_history=True)
410 hlen_b4_cell = \
410 hlen_b4_cell = \
411 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
411 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
412
412
413 # Turn off the exit flag, so the mainloop can be restarted if desired
413 # Turn off the exit flag, so the mainloop can be restarted if desired
414 self.exit_now = False
414 self.exit_now = False
415
415
416 def raw_input(self, prompt=''):
416 def raw_input(self, prompt=''):
417 """Write a prompt and read a line.
417 """Write a prompt and read a line.
418
418
419 The returned line does not include the trailing newline.
419 The returned line does not include the trailing newline.
420 When the user enters the EOF key sequence, EOFError is raised.
420 When the user enters the EOF key sequence, EOFError is raised.
421
421
422 Optional inputs:
422 Optional inputs:
423
423
424 - prompt(''): a string to be printed to prompt the user.
424 - prompt(''): a string to be printed to prompt the user.
425
425
426 - continue_prompt(False): whether this line is the first one or a
426 - continue_prompt(False): whether this line is the first one or a
427 continuation in a sequence of inputs.
427 continuation in a sequence of inputs.
428 """
428 """
429 # Code run by the user may have modified the readline completer state.
429 # Code run by the user may have modified the readline completer state.
430 # We must ensure that our completer is back in place.
430 # We must ensure that our completer is back in place.
431
431
432 if self.has_readline:
432 if self.has_readline:
433 self.set_readline_completer()
433 self.set_readline_completer()
434
434
435 try:
435 try:
436 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
436 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
437 except ValueError:
437 except ValueError:
438 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
438 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
439 " or sys.stdout.close()!\nExiting IPython!")
439 " or sys.stdout.close()!\nExiting IPython!")
440 self.ask_exit()
440 self.ask_exit()
441 return ""
441 return ""
442
442
443 # Try to be reasonably smart about not re-indenting pasted input more
443 # Try to be reasonably smart about not re-indenting pasted input more
444 # than necessary. We do this by trimming out the auto-indent initial
444 # than necessary. We do this by trimming out the auto-indent initial
445 # spaces, if the user's actual input started itself with whitespace.
445 # spaces, if the user's actual input started itself with whitespace.
446 if self.autoindent:
446 if self.autoindent:
447 if num_ini_spaces(line) > self.indent_current_nsp:
447 if num_ini_spaces(line) > self.indent_current_nsp:
448 line = line[self.indent_current_nsp:]
448 line = line[self.indent_current_nsp:]
449 self.indent_current_nsp = 0
449 self.indent_current_nsp = 0
450
450
451 return line
451 return line
452
452
453 #-------------------------------------------------------------------------
453 #-------------------------------------------------------------------------
454 # Methods to support auto-editing of SyntaxErrors.
454 # Methods to support auto-editing of SyntaxErrors.
455 #-------------------------------------------------------------------------
455 #-------------------------------------------------------------------------
456
456
457 def edit_syntax_error(self):
457 def edit_syntax_error(self):
458 """The bottom half of the syntax error handler called in the main loop.
458 """The bottom half of the syntax error handler called in the main loop.
459
459
460 Loop until syntax error is fixed or user cancels.
460 Loop until syntax error is fixed or user cancels.
461 """
461 """
462
462
463 while self.SyntaxTB.last_syntax_error:
463 while self.SyntaxTB.last_syntax_error:
464 # copy and clear last_syntax_error
464 # copy and clear last_syntax_error
465 err = self.SyntaxTB.clear_err_state()
465 err = self.SyntaxTB.clear_err_state()
466 if not self._should_recompile(err):
466 if not self._should_recompile(err):
467 return
467 return
468 try:
468 try:
469 # may set last_syntax_error again if a SyntaxError is raised
469 # may set last_syntax_error again if a SyntaxError is raised
470 self.safe_execfile(err.filename,self.user_ns)
470 self.safe_execfile(err.filename,self.user_ns)
471 except:
471 except:
472 self.showtraceback()
472 self.showtraceback()
473 else:
473 else:
474 try:
474 try:
475 f = file(err.filename)
475 f = file(err.filename)
476 try:
476 try:
477 # This should be inside a display_trap block and I
477 # This should be inside a display_trap block and I
478 # think it is.
478 # think it is.
479 sys.displayhook(f.read())
479 sys.displayhook(f.read())
480 finally:
480 finally:
481 f.close()
481 f.close()
482 except:
482 except:
483 self.showtraceback()
483 self.showtraceback()
484
484
485 def _should_recompile(self,e):
485 def _should_recompile(self,e):
486 """Utility routine for edit_syntax_error"""
486 """Utility routine for edit_syntax_error"""
487
487
488 if e.filename in ('<ipython console>','<input>','<string>',
488 if e.filename in ('<ipython console>','<input>','<string>',
489 '<console>','<BackgroundJob compilation>',
489 '<console>','<BackgroundJob compilation>',
490 None):
490 None):
491
491
492 return False
492 return False
493 try:
493 try:
494 if (self.autoedit_syntax and
494 if (self.autoedit_syntax and
495 not self.ask_yes_no('Return to editor to correct syntax error? '
495 not self.ask_yes_no('Return to editor to correct syntax error? '
496 '[Y/n] ','y')):
496 '[Y/n] ','y')):
497 return False
497 return False
498 except EOFError:
498 except EOFError:
499 return False
499 return False
500
500
501 def int0(x):
501 def int0(x):
502 try:
502 try:
503 return int(x)
503 return int(x)
504 except TypeError:
504 except TypeError:
505 return 0
505 return 0
506 # always pass integer line and offset values to editor hook
506 # always pass integer line and offset values to editor hook
507 try:
507 try:
508 self.hooks.fix_error_editor(e.filename,
508 self.hooks.fix_error_editor(e.filename,
509 int0(e.lineno),int0(e.offset),e.msg)
509 int0(e.lineno),int0(e.offset),e.msg)
510 except TryNext:
510 except TryNext:
511 warn('Could not open editor')
511 warn('Could not open editor')
512 return False
512 return False
513 return True
513 return True
514
514
515 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
516 # Things related to exiting
516 # Things related to exiting
517 #-------------------------------------------------------------------------
517 #-------------------------------------------------------------------------
518
518
519 def ask_exit(self):
519 def ask_exit(self):
520 """ Ask the shell to exit. Can be overiden and used as a callback. """
520 """ Ask the shell to exit. Can be overiden and used as a callback. """
521 self.exit_now = True
521 self.exit_now = True
522
522
523 def exit(self):
523 def exit(self):
524 """Handle interactive exit.
524 """Handle interactive exit.
525
525
526 This method calls the ask_exit callback."""
526 This method calls the ask_exit callback."""
527 if self.confirm_exit:
527 if self.confirm_exit:
528 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
528 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
529 self.ask_exit()
529 self.ask_exit()
530 else:
530 else:
531 self.ask_exit()
531 self.ask_exit()
532
532
533 #------------------------------------------------------------------------
533 #------------------------------------------------------------------------
534 # Magic overrides
534 # Magic overrides
535 #------------------------------------------------------------------------
535 #------------------------------------------------------------------------
536 # Once the base class stops inheriting from magic, this code needs to be
536 # Once the base class stops inheriting from magic, this code needs to be
537 # moved into a separate machinery as well. For now, at least isolate here
537 # moved into a separate machinery as well. For now, at least isolate here
538 # the magics which this class needs to implement differently from the base
538 # the magics which this class needs to implement differently from the base
539 # class, or that are unique to it.
539 # class, or that are unique to it.
540
540
541 def magic_autoindent(self, parameter_s = ''):
541 def magic_autoindent(self, parameter_s = ''):
542 """Toggle autoindent on/off (if available)."""
542 """Toggle autoindent on/off (if available)."""
543
543
544 self.shell.set_autoindent()
544 self.shell.set_autoindent()
545 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
545 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
546
546
547 @skip_doctest
547 @skip_doctest
548 def magic_cpaste(self, parameter_s=''):
548 def magic_cpaste(self, parameter_s=''):
549 """Paste & execute a pre-formatted code block from clipboard.
549 """Paste & execute a pre-formatted code block from clipboard.
550
550
551 You must terminate the block with '--' (two minus-signs) or Ctrl-D
551 You must terminate the block with '--' (two minus-signs) or Ctrl-D
552 alone on the line. You can also provide your own sentinel with '%paste
552 alone on the line. You can also provide your own sentinel with '%paste
553 -s %%' ('%%' is the new sentinel for this operation)
553 -s %%' ('%%' is the new sentinel for this operation)
554
554
555 The block is dedented prior to execution to enable execution of method
555 The block is dedented prior to execution to enable execution of method
556 definitions. '>' and '+' characters at the beginning of a line are
556 definitions. '>' and '+' characters at the beginning of a line are
557 ignored, to allow pasting directly from e-mails, diff files and
557 ignored, to allow pasting directly from e-mails, diff files and
558 doctests (the '...' continuation prompt is also stripped). The
558 doctests (the '...' continuation prompt is also stripped). The
559 executed block is also assigned to variable named 'pasted_block' for
559 executed block is also assigned to variable named 'pasted_block' for
560 later editing with '%edit pasted_block'.
560 later editing with '%edit pasted_block'.
561
561
562 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
562 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
563 This assigns the pasted block to variable 'foo' as string, without
563 This assigns the pasted block to variable 'foo' as string, without
564 dedenting or executing it (preceding >>> and + is still stripped)
564 dedenting or executing it (preceding >>> and + is still stripped)
565
565
566 '%cpaste -r' re-executes the block previously entered by cpaste.
566 '%cpaste -r' re-executes the block previously entered by cpaste.
567
567
568 Do not be alarmed by garbled output on Windows (it's a readline bug).
568 Do not be alarmed by garbled output on Windows (it's a readline bug).
569 Just press enter and type -- (and press enter again) and the block
569 Just press enter and type -- (and press enter again) and the block
570 will be what was just pasted.
570 will be what was just pasted.
571
571
572 IPython statements (magics, shell escapes) are not supported (yet).
572 IPython statements (magics, shell escapes) are not supported (yet).
573
573
574 See also
574 See also
575 --------
575 --------
576 paste: automatically pull code from clipboard.
576 paste: automatically pull code from clipboard.
577
577
578 Examples
578 Examples
579 --------
579 --------
580 ::
580 ::
581
581
582 In [8]: %cpaste
582 In [8]: %cpaste
583 Pasting code; enter '--' alone on the line to stop.
583 Pasting code; enter '--' alone on the line to stop.
584 :>>> a = ["world!", "Hello"]
584 :>>> a = ["world!", "Hello"]
585 :>>> print " ".join(sorted(a))
585 :>>> print " ".join(sorted(a))
586 :--
586 :--
587 Hello world!
587 Hello world!
588 """
588 """
589
589
590 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
590 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
591 if 'r' in opts:
591 if 'r' in opts:
592 rerun_pasted(self.shell)
592 rerun_pasted(self.shell)
593 return
593 return
594
594
595 sentinel = opts.get('s', '--')
595 sentinel = opts.get('s', '--')
596 block = strip_email_quotes(get_pasted_lines(sentinel))
596 block = strip_email_quotes(get_pasted_lines(sentinel))
597 store_or_execute(self.shell, block, name)
597 store_or_execute(self.shell, block, name)
598
598
599 def magic_paste(self, parameter_s=''):
599 def magic_paste(self, parameter_s=''):
600 """Paste & execute a pre-formatted code block from clipboard.
600 """Paste & execute a pre-formatted code block from clipboard.
601
601
602 The text is pulled directly from the clipboard without user
602 The text is pulled directly from the clipboard without user
603 intervention and printed back on the screen before execution (unless
603 intervention and printed back on the screen before execution (unless
604 the -q flag is given to force quiet mode).
604 the -q flag is given to force quiet mode).
605
605
606 The block is dedented prior to execution to enable execution of method
606 The block is dedented prior to execution to enable execution of method
607 definitions. '>' and '+' characters at the beginning of a line are
607 definitions. '>' and '+' characters at the beginning of a line are
608 ignored, to allow pasting directly from e-mails, diff files and
608 ignored, to allow pasting directly from e-mails, diff files and
609 doctests (the '...' continuation prompt is also stripped). The
609 doctests (the '...' continuation prompt is also stripped). The
610 executed block is also assigned to variable named 'pasted_block' for
610 executed block is also assigned to variable named 'pasted_block' for
611 later editing with '%edit pasted_block'.
611 later editing with '%edit pasted_block'.
612
612
613 You can also pass a variable name as an argument, e.g. '%paste foo'.
613 You can also pass a variable name as an argument, e.g. '%paste foo'.
614 This assigns the pasted block to variable 'foo' as string, without
614 This assigns the pasted block to variable 'foo' as string, without
615 dedenting or executing it (preceding >>> and + is still stripped)
615 dedenting or executing it (preceding >>> and + is still stripped)
616
616
617 Options
617 Options
618 -------
618 -------
619
619
620 -r: re-executes the block previously entered by cpaste.
620 -r: re-executes the block previously entered by cpaste.
621
621
622 -q: quiet mode: do not echo the pasted text back to the terminal.
622 -q: quiet mode: do not echo the pasted text back to the terminal.
623
623
624 IPython statements (magics, shell escapes) are not supported (yet).
624 IPython statements (magics, shell escapes) are not supported (yet).
625
625
626 See also
626 See also
627 --------
627 --------
628 cpaste: manually paste code into terminal until you mark its end.
628 cpaste: manually paste code into terminal until you mark its end.
629 """
629 """
630 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
630 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
631 if 'r' in opts:
631 if 'r' in opts:
632 rerun_pasted(self.shell)
632 rerun_pasted(self.shell)
633 return
633 return
634 try:
634 try:
635 text = self.shell.hooks.clipboard_get()
635 text = self.shell.hooks.clipboard_get()
636 block = strip_email_quotes(text.splitlines())
636 block = strip_email_quotes(text.splitlines())
637 except TryNext as clipboard_exc:
637 except TryNext as clipboard_exc:
638 message = getattr(clipboard_exc, 'args')
638 message = getattr(clipboard_exc, 'args')
639 if message:
639 if message:
640 error(message[0])
640 error(message[0])
641 else:
641 else:
642 error('Could not get text from the clipboard.')
642 error('Could not get text from the clipboard.')
643 return
643 return
644
644
645 # By default, echo back to terminal unless quiet mode is requested
645 # By default, echo back to terminal unless quiet mode is requested
646 if 'q' not in opts:
646 if 'q' not in opts:
647 write = self.shell.write
647 write = self.shell.write
648 write(self.shell.pycolorize(block))
648 write(self.shell.pycolorize(block))
649 if not block.endswith('\n'):
649 if not block.endswith('\n'):
650 write('\n')
650 write('\n')
651 write("## -- End pasted text --\n")
651 write("## -- End pasted text --\n")
652
652
653 store_or_execute(self.shell, block, name)
653 store_or_execute(self.shell, block, name)
654
654
655 # Class-level: add a '%cls' magic only on Windows
655 # Class-level: add a '%cls' magic only on Windows
656 if sys.platform == 'win32':
656 if sys.platform == 'win32':
657 def magic_cls(self, s):
657 def magic_cls(self, s):
658 """Clear screen.
658 """Clear screen.
659 """
659 """
660 os.system("cls")
660 os.system("cls")
661
661
662 def showindentationerror(self):
662 def showindentationerror(self):
663 super(TerminalInteractiveShell, self).showindentationerror()
663 super(TerminalInteractiveShell, self).showindentationerror()
664 print("If you want to paste code into IPython, try the "
664 print("If you want to paste code into IPython, try the "
665 "%paste and %cpaste magic functions.")
665 "%paste and %cpaste magic functions.")
666
666
667
667
668 InteractiveShellABC.register(TerminalInteractiveShell)
668 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,759 +1,759 b''
1 """The Python scheduler for rich scheduling.
1 """The Python scheduler for rich scheduling.
2
2
3 The Pure ZMQ scheduler does not allow routing schemes other than LRU,
3 The Pure ZMQ scheduler does not allow routing schemes other than LRU,
4 nor does it check msg_id DAG dependencies. For those, a slightly slower
4 nor does it check msg_id DAG dependencies. For those, a slightly slower
5 Python Scheduler exists.
5 Python Scheduler exists.
6
6
7 Authors:
7 Authors:
8
8
9 * Min RK
9 * Min RK
10 """
10 """
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2010-2011 The IPython Development Team
12 # Copyright (C) 2010-2011 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 from __future__ import print_function
22 from __future__ import print_function
23
23
24 import logging
24 import logging
25 import sys
25 import sys
26 import time
26 import time
27
27
28 from datetime import datetime, timedelta
28 from datetime import datetime, timedelta
29 from random import randint, random
29 from random import randint, random
30 from types import FunctionType
30 from types import FunctionType
31
31
32 try:
32 try:
33 import numpy
33 import numpy
34 except ImportError:
34 except ImportError:
35 numpy = None
35 numpy = None
36
36
37 import zmq
37 import zmq
38 from zmq.eventloop import ioloop, zmqstream
38 from zmq.eventloop import ioloop, zmqstream
39
39
40 # local imports
40 # local imports
41 from IPython.external.decorator import decorator
41 from IPython.external.decorator import decorator
42 from IPython.config.application import Application
42 from IPython.config.application import Application
43 from IPython.config.loader import Config
43 from IPython.config.loader import Config
44 from IPython.utils.traitlets import Instance, Dict, List, Set, Integer, Enum, CBytes
44 from IPython.utils.traitlets import Instance, Dict, List, Set, Integer, Enum, CBytes
45
45
46 from IPython.parallel import error
46 from IPython.parallel import error
47 from IPython.parallel.factory import SessionFactory
47 from IPython.parallel.factory import SessionFactory
48 from IPython.parallel.util import connect_logger, local_logger, asbytes
48 from IPython.parallel.util import connect_logger, local_logger, asbytes
49
49
50 from .dependency import Dependency
50 from .dependency import Dependency
51
51
52 @decorator
52 @decorator
53 def logged(f,self,*args,**kwargs):
53 def logged(f,self,*args,**kwargs):
54 # print ("#--------------------")
54 # print ("#--------------------")
55 self.log.debug("scheduler::%s(*%s,**%s)", f.func_name, args, kwargs)
55 self.log.debug("scheduler::%s(*%s,**%s)", f.func_name, args, kwargs)
56 # print ("#--")
56 # print ("#--")
57 return f(self,*args, **kwargs)
57 return f(self,*args, **kwargs)
58
58
59 #----------------------------------------------------------------------
59 #----------------------------------------------------------------------
60 # Chooser functions
60 # Chooser functions
61 #----------------------------------------------------------------------
61 #----------------------------------------------------------------------
62
62
63 def plainrandom(loads):
63 def plainrandom(loads):
64 """Plain random pick."""
64 """Plain random pick."""
65 n = len(loads)
65 n = len(loads)
66 return randint(0,n-1)
66 return randint(0,n-1)
67
67
68 def lru(loads):
68 def lru(loads):
69 """Always pick the front of the line.
69 """Always pick the front of the line.
70
70
71 The content of `loads` is ignored.
71 The content of `loads` is ignored.
72
72
73 Assumes LRU ordering of loads, with oldest first.
73 Assumes LRU ordering of loads, with oldest first.
74 """
74 """
75 return 0
75 return 0
76
76
77 def twobin(loads):
77 def twobin(loads):
78 """Pick two at random, use the LRU of the two.
78 """Pick two at random, use the LRU of the two.
79
79
80 The content of loads is ignored.
80 The content of loads is ignored.
81
81
82 Assumes LRU ordering of loads, with oldest first.
82 Assumes LRU ordering of loads, with oldest first.
83 """
83 """
84 n = len(loads)
84 n = len(loads)
85 a = randint(0,n-1)
85 a = randint(0,n-1)
86 b = randint(0,n-1)
86 b = randint(0,n-1)
87 return min(a,b)
87 return min(a,b)
88
88
89 def weighted(loads):
89 def weighted(loads):
90 """Pick two at random using inverse load as weight.
90 """Pick two at random using inverse load as weight.
91
91
92 Return the less loaded of the two.
92 Return the less loaded of the two.
93 """
93 """
94 # weight 0 a million times more than 1:
94 # weight 0 a million times more than 1:
95 weights = 1./(1e-6+numpy.array(loads))
95 weights = 1./(1e-6+numpy.array(loads))
96 sums = weights.cumsum()
96 sums = weights.cumsum()
97 t = sums[-1]
97 t = sums[-1]
98 x = random()*t
98 x = random()*t
99 y = random()*t
99 y = random()*t
100 idx = 0
100 idx = 0
101 idy = 0
101 idy = 0
102 while sums[idx] < x:
102 while sums[idx] < x:
103 idx += 1
103 idx += 1
104 while sums[idy] < y:
104 while sums[idy] < y:
105 idy += 1
105 idy += 1
106 if weights[idy] > weights[idx]:
106 if weights[idy] > weights[idx]:
107 return idy
107 return idy
108 else:
108 else:
109 return idx
109 return idx
110
110
111 def leastload(loads):
111 def leastload(loads):
112 """Always choose the lowest load.
112 """Always choose the lowest load.
113
113
114 If the lowest load occurs more than once, the first
114 If the lowest load occurs more than once, the first
115 occurance will be used. If loads has LRU ordering, this means
115 occurance will be used. If loads has LRU ordering, this means
116 the LRU of those with the lowest load is chosen.
116 the LRU of those with the lowest load is chosen.
117 """
117 """
118 return loads.index(min(loads))
118 return loads.index(min(loads))
119
119
120 #---------------------------------------------------------------------
120 #---------------------------------------------------------------------
121 # Classes
121 # Classes
122 #---------------------------------------------------------------------
122 #---------------------------------------------------------------------
123
123
124
124
125 # store empty default dependency:
125 # store empty default dependency:
126 MET = Dependency([])
126 MET = Dependency([])
127
127
128
128
129 class Job(object):
129 class Job(object):
130 """Simple container for a job"""
130 """Simple container for a job"""
131 def __init__(self, msg_id, raw_msg, idents, msg, header, targets, after, follow, timeout):
131 def __init__(self, msg_id, raw_msg, idents, msg, header, targets, after, follow, timeout):
132 self.msg_id = msg_id
132 self.msg_id = msg_id
133 self.raw_msg = raw_msg
133 self.raw_msg = raw_msg
134 self.idents = idents
134 self.idents = idents
135 self.msg = msg
135 self.msg = msg
136 self.header = header
136 self.header = header
137 self.targets = targets
137 self.targets = targets
138 self.after = after
138 self.after = after
139 self.follow = follow
139 self.follow = follow
140 self.timeout = timeout
140 self.timeout = timeout
141
141
142
142
143 self.timestamp = time.time()
143 self.timestamp = time.time()
144 self.blacklist = set()
144 self.blacklist = set()
145
145
146 @property
146 @property
147 def dependents(self):
147 def dependents(self):
148 return self.follow.union(self.after)
148 return self.follow.union(self.after)
149
149
150 class TaskScheduler(SessionFactory):
150 class TaskScheduler(SessionFactory):
151 """Python TaskScheduler object.
151 """Python TaskScheduler object.
152
152
153 This is the simplest object that supports msg_id based
153 This is the simplest object that supports msg_id based
154 DAG dependencies. *Only* task msg_ids are checked, not
154 DAG dependencies. *Only* task msg_ids are checked, not
155 msg_ids of jobs submitted via the MUX queue.
155 msg_ids of jobs submitted via the MUX queue.
156
156
157 """
157 """
158
158
159 hwm = Integer(1, config=True,
159 hwm = Integer(1, config=True,
160 help="""specify the High Water Mark (HWM) for the downstream
160 help="""specify the High Water Mark (HWM) for the downstream
161 socket in the Task scheduler. This is the maximum number
161 socket in the Task scheduler. This is the maximum number
162 of allowed outstanding tasks on each engine.
162 of allowed outstanding tasks on each engine.
163
163
164 The default (1) means that only one task can be outstanding on each
164 The default (1) means that only one task can be outstanding on each
165 engine. Setting TaskScheduler.hwm=0 means there is no limit, and the
165 engine. Setting TaskScheduler.hwm=0 means there is no limit, and the
166 engines continue to be assigned tasks while they are working,
166 engines continue to be assigned tasks while they are working,
167 effectively hiding network latency behind computation, but can result
167 effectively hiding network latency behind computation, but can result
168 in an imbalance of work when submitting many heterogenous tasks all at
168 in an imbalance of work when submitting many heterogenous tasks all at
169 once. Any positive value greater than one is a compromise between the
169 once. Any positive value greater than one is a compromise between the
170 two.
170 two.
171
171
172 """
172 """
173 )
173 )
174 scheme_name = Enum(('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin'),
174 scheme_name = Enum(('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin'),
175 'leastload', config=True, allow_none=False,
175 'leastload', config=True, allow_none=False,
176 help="""select the task scheduler scheme [default: Python LRU]
176 help="""select the task scheduler scheme [default: Python LRU]
177 Options are: 'pure', 'lru', 'plainrandom', 'weighted', 'twobin','leastload'"""
177 Options are: 'pure', 'lru', 'plainrandom', 'weighted', 'twobin','leastload'"""
178 )
178 )
179 def _scheme_name_changed(self, old, new):
179 def _scheme_name_changed(self, old, new):
180 self.log.debug("Using scheme %r"%new)
180 self.log.debug("Using scheme %r"%new)
181 self.scheme = globals()[new]
181 self.scheme = globals()[new]
182
182
183 # input arguments:
183 # input arguments:
184 scheme = Instance(FunctionType) # function for determining the destination
184 scheme = Instance(FunctionType) # function for determining the destination
185 def _scheme_default(self):
185 def _scheme_default(self):
186 return leastload
186 return leastload
187 client_stream = Instance(zmqstream.ZMQStream) # client-facing stream
187 client_stream = Instance(zmqstream.ZMQStream) # client-facing stream
188 engine_stream = Instance(zmqstream.ZMQStream) # engine-facing stream
188 engine_stream = Instance(zmqstream.ZMQStream) # engine-facing stream
189 notifier_stream = Instance(zmqstream.ZMQStream) # hub-facing sub stream
189 notifier_stream = Instance(zmqstream.ZMQStream) # hub-facing sub stream
190 mon_stream = Instance(zmqstream.ZMQStream) # hub-facing pub stream
190 mon_stream = Instance(zmqstream.ZMQStream) # hub-facing pub stream
191
191
192 # internals:
192 # internals:
193 graph = Dict() # dict by msg_id of [ msg_ids that depend on key ]
193 graph = Dict() # dict by msg_id of [ msg_ids that depend on key ]
194 retries = Dict() # dict by msg_id of retries remaining (non-neg ints)
194 retries = Dict() # dict by msg_id of retries remaining (non-neg ints)
195 # waiting = List() # list of msg_ids ready to run, but haven't due to HWM
195 # waiting = List() # list of msg_ids ready to run, but haven't due to HWM
196 depending = Dict() # dict by msg_id of Jobs
196 depending = Dict() # dict by msg_id of Jobs
197 pending = Dict() # dict by engine_uuid of submitted tasks
197 pending = Dict() # dict by engine_uuid of submitted tasks
198 completed = Dict() # dict by engine_uuid of completed tasks
198 completed = Dict() # dict by engine_uuid of completed tasks
199 failed = Dict() # dict by engine_uuid of failed tasks
199 failed = Dict() # dict by engine_uuid of failed tasks
200 destinations = Dict() # dict by msg_id of engine_uuids where jobs ran (reverse of completed+failed)
200 destinations = Dict() # dict by msg_id of engine_uuids where jobs ran (reverse of completed+failed)
201 clients = Dict() # dict by msg_id for who submitted the task
201 clients = Dict() # dict by msg_id for who submitted the task
202 targets = List() # list of target IDENTs
202 targets = List() # list of target IDENTs
203 loads = List() # list of engine loads
203 loads = List() # list of engine loads
204 # full = Set() # set of IDENTs that have HWM outstanding tasks
204 # full = Set() # set of IDENTs that have HWM outstanding tasks
205 all_completed = Set() # set of all completed tasks
205 all_completed = Set() # set of all completed tasks
206 all_failed = Set() # set of all failed tasks
206 all_failed = Set() # set of all failed tasks
207 all_done = Set() # set of all finished tasks=union(completed,failed)
207 all_done = Set() # set of all finished tasks=union(completed,failed)
208 all_ids = Set() # set of all submitted task IDs
208 all_ids = Set() # set of all submitted task IDs
209
209
210 auditor = Instance('zmq.eventloop.ioloop.PeriodicCallback')
210 auditor = Instance('zmq.eventloop.ioloop.PeriodicCallback')
211
211
212 ident = CBytes() # ZMQ identity. This should just be self.session.session
212 ident = CBytes() # ZMQ identity. This should just be self.session.session
213 # but ensure Bytes
213 # but ensure Bytes
214 def _ident_default(self):
214 def _ident_default(self):
215 return self.session.bsession
215 return self.session.bsession
216
216
217 def start(self):
217 def start(self):
218 self.engine_stream.on_recv(self.dispatch_result, copy=False)
218 self.engine_stream.on_recv(self.dispatch_result, copy=False)
219 self.client_stream.on_recv(self.dispatch_submission, copy=False)
219 self.client_stream.on_recv(self.dispatch_submission, copy=False)
220
220
221 self._notification_handlers = dict(
221 self._notification_handlers = dict(
222 registration_notification = self._register_engine,
222 registration_notification = self._register_engine,
223 unregistration_notification = self._unregister_engine
223 unregistration_notification = self._unregister_engine
224 )
224 )
225 self.notifier_stream.on_recv(self.dispatch_notification)
225 self.notifier_stream.on_recv(self.dispatch_notification)
226 self.auditor = ioloop.PeriodicCallback(self.audit_timeouts, 2e3, self.loop) # 1 Hz
226 self.auditor = ioloop.PeriodicCallback(self.audit_timeouts, 2e3, self.loop) # 1 Hz
227 self.auditor.start()
227 self.auditor.start()
228 self.log.info("Scheduler started [%s]"%self.scheme_name)
228 self.log.info("Scheduler started [%s]"%self.scheme_name)
229
229
230 def resume_receiving(self):
230 def resume_receiving(self):
231 """Resume accepting jobs."""
231 """Resume accepting jobs."""
232 self.client_stream.on_recv(self.dispatch_submission, copy=False)
232 self.client_stream.on_recv(self.dispatch_submission, copy=False)
233
233
234 def stop_receiving(self):
234 def stop_receiving(self):
235 """Stop accepting jobs while there are no engines.
235 """Stop accepting jobs while there are no engines.
236 Leave them in the ZMQ queue."""
236 Leave them in the ZMQ queue."""
237 self.client_stream.on_recv(None)
237 self.client_stream.on_recv(None)
238
238
239 #-----------------------------------------------------------------------
239 #-----------------------------------------------------------------------
240 # [Un]Registration Handling
240 # [Un]Registration Handling
241 #-----------------------------------------------------------------------
241 #-----------------------------------------------------------------------
242
242
243 def dispatch_notification(self, msg):
243 def dispatch_notification(self, msg):
244 """dispatch register/unregister events."""
244 """dispatch register/unregister events."""
245 try:
245 try:
246 idents,msg = self.session.feed_identities(msg)
246 idents,msg = self.session.feed_identities(msg)
247 except ValueError:
247 except ValueError:
248 self.log.warn("task::Invalid Message: %r",msg)
248 self.log.warn("task::Invalid Message: %r",msg)
249 return
249 return
250 try:
250 try:
251 msg = self.session.unserialize(msg)
251 msg = self.session.unserialize(msg)
252 except ValueError:
252 except ValueError:
253 self.log.warn("task::Unauthorized message from: %r"%idents)
253 self.log.warn("task::Unauthorized message from: %r"%idents)
254 return
254 return
255
255
256 msg_type = msg['header']['msg_type']
256 msg_type = msg['header']['msg_type']
257
257
258 handler = self._notification_handlers.get(msg_type, None)
258 handler = self._notification_handlers.get(msg_type, None)
259 if handler is None:
259 if handler is None:
260 self.log.error("Unhandled message type: %r"%msg_type)
260 self.log.error("Unhandled message type: %r"%msg_type)
261 else:
261 else:
262 try:
262 try:
263 handler(asbytes(msg['content']['queue']))
263 handler(asbytes(msg['content']['queue']))
264 except Exception:
264 except Exception:
265 self.log.error("task::Invalid notification msg: %r", msg, exc_info=True)
265 self.log.error("task::Invalid notification msg: %r", msg, exc_info=True)
266
266
267 def _register_engine(self, uid):
267 def _register_engine(self, uid):
268 """New engine with ident `uid` became available."""
268 """New engine with ident `uid` became available."""
269 # head of the line:
269 # head of the line:
270 self.targets.insert(0,uid)
270 self.targets.insert(0,uid)
271 self.loads.insert(0,0)
271 self.loads.insert(0,0)
272
272
273 # initialize sets
273 # initialize sets
274 self.completed[uid] = set()
274 self.completed[uid] = set()
275 self.failed[uid] = set()
275 self.failed[uid] = set()
276 self.pending[uid] = {}
276 self.pending[uid] = {}
277
277
278 # rescan the graph:
278 # rescan the graph:
279 self.update_graph(None)
279 self.update_graph(None)
280
280
281 def _unregister_engine(self, uid):
281 def _unregister_engine(self, uid):
282 """Existing engine with ident `uid` became unavailable."""
282 """Existing engine with ident `uid` became unavailable."""
283 if len(self.targets) == 1:
283 if len(self.targets) == 1:
284 # this was our only engine
284 # this was our only engine
285 pass
285 pass
286
286
287 # handle any potentially finished tasks:
287 # handle any potentially finished tasks:
288 self.engine_stream.flush()
288 self.engine_stream.flush()
289
289
290 # don't pop destinations, because they might be used later
290 # don't pop destinations, because they might be used later
291 # map(self.destinations.pop, self.completed.pop(uid))
291 # map(self.destinations.pop, self.completed.pop(uid))
292 # map(self.destinations.pop, self.failed.pop(uid))
292 # map(self.destinations.pop, self.failed.pop(uid))
293
293
294 # prevent this engine from receiving work
294 # prevent this engine from receiving work
295 idx = self.targets.index(uid)
295 idx = self.targets.index(uid)
296 self.targets.pop(idx)
296 self.targets.pop(idx)
297 self.loads.pop(idx)
297 self.loads.pop(idx)
298
298
299 # wait 5 seconds before cleaning up pending jobs, since the results might
299 # wait 5 seconds before cleaning up pending jobs, since the results might
300 # still be incoming
300 # still be incoming
301 if self.pending[uid]:
301 if self.pending[uid]:
302 dc = ioloop.DelayedCallback(lambda : self.handle_stranded_tasks(uid), 5000, self.loop)
302 dc = ioloop.DelayedCallback(lambda : self.handle_stranded_tasks(uid), 5000, self.loop)
303 dc.start()
303 dc.start()
304 else:
304 else:
305 self.completed.pop(uid)
305 self.completed.pop(uid)
306 self.failed.pop(uid)
306 self.failed.pop(uid)
307
307
308
308
309 def handle_stranded_tasks(self, engine):
309 def handle_stranded_tasks(self, engine):
310 """Deal with jobs resident in an engine that died."""
310 """Deal with jobs resident in an engine that died."""
311 lost = self.pending[engine]
311 lost = self.pending[engine]
312 for msg_id in lost.keys():
312 for msg_id in lost.keys():
313 if msg_id not in self.pending[engine]:
313 if msg_id not in self.pending[engine]:
314 # prevent double-handling of messages
314 # prevent double-handling of messages
315 continue
315 continue
316
316
317 raw_msg = lost[msg_id][0]
317 raw_msg = lost[msg_id][0]
318 idents,msg = self.session.feed_identities(raw_msg, copy=False)
318 idents,msg = self.session.feed_identities(raw_msg, copy=False)
319 parent = self.session.unpack(msg[1].bytes)
319 parent = self.session.unpack(msg[1].bytes)
320 idents = [engine, idents[0]]
320 idents = [engine, idents[0]]
321
321
322 # build fake error reply
322 # build fake error reply
323 try:
323 try:
324 raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
324 raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
325 except:
325 except:
326 content = error.wrap_exception()
326 content = error.wrap_exception()
327 # build fake header
327 # build fake header
328 header = dict(
328 header = dict(
329 status='error',
329 status='error',
330 engine=engine,
330 engine=engine,
331 date=datetime.now(),
331 date=datetime.now(),
332 )
332 )
333 msg = self.session.msg('apply_reply', content, parent=parent, subheader=header)
333 msg = self.session.msg('apply_reply', content, parent=parent, subheader=header)
334 raw_reply = map(zmq.Message, self.session.serialize(msg, ident=idents))
334 raw_reply = map(zmq.Message, self.session.serialize(msg, ident=idents))
335 # and dispatch it
335 # and dispatch it
336 self.dispatch_result(raw_reply)
336 self.dispatch_result(raw_reply)
337
337
338 # finally scrub completed/failed lists
338 # finally scrub completed/failed lists
339 self.completed.pop(engine)
339 self.completed.pop(engine)
340 self.failed.pop(engine)
340 self.failed.pop(engine)
341
341
342
342
343 #-----------------------------------------------------------------------
343 #-----------------------------------------------------------------------
344 # Job Submission
344 # Job Submission
345 #-----------------------------------------------------------------------
345 #-----------------------------------------------------------------------
346 def dispatch_submission(self, raw_msg):
346 def dispatch_submission(self, raw_msg):
347 """Dispatch job submission to appropriate handlers."""
347 """Dispatch job submission to appropriate handlers."""
348 # ensure targets up to date:
348 # ensure targets up to date:
349 self.notifier_stream.flush()
349 self.notifier_stream.flush()
350 try:
350 try:
351 idents, msg = self.session.feed_identities(raw_msg, copy=False)
351 idents, msg = self.session.feed_identities(raw_msg, copy=False)
352 msg = self.session.unserialize(msg, content=False, copy=False)
352 msg = self.session.unserialize(msg, content=False, copy=False)
353 except Exception:
353 except Exception:
354 self.log.error("task::Invaid task msg: %r"%raw_msg, exc_info=True)
354 self.log.error("task::Invaid task msg: %r"%raw_msg, exc_info=True)
355 return
355 return
356
356
357
357
358 # send to monitor
358 # send to monitor
359 self.mon_stream.send_multipart([b'intask']+raw_msg, copy=False)
359 self.mon_stream.send_multipart([b'intask']+raw_msg, copy=False)
360
360
361 header = msg['header']
361 header = msg['header']
362 msg_id = header['msg_id']
362 msg_id = header['msg_id']
363 self.all_ids.add(msg_id)
363 self.all_ids.add(msg_id)
364
364
365 # get targets as a set of bytes objects
365 # get targets as a set of bytes objects
366 # from a list of unicode objects
366 # from a list of unicode objects
367 targets = header.get('targets', [])
367 targets = header.get('targets', [])
368 targets = map(asbytes, targets)
368 targets = map(asbytes, targets)
369 targets = set(targets)
369 targets = set(targets)
370
370
371 retries = header.get('retries', 0)
371 retries = header.get('retries', 0)
372 self.retries[msg_id] = retries
372 self.retries[msg_id] = retries
373
373
374 # time dependencies
374 # time dependencies
375 after = header.get('after', None)
375 after = header.get('after', None)
376 if after:
376 if after:
377 after = Dependency(after)
377 after = Dependency(after)
378 if after.all:
378 if after.all:
379 if after.success:
379 if after.success:
380 after = Dependency(after.difference(self.all_completed),
380 after = Dependency(after.difference(self.all_completed),
381 success=after.success,
381 success=after.success,
382 failure=after.failure,
382 failure=after.failure,
383 all=after.all,
383 all=after.all,
384 )
384 )
385 if after.failure:
385 if after.failure:
386 after = Dependency(after.difference(self.all_failed),
386 after = Dependency(after.difference(self.all_failed),
387 success=after.success,
387 success=after.success,
388 failure=after.failure,
388 failure=after.failure,
389 all=after.all,
389 all=after.all,
390 )
390 )
391 if after.check(self.all_completed, self.all_failed):
391 if after.check(self.all_completed, self.all_failed):
392 # recast as empty set, if `after` already met,
392 # recast as empty set, if `after` already met,
393 # to prevent unnecessary set comparisons
393 # to prevent unnecessary set comparisons
394 after = MET
394 after = MET
395 else:
395 else:
396 after = MET
396 after = MET
397
397
398 # location dependencies
398 # location dependencies
399 follow = Dependency(header.get('follow', []))
399 follow = Dependency(header.get('follow', []))
400
400
401 # turn timeouts into datetime objects:
401 # turn timeouts into datetime objects:
402 timeout = header.get('timeout', None)
402 timeout = header.get('timeout', None)
403 if timeout:
403 if timeout:
404 # cast to float, because jsonlib returns floats as decimal.Decimal,
404 # cast to float, because jsonlib returns floats as decimal.Decimal,
405 # which timedelta does not accept
405 # which timedelta does not accept
406 timeout = datetime.now() + timedelta(0,float(timeout),0)
406 timeout = datetime.now() + timedelta(0,float(timeout),0)
407
407
408 job = Job(msg_id=msg_id, raw_msg=raw_msg, idents=idents, msg=msg,
408 job = Job(msg_id=msg_id, raw_msg=raw_msg, idents=idents, msg=msg,
409 header=header, targets=targets, after=after, follow=follow,
409 header=header, targets=targets, after=after, follow=follow,
410 timeout=timeout,
410 timeout=timeout,
411 )
411 )
412
412
413 # validate and reduce dependencies:
413 # validate and reduce dependencies:
414 for dep in after,follow:
414 for dep in after,follow:
415 if not dep: # empty dependency
415 if not dep: # empty dependency
416 continue
416 continue
417 # check valid:
417 # check valid:
418 if msg_id in dep or dep.difference(self.all_ids):
418 if msg_id in dep or dep.difference(self.all_ids):
419 self.depending[msg_id] = job
419 self.depending[msg_id] = job
420 return self.fail_unreachable(msg_id, error.InvalidDependency)
420 return self.fail_unreachable(msg_id, error.InvalidDependency)
421 # check if unreachable:
421 # check if unreachable:
422 if dep.unreachable(self.all_completed, self.all_failed):
422 if dep.unreachable(self.all_completed, self.all_failed):
423 self.depending[msg_id] = job
423 self.depending[msg_id] = job
424 return self.fail_unreachable(msg_id)
424 return self.fail_unreachable(msg_id)
425
425
426 if after.check(self.all_completed, self.all_failed):
426 if after.check(self.all_completed, self.all_failed):
427 # time deps already met, try to run
427 # time deps already met, try to run
428 if not self.maybe_run(job):
428 if not self.maybe_run(job):
429 # can't run yet
429 # can't run yet
430 if msg_id not in self.all_failed:
430 if msg_id not in self.all_failed:
431 # could have failed as unreachable
431 # could have failed as unreachable
432 self.save_unmet(job)
432 self.save_unmet(job)
433 else:
433 else:
434 self.save_unmet(job)
434 self.save_unmet(job)
435
435
436 def audit_timeouts(self):
436 def audit_timeouts(self):
437 """Audit all waiting tasks for expired timeouts."""
437 """Audit all waiting tasks for expired timeouts."""
438 now = datetime.now()
438 now = datetime.now()
439 for msg_id in self.depending.keys():
439 for msg_id in self.depending.keys():
440 # must recheck, in case one failure cascaded to another:
440 # must recheck, in case one failure cascaded to another:
441 if msg_id in self.depending:
441 if msg_id in self.depending:
442 job = self.depending[msg_id]
442 job = self.depending[msg_id]
443 if job.timeout and job.timeout < now:
443 if job.timeout and job.timeout < now:
444 self.fail_unreachable(msg_id, error.TaskTimeout)
444 self.fail_unreachable(msg_id, error.TaskTimeout)
445
445
446 def fail_unreachable(self, msg_id, why=error.ImpossibleDependency):
446 def fail_unreachable(self, msg_id, why=error.ImpossibleDependency):
447 """a task has become unreachable, send a reply with an ImpossibleDependency
447 """a task has become unreachable, send a reply with an ImpossibleDependency
448 error."""
448 error."""
449 if msg_id not in self.depending:
449 if msg_id not in self.depending:
450 self.log.error("msg %r already failed!", msg_id)
450 self.log.error("msg %r already failed!", msg_id)
451 return
451 return
452 job = self.depending.pop(msg_id)
452 job = self.depending.pop(msg_id)
453 for mid in job.dependents:
453 for mid in job.dependents:
454 if mid in self.graph:
454 if mid in self.graph:
455 self.graph[mid].remove(msg_id)
455 self.graph[mid].remove(msg_id)
456
456
457 try:
457 try:
458 raise why()
458 raise why()
459 except:
459 except:
460 content = error.wrap_exception()
460 content = error.wrap_exception()
461
461
462 self.all_done.add(msg_id)
462 self.all_done.add(msg_id)
463 self.all_failed.add(msg_id)
463 self.all_failed.add(msg_id)
464
464
465 msg = self.session.send(self.client_stream, 'apply_reply', content,
465 msg = self.session.send(self.client_stream, 'apply_reply', content,
466 parent=job.header, ident=job.idents)
466 parent=job.header, ident=job.idents)
467 self.session.send(self.mon_stream, msg, ident=[b'outtask']+job.idents)
467 self.session.send(self.mon_stream, msg, ident=[b'outtask']+job.idents)
468
468
469 self.update_graph(msg_id, success=False)
469 self.update_graph(msg_id, success=False)
470
470
471 def maybe_run(self, job):
471 def maybe_run(self, job):
472 """check location dependencies, and run if they are met."""
472 """check location dependencies, and run if they are met."""
473 msg_id = job.msg_id
473 msg_id = job.msg_id
474 self.log.debug("Attempting to assign task %s", msg_id)
474 self.log.debug("Attempting to assign task %s", msg_id)
475 if not self.targets:
475 if not self.targets:
476 # no engines, definitely can't run
476 # no engines, definitely can't run
477 return False
477 return False
478
478
479 if job.follow or job.targets or job.blacklist or self.hwm:
479 if job.follow or job.targets or job.blacklist or self.hwm:
480 # we need a can_run filter
480 # we need a can_run filter
481 def can_run(idx):
481 def can_run(idx):
482 # check hwm
482 # check hwm
483 if self.hwm and self.loads[idx] == self.hwm:
483 if self.hwm and self.loads[idx] == self.hwm:
484 return False
484 return False
485 target = self.targets[idx]
485 target = self.targets[idx]
486 # check blacklist
486 # check blacklist
487 if target in job.blacklist:
487 if target in job.blacklist:
488 return False
488 return False
489 # check targets
489 # check targets
490 if job.targets and target not in job.targets:
490 if job.targets and target not in job.targets:
491 return False
491 return False
492 # check follow
492 # check follow
493 return job.follow.check(self.completed[target], self.failed[target])
493 return job.follow.check(self.completed[target], self.failed[target])
494
494
495 indices = filter(can_run, range(len(self.targets)))
495 indices = filter(can_run, range(len(self.targets)))
496
496
497 if not indices:
497 if not indices:
498 # couldn't run
498 # couldn't run
499 if job.follow.all:
499 if job.follow.all:
500 # check follow for impossibility
500 # check follow for impossibility
501 dests = set()
501 dests = set()
502 relevant = set()
502 relevant = set()
503 if job.follow.success:
503 if job.follow.success:
504 relevant = self.all_completed
504 relevant = self.all_completed
505 if job.follow.failure:
505 if job.follow.failure:
506 relevant = relevant.union(self.all_failed)
506 relevant = relevant.union(self.all_failed)
507 for m in job.follow.intersection(relevant):
507 for m in job.follow.intersection(relevant):
508 dests.add(self.destinations[m])
508 dests.add(self.destinations[m])
509 if len(dests) > 1:
509 if len(dests) > 1:
510 self.depending[msg_id] = job
510 self.depending[msg_id] = job
511 self.fail_unreachable(msg_id)
511 self.fail_unreachable(msg_id)
512 return False
512 return False
513 if job.targets:
513 if job.targets:
514 # check blacklist+targets for impossibility
514 # check blacklist+targets for impossibility
515 job.targets.difference_update(blacklist)
515 job.targets.difference_update(job.blacklist)
516 if not job.targets or not job.targets.intersection(self.targets):
516 if not job.targets or not job.targets.intersection(self.targets):
517 self.depending[msg_id] = job
517 self.depending[msg_id] = job
518 self.fail_unreachable(msg_id)
518 self.fail_unreachable(msg_id)
519 return False
519 return False
520 return False
520 return False
521 else:
521 else:
522 indices = None
522 indices = None
523
523
524 self.submit_task(job, indices)
524 self.submit_task(job, indices)
525 return True
525 return True
526
526
527 def save_unmet(self, job):
527 def save_unmet(self, job):
528 """Save a message for later submission when its dependencies are met."""
528 """Save a message for later submission when its dependencies are met."""
529 msg_id = job.msg_id
529 msg_id = job.msg_id
530 self.depending[msg_id] = job
530 self.depending[msg_id] = job
531 # track the ids in follow or after, but not those already finished
531 # track the ids in follow or after, but not those already finished
532 for dep_id in job.after.union(job.follow).difference(self.all_done):
532 for dep_id in job.after.union(job.follow).difference(self.all_done):
533 if dep_id not in self.graph:
533 if dep_id not in self.graph:
534 self.graph[dep_id] = set()
534 self.graph[dep_id] = set()
535 self.graph[dep_id].add(msg_id)
535 self.graph[dep_id].add(msg_id)
536
536
537 def submit_task(self, job, indices=None):
537 def submit_task(self, job, indices=None):
538 """Submit a task to any of a subset of our targets."""
538 """Submit a task to any of a subset of our targets."""
539 if indices:
539 if indices:
540 loads = [self.loads[i] for i in indices]
540 loads = [self.loads[i] for i in indices]
541 else:
541 else:
542 loads = self.loads
542 loads = self.loads
543 idx = self.scheme(loads)
543 idx = self.scheme(loads)
544 if indices:
544 if indices:
545 idx = indices[idx]
545 idx = indices[idx]
546 target = self.targets[idx]
546 target = self.targets[idx]
547 # print (target, map(str, msg[:3]))
547 # print (target, map(str, msg[:3]))
548 # send job to the engine
548 # send job to the engine
549 self.engine_stream.send(target, flags=zmq.SNDMORE, copy=False)
549 self.engine_stream.send(target, flags=zmq.SNDMORE, copy=False)
550 self.engine_stream.send_multipart(job.raw_msg, copy=False)
550 self.engine_stream.send_multipart(job.raw_msg, copy=False)
551 # update load
551 # update load
552 self.add_job(idx)
552 self.add_job(idx)
553 self.pending[target][job.msg_id] = job
553 self.pending[target][job.msg_id] = job
554 # notify Hub
554 # notify Hub
555 content = dict(msg_id=job.msg_id, engine_id=target.decode('ascii'))
555 content = dict(msg_id=job.msg_id, engine_id=target.decode('ascii'))
556 self.session.send(self.mon_stream, 'task_destination', content=content,
556 self.session.send(self.mon_stream, 'task_destination', content=content,
557 ident=[b'tracktask',self.ident])
557 ident=[b'tracktask',self.ident])
558
558
559
559
560 #-----------------------------------------------------------------------
560 #-----------------------------------------------------------------------
561 # Result Handling
561 # Result Handling
562 #-----------------------------------------------------------------------
562 #-----------------------------------------------------------------------
563 def dispatch_result(self, raw_msg):
563 def dispatch_result(self, raw_msg):
564 """dispatch method for result replies"""
564 """dispatch method for result replies"""
565 try:
565 try:
566 idents,msg = self.session.feed_identities(raw_msg, copy=False)
566 idents,msg = self.session.feed_identities(raw_msg, copy=False)
567 msg = self.session.unserialize(msg, content=False, copy=False)
567 msg = self.session.unserialize(msg, content=False, copy=False)
568 engine = idents[0]
568 engine = idents[0]
569 try:
569 try:
570 idx = self.targets.index(engine)
570 idx = self.targets.index(engine)
571 except ValueError:
571 except ValueError:
572 pass # skip load-update for dead engines
572 pass # skip load-update for dead engines
573 else:
573 else:
574 self.finish_job(idx)
574 self.finish_job(idx)
575 except Exception:
575 except Exception:
576 self.log.error("task::Invaid result: %r", raw_msg, exc_info=True)
576 self.log.error("task::Invaid result: %r", raw_msg, exc_info=True)
577 return
577 return
578
578
579 header = msg['header']
579 header = msg['header']
580 parent = msg['parent_header']
580 parent = msg['parent_header']
581 if header.get('dependencies_met', True):
581 if header.get('dependencies_met', True):
582 success = (header['status'] == 'ok')
582 success = (header['status'] == 'ok')
583 msg_id = parent['msg_id']
583 msg_id = parent['msg_id']
584 retries = self.retries[msg_id]
584 retries = self.retries[msg_id]
585 if not success and retries > 0:
585 if not success and retries > 0:
586 # failed
586 # failed
587 self.retries[msg_id] = retries - 1
587 self.retries[msg_id] = retries - 1
588 self.handle_unmet_dependency(idents, parent)
588 self.handle_unmet_dependency(idents, parent)
589 else:
589 else:
590 del self.retries[msg_id]
590 del self.retries[msg_id]
591 # relay to client and update graph
591 # relay to client and update graph
592 self.handle_result(idents, parent, raw_msg, success)
592 self.handle_result(idents, parent, raw_msg, success)
593 # send to Hub monitor
593 # send to Hub monitor
594 self.mon_stream.send_multipart([b'outtask']+raw_msg, copy=False)
594 self.mon_stream.send_multipart([b'outtask']+raw_msg, copy=False)
595 else:
595 else:
596 self.handle_unmet_dependency(idents, parent)
596 self.handle_unmet_dependency(idents, parent)
597
597
598 def handle_result(self, idents, parent, raw_msg, success=True):
598 def handle_result(self, idents, parent, raw_msg, success=True):
599 """handle a real task result, either success or failure"""
599 """handle a real task result, either success or failure"""
600 # first, relay result to client
600 # first, relay result to client
601 engine = idents[0]
601 engine = idents[0]
602 client = idents[1]
602 client = idents[1]
603 # swap_ids for XREP-XREP mirror
603 # swap_ids for XREP-XREP mirror
604 raw_msg[:2] = [client,engine]
604 raw_msg[:2] = [client,engine]
605 # print (map(str, raw_msg[:4]))
605 # print (map(str, raw_msg[:4]))
606 self.client_stream.send_multipart(raw_msg, copy=False)
606 self.client_stream.send_multipart(raw_msg, copy=False)
607 # now, update our data structures
607 # now, update our data structures
608 msg_id = parent['msg_id']
608 msg_id = parent['msg_id']
609 self.pending[engine].pop(msg_id)
609 self.pending[engine].pop(msg_id)
610 if success:
610 if success:
611 self.completed[engine].add(msg_id)
611 self.completed[engine].add(msg_id)
612 self.all_completed.add(msg_id)
612 self.all_completed.add(msg_id)
613 else:
613 else:
614 self.failed[engine].add(msg_id)
614 self.failed[engine].add(msg_id)
615 self.all_failed.add(msg_id)
615 self.all_failed.add(msg_id)
616 self.all_done.add(msg_id)
616 self.all_done.add(msg_id)
617 self.destinations[msg_id] = engine
617 self.destinations[msg_id] = engine
618
618
619 self.update_graph(msg_id, success)
619 self.update_graph(msg_id, success)
620
620
621 def handle_unmet_dependency(self, idents, parent):
621 def handle_unmet_dependency(self, idents, parent):
622 """handle an unmet dependency"""
622 """handle an unmet dependency"""
623 engine = idents[0]
623 engine = idents[0]
624 msg_id = parent['msg_id']
624 msg_id = parent['msg_id']
625
625
626 job = self.pending[engine].pop(msg_id)
626 job = self.pending[engine].pop(msg_id)
627 job.blacklist.add(engine)
627 job.blacklist.add(engine)
628
628
629 if job.blacklist == job.targets:
629 if job.blacklist == job.targets:
630 self.depending[msg_id] = job
630 self.depending[msg_id] = job
631 self.fail_unreachable(msg_id)
631 self.fail_unreachable(msg_id)
632 elif not self.maybe_run(job):
632 elif not self.maybe_run(job):
633 # resubmit failed
633 # resubmit failed
634 if msg_id not in self.all_failed:
634 if msg_id not in self.all_failed:
635 # put it back in our dependency tree
635 # put it back in our dependency tree
636 self.save_unmet(job)
636 self.save_unmet(job)
637
637
638 if self.hwm:
638 if self.hwm:
639 try:
639 try:
640 idx = self.targets.index(engine)
640 idx = self.targets.index(engine)
641 except ValueError:
641 except ValueError:
642 pass # skip load-update for dead engines
642 pass # skip load-update for dead engines
643 else:
643 else:
644 if self.loads[idx] == self.hwm-1:
644 if self.loads[idx] == self.hwm-1:
645 self.update_graph(None)
645 self.update_graph(None)
646
646
647
647
648
648
649 def update_graph(self, dep_id=None, success=True):
649 def update_graph(self, dep_id=None, success=True):
650 """dep_id just finished. Update our dependency
650 """dep_id just finished. Update our dependency
651 graph and submit any jobs that just became runable.
651 graph and submit any jobs that just became runable.
652
652
653 Called with dep_id=None to update entire graph for hwm, but without finishing
653 Called with dep_id=None to update entire graph for hwm, but without finishing
654 a task.
654 a task.
655 """
655 """
656 # print ("\n\n***********")
656 # print ("\n\n***********")
657 # pprint (dep_id)
657 # pprint (dep_id)
658 # pprint (self.graph)
658 # pprint (self.graph)
659 # pprint (self.depending)
659 # pprint (self.depending)
660 # pprint (self.all_completed)
660 # pprint (self.all_completed)
661 # pprint (self.all_failed)
661 # pprint (self.all_failed)
662 # print ("\n\n***********\n\n")
662 # print ("\n\n***********\n\n")
663 # update any jobs that depended on the dependency
663 # update any jobs that depended on the dependency
664 jobs = self.graph.pop(dep_id, [])
664 jobs = self.graph.pop(dep_id, [])
665
665
666 # recheck *all* jobs if
666 # recheck *all* jobs if
667 # a) we have HWM and an engine just become no longer full
667 # a) we have HWM and an engine just become no longer full
668 # or b) dep_id was given as None
668 # or b) dep_id was given as None
669
669
670 if dep_id is None or self.hwm and any( [ load==self.hwm-1 for load in self.loads ]):
670 if dep_id is None or self.hwm and any( [ load==self.hwm-1 for load in self.loads ]):
671 jobs = self.depending.keys()
671 jobs = self.depending.keys()
672
672
673 for msg_id in sorted(jobs, key=lambda msg_id: self.depending[msg_id].timestamp):
673 for msg_id in sorted(jobs, key=lambda msg_id: self.depending[msg_id].timestamp):
674 job = self.depending[msg_id]
674 job = self.depending[msg_id]
675
675
676 if job.after.unreachable(self.all_completed, self.all_failed)\
676 if job.after.unreachable(self.all_completed, self.all_failed)\
677 or job.follow.unreachable(self.all_completed, self.all_failed):
677 or job.follow.unreachable(self.all_completed, self.all_failed):
678 self.fail_unreachable(msg_id)
678 self.fail_unreachable(msg_id)
679
679
680 elif job.after.check(self.all_completed, self.all_failed): # time deps met, maybe run
680 elif job.after.check(self.all_completed, self.all_failed): # time deps met, maybe run
681 if self.maybe_run(job):
681 if self.maybe_run(job):
682
682
683 self.depending.pop(msg_id)
683 self.depending.pop(msg_id)
684 for mid in job.dependents:
684 for mid in job.dependents:
685 if mid in self.graph:
685 if mid in self.graph:
686 self.graph[mid].remove(msg_id)
686 self.graph[mid].remove(msg_id)
687
687
688 #----------------------------------------------------------------------
688 #----------------------------------------------------------------------
689 # methods to be overridden by subclasses
689 # methods to be overridden by subclasses
690 #----------------------------------------------------------------------
690 #----------------------------------------------------------------------
691
691
692 def add_job(self, idx):
692 def add_job(self, idx):
693 """Called after self.targets[idx] just got the job with header.
693 """Called after self.targets[idx] just got the job with header.
694 Override with subclasses. The default ordering is simple LRU.
694 Override with subclasses. The default ordering is simple LRU.
695 The default loads are the number of outstanding jobs."""
695 The default loads are the number of outstanding jobs."""
696 self.loads[idx] += 1
696 self.loads[idx] += 1
697 for lis in (self.targets, self.loads):
697 for lis in (self.targets, self.loads):
698 lis.append(lis.pop(idx))
698 lis.append(lis.pop(idx))
699
699
700
700
701 def finish_job(self, idx):
701 def finish_job(self, idx):
702 """Called after self.targets[idx] just finished a job.
702 """Called after self.targets[idx] just finished a job.
703 Override with subclasses."""
703 Override with subclasses."""
704 self.loads[idx] -= 1
704 self.loads[idx] -= 1
705
705
706
706
707
707
708 def launch_scheduler(in_addr, out_addr, mon_addr, not_addr, config=None,
708 def launch_scheduler(in_addr, out_addr, mon_addr, not_addr, config=None,
709 logname='root', log_url=None, loglevel=logging.DEBUG,
709 logname='root', log_url=None, loglevel=logging.DEBUG,
710 identity=b'task', in_thread=False):
710 identity=b'task', in_thread=False):
711
711
712 ZMQStream = zmqstream.ZMQStream
712 ZMQStream = zmqstream.ZMQStream
713
713
714 if config:
714 if config:
715 # unwrap dict back into Config
715 # unwrap dict back into Config
716 config = Config(config)
716 config = Config(config)
717
717
718 if in_thread:
718 if in_thread:
719 # use instance() to get the same Context/Loop as our parent
719 # use instance() to get the same Context/Loop as our parent
720 ctx = zmq.Context.instance()
720 ctx = zmq.Context.instance()
721 loop = ioloop.IOLoop.instance()
721 loop = ioloop.IOLoop.instance()
722 else:
722 else:
723 # in a process, don't use instance()
723 # in a process, don't use instance()
724 # for safety with multiprocessing
724 # for safety with multiprocessing
725 ctx = zmq.Context()
725 ctx = zmq.Context()
726 loop = ioloop.IOLoop()
726 loop = ioloop.IOLoop()
727 ins = ZMQStream(ctx.socket(zmq.ROUTER),loop)
727 ins = ZMQStream(ctx.socket(zmq.ROUTER),loop)
728 ins.setsockopt(zmq.IDENTITY, identity)
728 ins.setsockopt(zmq.IDENTITY, identity)
729 ins.bind(in_addr)
729 ins.bind(in_addr)
730
730
731 outs = ZMQStream(ctx.socket(zmq.ROUTER),loop)
731 outs = ZMQStream(ctx.socket(zmq.ROUTER),loop)
732 outs.setsockopt(zmq.IDENTITY, identity)
732 outs.setsockopt(zmq.IDENTITY, identity)
733 outs.bind(out_addr)
733 outs.bind(out_addr)
734 mons = zmqstream.ZMQStream(ctx.socket(zmq.PUB),loop)
734 mons = zmqstream.ZMQStream(ctx.socket(zmq.PUB),loop)
735 mons.connect(mon_addr)
735 mons.connect(mon_addr)
736 nots = zmqstream.ZMQStream(ctx.socket(zmq.SUB),loop)
736 nots = zmqstream.ZMQStream(ctx.socket(zmq.SUB),loop)
737 nots.setsockopt(zmq.SUBSCRIBE, b'')
737 nots.setsockopt(zmq.SUBSCRIBE, b'')
738 nots.connect(not_addr)
738 nots.connect(not_addr)
739
739
740 # setup logging.
740 # setup logging.
741 if in_thread:
741 if in_thread:
742 log = Application.instance().log
742 log = Application.instance().log
743 else:
743 else:
744 if log_url:
744 if log_url:
745 log = connect_logger(logname, ctx, log_url, root="scheduler", loglevel=loglevel)
745 log = connect_logger(logname, ctx, log_url, root="scheduler", loglevel=loglevel)
746 else:
746 else:
747 log = local_logger(logname, loglevel)
747 log = local_logger(logname, loglevel)
748
748
749 scheduler = TaskScheduler(client_stream=ins, engine_stream=outs,
749 scheduler = TaskScheduler(client_stream=ins, engine_stream=outs,
750 mon_stream=mons, notifier_stream=nots,
750 mon_stream=mons, notifier_stream=nots,
751 loop=loop, log=log,
751 loop=loop, log=log,
752 config=config)
752 config=config)
753 scheduler.start()
753 scheduler.start()
754 if not in_thread:
754 if not in_thread:
755 try:
755 try:
756 loop.start()
756 loop.start()
757 except KeyboardInterrupt:
757 except KeyboardInterrupt:
758 scheduler.log.critical("Interrupted, exiting...")
758 scheduler.log.critical("Interrupted, exiting...")
759
759
@@ -1,120 +1,122 b''
1 """toplevel setup/teardown for parallel tests."""
1 """toplevel setup/teardown for parallel tests."""
2
2
3 #-------------------------------------------------------------------------------
3 #-------------------------------------------------------------------------------
4 # Copyright (C) 2011 The IPython Development Team
4 # Copyright (C) 2011 The IPython Development Team
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 #-------------------------------------------------------------------------------
10 #-------------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-------------------------------------------------------------------------------
12 #-------------------------------------------------------------------------------
13
13
14 import os
14 import os
15 import tempfile
15 import tempfile
16 import time
16 import time
17 from subprocess import Popen
17 from subprocess import Popen
18
18
19 from IPython.utils.path import get_ipython_dir
19 from IPython.utils.path import get_ipython_dir
20 from IPython.parallel import Client
20 from IPython.parallel import Client
21 from IPython.parallel.apps.launcher import (LocalProcessLauncher,
21 from IPython.parallel.apps.launcher import (LocalProcessLauncher,
22 ipengine_cmd_argv,
22 ipengine_cmd_argv,
23 ipcontroller_cmd_argv,
23 ipcontroller_cmd_argv,
24 SIGKILL)
24 SIGKILL,
25 ProcessStateError,
26 )
25
27
26 # globals
28 # globals
27 launchers = []
29 launchers = []
28 blackhole = open(os.devnull, 'w')
30 blackhole = open(os.devnull, 'w')
29
31
30 # Launcher class
32 # Launcher class
31 class TestProcessLauncher(LocalProcessLauncher):
33 class TestProcessLauncher(LocalProcessLauncher):
32 """subclass LocalProcessLauncher, to prevent extra sockets and threads being created on Windows"""
34 """subclass LocalProcessLauncher, to prevent extra sockets and threads being created on Windows"""
33 def start(self):
35 def start(self):
34 if self.state == 'before':
36 if self.state == 'before':
35 self.process = Popen(self.args,
37 self.process = Popen(self.args,
36 stdout=blackhole, stderr=blackhole,
38 stdout=blackhole, stderr=blackhole,
37 env=os.environ,
39 env=os.environ,
38 cwd=self.work_dir
40 cwd=self.work_dir
39 )
41 )
40 self.notify_start(self.process.pid)
42 self.notify_start(self.process.pid)
41 self.poll = self.process.poll
43 self.poll = self.process.poll
42 else:
44 else:
43 s = 'The process was already started and has state: %r' % self.state
45 s = 'The process was already started and has state: %r' % self.state
44 raise ProcessStateError(s)
46 raise ProcessStateError(s)
45
47
46 # nose setup/teardown
48 # nose setup/teardown
47
49
48 def setup():
50 def setup():
49 cluster_dir = os.path.join(get_ipython_dir(), 'profile_iptest')
51 cluster_dir = os.path.join(get_ipython_dir(), 'profile_iptest')
50 engine_json = os.path.join(cluster_dir, 'security', 'ipcontroller-engine.json')
52 engine_json = os.path.join(cluster_dir, 'security', 'ipcontroller-engine.json')
51 client_json = os.path.join(cluster_dir, 'security', 'ipcontroller-client.json')
53 client_json = os.path.join(cluster_dir, 'security', 'ipcontroller-client.json')
52 for json in (engine_json, client_json):
54 for json in (engine_json, client_json):
53 if os.path.exists(json):
55 if os.path.exists(json):
54 os.remove(json)
56 os.remove(json)
55
57
56 cp = TestProcessLauncher()
58 cp = TestProcessLauncher()
57 cp.cmd_and_args = ipcontroller_cmd_argv + \
59 cp.cmd_and_args = ipcontroller_cmd_argv + \
58 ['--profile=iptest', '--log-level=50', '--ping=250']
60 ['--profile=iptest', '--log-level=50', '--ping=250']
59 cp.start()
61 cp.start()
60 launchers.append(cp)
62 launchers.append(cp)
61 tic = time.time()
63 tic = time.time()
62 while not os.path.exists(engine_json) or not os.path.exists(client_json):
64 while not os.path.exists(engine_json) or not os.path.exists(client_json):
63 if cp.poll() is not None:
65 if cp.poll() is not None:
64 print cp.poll()
66 print cp.poll()
65 raise RuntimeError("The test controller failed to start.")
67 raise RuntimeError("The test controller failed to start.")
66 elif time.time()-tic > 10:
68 elif time.time()-tic > 10:
67 raise RuntimeError("Timeout waiting for the test controller to start.")
69 raise RuntimeError("Timeout waiting for the test controller to start.")
68 time.sleep(0.1)
70 time.sleep(0.1)
69 add_engines(1)
71 add_engines(1)
70
72
71 def add_engines(n=1, profile='iptest', total=False):
73 def add_engines(n=1, profile='iptest', total=False):
72 """add a number of engines to a given profile.
74 """add a number of engines to a given profile.
73
75
74 If total is True, then already running engines are counted, and only
76 If total is True, then already running engines are counted, and only
75 the additional engines necessary (if any) are started.
77 the additional engines necessary (if any) are started.
76 """
78 """
77 rc = Client(profile=profile)
79 rc = Client(profile=profile)
78 base = len(rc)
80 base = len(rc)
79
81
80 if total:
82 if total:
81 n = max(n - base, 0)
83 n = max(n - base, 0)
82
84
83 eps = []
85 eps = []
84 for i in range(n):
86 for i in range(n):
85 ep = TestProcessLauncher()
87 ep = TestProcessLauncher()
86 ep.cmd_and_args = ipengine_cmd_argv + ['--profile=%s'%profile, '--log-level=50']
88 ep.cmd_and_args = ipengine_cmd_argv + ['--profile=%s'%profile, '--log-level=50']
87 ep.start()
89 ep.start()
88 launchers.append(ep)
90 launchers.append(ep)
89 eps.append(ep)
91 eps.append(ep)
90 tic = time.time()
92 tic = time.time()
91 while len(rc) < base+n:
93 while len(rc) < base+n:
92 if any([ ep.poll() is not None for ep in eps ]):
94 if any([ ep.poll() is not None for ep in eps ]):
93 raise RuntimeError("A test engine failed to start.")
95 raise RuntimeError("A test engine failed to start.")
94 elif time.time()-tic > 10:
96 elif time.time()-tic > 10:
95 raise RuntimeError("Timeout waiting for engines to connect.")
97 raise RuntimeError("Timeout waiting for engines to connect.")
96 time.sleep(.1)
98 time.sleep(.1)
97 rc.spin()
99 rc.spin()
98 rc.close()
100 rc.close()
99 return eps
101 return eps
100
102
101 def teardown():
103 def teardown():
102 time.sleep(1)
104 time.sleep(1)
103 while launchers:
105 while launchers:
104 p = launchers.pop()
106 p = launchers.pop()
105 if p.poll() is None:
107 if p.poll() is None:
106 try:
108 try:
107 p.stop()
109 p.stop()
108 except Exception, e:
110 except Exception, e:
109 print e
111 print e
110 pass
112 pass
111 if p.poll() is None:
113 if p.poll() is None:
112 time.sleep(.25)
114 time.sleep(.25)
113 if p.poll() is None:
115 if p.poll() is None:
114 try:
116 try:
115 print 'cleaning up test process...'
117 print 'cleaning up test process...'
116 p.signal(SIGKILL)
118 p.signal(SIGKILL)
117 except:
119 except:
118 print "couldn't shutdown process: ", p
120 print "couldn't shutdown process: ", p
119 blackhole.close()
121 blackhole.close()
120
122
@@ -1,364 +1,364 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 """ PickleShare - a small 'shelve' like datastore with concurrency support
3 """ PickleShare - a small 'shelve' like datastore with concurrency support
4
4
5 Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike
5 Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike
6 shelve, many processes can access the database simultaneously. Changing a
6 shelve, many processes can access the database simultaneously. Changing a
7 value in database is immediately visible to other processes accessing the
7 value in database is immediately visible to other processes accessing the
8 same database.
8 same database.
9
9
10 Concurrency is possible because the values are stored in separate files. Hence
10 Concurrency is possible because the values are stored in separate files. Hence
11 the "database" is a directory where *all* files are governed by PickleShare.
11 the "database" is a directory where *all* files are governed by PickleShare.
12
12
13 Example usage::
13 Example usage::
14
14
15 from pickleshare import *
15 from pickleshare import *
16 db = PickleShareDB('~/testpickleshare')
16 db = PickleShareDB('~/testpickleshare')
17 db.clear()
17 db.clear()
18 print "Should be empty:",db.items()
18 print "Should be empty:",db.items()
19 db['hello'] = 15
19 db['hello'] = 15
20 db['aku ankka'] = [1,2,313]
20 db['aku ankka'] = [1,2,313]
21 db['paths/are/ok/key'] = [1,(5,46)]
21 db['paths/are/ok/key'] = [1,(5,46)]
22 print db.keys()
22 print db.keys()
23 del db['aku ankka']
23 del db['aku ankka']
24
24
25 This module is certainly not ZODB, but can be used for low-load
25 This module is certainly not ZODB, but can be used for low-load
26 (non-mission-critical) situations where tiny code size trumps the
26 (non-mission-critical) situations where tiny code size trumps the
27 advanced features of a "real" object database.
27 advanced features of a "real" object database.
28
28
29 Installation guide: easy_install pickleshare
29 Installation guide: easy_install pickleshare
30
30
31 Author: Ville Vainio <vivainio@gmail.com>
31 Author: Ville Vainio <vivainio@gmail.com>
32 License: MIT open source license.
32 License: MIT open source license.
33
33
34 """
34 """
35
35
36 from IPython.external.path import path as Path
36 from IPython.external.path import path as Path
37 import os,stat,time
37 import os,stat,time
38 import collections
38 import collections
39 import cPickle as pickle
39 import cPickle as pickle
40 import glob
40 import glob
41
41
42 def gethashfile(key):
42 def gethashfile(key):
43 return ("%02x" % abs(hash(key) % 256))[-2:]
43 return ("%02x" % abs(hash(key) % 256))[-2:]
44
44
45 _sentinel = object()
45 _sentinel = object()
46
46
47 class PickleShareDB(collections.MutableMapping):
47 class PickleShareDB(collections.MutableMapping):
48 """ The main 'connection' object for PickleShare database """
48 """ The main 'connection' object for PickleShare database """
49 def __init__(self,root):
49 def __init__(self,root):
50 """ Return a db object that will manage the specied directory"""
50 """ Return a db object that will manage the specied directory"""
51 self.root = Path(root).expanduser().abspath()
51 self.root = Path(root).expanduser().abspath()
52 if not self.root.isdir():
52 if not self.root.isdir():
53 self.root.makedirs()
53 self.root.makedirs()
54 # cache has { 'key' : (obj, orig_mod_time) }
54 # cache has { 'key' : (obj, orig_mod_time) }
55 self.cache = {}
55 self.cache = {}
56
56
57
57
58 def __getitem__(self,key):
58 def __getitem__(self,key):
59 """ db['key'] reading """
59 """ db['key'] reading """
60 fil = self.root / key
60 fil = self.root / key
61 try:
61 try:
62 mtime = (fil.stat()[stat.ST_MTIME])
62 mtime = (fil.stat()[stat.ST_MTIME])
63 except OSError:
63 except OSError:
64 raise KeyError(key)
64 raise KeyError(key)
65
65
66 if fil in self.cache and mtime == self.cache[fil][1]:
66 if fil in self.cache and mtime == self.cache[fil][1]:
67 return self.cache[fil][0]
67 return self.cache[fil][0]
68 try:
68 try:
69 # The cached item has expired, need to read
69 # The cached item has expired, need to read
70 obj = pickle.loads(fil.open("rb").read())
70 obj = pickle.loads(fil.open("rb").read())
71 except:
71 except:
72 raise KeyError(key)
72 raise KeyError(key)
73
73
74 self.cache[fil] = (obj,mtime)
74 self.cache[fil] = (obj,mtime)
75 return obj
75 return obj
76
76
77 def __setitem__(self,key,value):
77 def __setitem__(self,key,value):
78 """ db['key'] = 5 """
78 """ db['key'] = 5 """
79 fil = self.root / key
79 fil = self.root / key
80 parent = fil.parent
80 parent = fil.parent
81 if parent and not parent.isdir():
81 if parent and not parent.isdir():
82 parent.makedirs()
82 parent.makedirs()
83 # We specify protocol 2, so that we can mostly go between Python 2
83 # We specify protocol 2, so that we can mostly go between Python 2
84 # and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete.
84 # and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete.
85 pickled = pickle.dump(value,fil.open('wb'), protocol=2)
85 pickled = pickle.dump(value,fil.open('wb'), protocol=2)
86 try:
86 try:
87 self.cache[fil] = (value,fil.mtime)
87 self.cache[fil] = (value,fil.mtime)
88 except OSError,e:
88 except OSError,e:
89 if e.errno != 2:
89 if e.errno != 2:
90 raise
90 raise
91
91
92 def hset(self, hashroot, key, value):
92 def hset(self, hashroot, key, value):
93 """ hashed set """
93 """ hashed set """
94 hroot = self.root / hashroot
94 hroot = self.root / hashroot
95 if not hroot.isdir():
95 if not hroot.isdir():
96 hroot.makedirs()
96 hroot.makedirs()
97 hfile = hroot / gethashfile(key)
97 hfile = hroot / gethashfile(key)
98 d = self.get(hfile, {})
98 d = self.get(hfile, {})
99 d.update( {key : value})
99 d.update( {key : value})
100 self[hfile] = d
100 self[hfile] = d
101
101
102
102
103
103
104 def hget(self, hashroot, key, default = _sentinel, fast_only = True):
104 def hget(self, hashroot, key, default = _sentinel, fast_only = True):
105 """ hashed get """
105 """ hashed get """
106 hroot = self.root / hashroot
106 hroot = self.root / hashroot
107 hfile = hroot / gethashfile(key)
107 hfile = hroot / gethashfile(key)
108
108
109 d = self.get(hfile, _sentinel )
109 d = self.get(hfile, _sentinel )
110 #print "got dict",d,"from",hfile
110 #print "got dict",d,"from",hfile
111 if d is _sentinel:
111 if d is _sentinel:
112 if fast_only:
112 if fast_only:
113 if default is _sentinel:
113 if default is _sentinel:
114 raise KeyError(key)
114 raise KeyError(key)
115
115
116 return default
116 return default
117
117
118 # slow mode ok, works even after hcompress()
118 # slow mode ok, works even after hcompress()
119 d = self.hdict(hashroot)
119 d = self.hdict(hashroot)
120
120
121 return d.get(key, default)
121 return d.get(key, default)
122
122
123 def hdict(self, hashroot):
123 def hdict(self, hashroot):
124 """ Get all data contained in hashed category 'hashroot' as dict """
124 """ Get all data contained in hashed category 'hashroot' as dict """
125 hfiles = self.keys(hashroot + "/*")
125 hfiles = self.keys(hashroot + "/*")
126 hfiles.sort()
126 hfiles.sort()
127 last = len(hfiles) and hfiles[-1] or ''
127 last = len(hfiles) and hfiles[-1] or ''
128 if last.endswith('xx'):
128 if last.endswith('xx'):
129 # print "using xx"
129 # print "using xx"
130 hfiles = [last] + hfiles[:-1]
130 hfiles = [last] + hfiles[:-1]
131
131
132 all = {}
132 all = {}
133
133
134 for f in hfiles:
134 for f in hfiles:
135 # print "using",f
135 # print "using",f
136 try:
136 try:
137 all.update(self[f])
137 all.update(self[f])
138 except KeyError:
138 except KeyError:
139 print "Corrupt",f,"deleted - hset is not threadsafe!"
139 print "Corrupt",f,"deleted - hset is not threadsafe!"
140 del self[f]
140 del self[f]
141
141
142 self.uncache(f)
142 self.uncache(f)
143
143
144 return all
144 return all
145
145
146 def hcompress(self, hashroot):
146 def hcompress(self, hashroot):
147 """ Compress category 'hashroot', so hset is fast again
147 """ Compress category 'hashroot', so hset is fast again
148
148
149 hget will fail if fast_only is True for compressed items (that were
149 hget will fail if fast_only is True for compressed items (that were
150 hset before hcompress).
150 hset before hcompress).
151
151
152 """
152 """
153 hfiles = self.keys(hashroot + "/*")
153 hfiles = self.keys(hashroot + "/*")
154 all = {}
154 all = {}
155 for f in hfiles:
155 for f in hfiles:
156 # print "using",f
156 # print "using",f
157 all.update(self[f])
157 all.update(self[f])
158 self.uncache(f)
158 self.uncache(f)
159
159
160 self[hashroot + '/xx'] = all
160 self[hashroot + '/xx'] = all
161 for f in hfiles:
161 for f in hfiles:
162 p = self.root / f
162 p = self.root / f
163 if p.basename() == 'xx':
163 if p.basename() == 'xx':
164 continue
164 continue
165 p.remove()
165 p.remove()
166
166
167
167
168
168
169 def __delitem__(self,key):
169 def __delitem__(self,key):
170 """ del db["key"] """
170 """ del db["key"] """
171 fil = self.root / key
171 fil = self.root / key
172 self.cache.pop(fil,None)
172 self.cache.pop(fil,None)
173 try:
173 try:
174 fil.remove()
174 fil.remove()
175 except OSError:
175 except OSError:
176 # notfound and permission denied are ok - we
176 # notfound and permission denied are ok - we
177 # lost, the other process wins the conflict
177 # lost, the other process wins the conflict
178 pass
178 pass
179
179
180 def _normalized(self, p):
180 def _normalized(self, p):
181 """ Make a key suitable for user's eyes """
181 """ Make a key suitable for user's eyes """
182 return str(self.root.relpathto(p)).replace('\\','/')
182 return str(self.root.relpathto(p)).replace('\\','/')
183
183
184 def keys(self, globpat = None):
184 def keys(self, globpat = None):
185 """ All keys in DB, or all keys matching a glob"""
185 """ All keys in DB, or all keys matching a glob"""
186
186
187 if globpat is None:
187 if globpat is None:
188 files = self.root.walkfiles()
188 files = self.root.walkfiles()
189 else:
189 else:
190 files = [Path(p) for p in glob.glob(self.root/globpat)]
190 files = [Path(p) for p in glob.glob(self.root/globpat)]
191 return [self._normalized(p) for p in files if p.isfile()]
191 return [self._normalized(p) for p in files if p.isfile()]
192
192
193 def __iter__(self):
193 def __iter__(self):
194 return iter(keys)
194 return iter(self.keys())
195
195
196 def __len__(self):
196 def __len__(self):
197 return len(keys)
197 return len(self.keys())
198
198
199 def uncache(self,*items):
199 def uncache(self,*items):
200 """ Removes all, or specified items from cache
200 """ Removes all, or specified items from cache
201
201
202 Use this after reading a large amount of large objects
202 Use this after reading a large amount of large objects
203 to free up memory, when you won't be needing the objects
203 to free up memory, when you won't be needing the objects
204 for a while.
204 for a while.
205
205
206 """
206 """
207 if not items:
207 if not items:
208 self.cache = {}
208 self.cache = {}
209 for it in items:
209 for it in items:
210 self.cache.pop(it,None)
210 self.cache.pop(it,None)
211
211
212 def waitget(self,key, maxwaittime = 60 ):
212 def waitget(self,key, maxwaittime = 60 ):
213 """ Wait (poll) for a key to get a value
213 """ Wait (poll) for a key to get a value
214
214
215 Will wait for `maxwaittime` seconds before raising a KeyError.
215 Will wait for `maxwaittime` seconds before raising a KeyError.
216 The call exits normally if the `key` field in db gets a value
216 The call exits normally if the `key` field in db gets a value
217 within the timeout period.
217 within the timeout period.
218
218
219 Use this for synchronizing different processes or for ensuring
219 Use this for synchronizing different processes or for ensuring
220 that an unfortunately timed "db['key'] = newvalue" operation
220 that an unfortunately timed "db['key'] = newvalue" operation
221 in another process (which causes all 'get' operation to cause a
221 in another process (which causes all 'get' operation to cause a
222 KeyError for the duration of pickling) won't screw up your program
222 KeyError for the duration of pickling) won't screw up your program
223 logic.
223 logic.
224 """
224 """
225
225
226 wtimes = [0.2] * 3 + [0.5] * 2 + [1]
226 wtimes = [0.2] * 3 + [0.5] * 2 + [1]
227 tries = 0
227 tries = 0
228 waited = 0
228 waited = 0
229 while 1:
229 while 1:
230 try:
230 try:
231 val = self[key]
231 val = self[key]
232 return val
232 return val
233 except KeyError:
233 except KeyError:
234 pass
234 pass
235
235
236 if waited > maxwaittime:
236 if waited > maxwaittime:
237 raise KeyError(key)
237 raise KeyError(key)
238
238
239 time.sleep(wtimes[tries])
239 time.sleep(wtimes[tries])
240 waited+=wtimes[tries]
240 waited+=wtimes[tries]
241 if tries < len(wtimes) -1:
241 if tries < len(wtimes) -1:
242 tries+=1
242 tries+=1
243
243
244 def getlink(self,folder):
244 def getlink(self,folder):
245 """ Get a convenient link for accessing items """
245 """ Get a convenient link for accessing items """
246 return PickleShareLink(self, folder)
246 return PickleShareLink(self, folder)
247
247
248 def __repr__(self):
248 def __repr__(self):
249 return "PickleShareDB('%s')" % self.root
249 return "PickleShareDB('%s')" % self.root
250
250
251
251
252
252
253 class PickleShareLink:
253 class PickleShareLink:
254 """ A shortdand for accessing nested PickleShare data conveniently.
254 """ A shortdand for accessing nested PickleShare data conveniently.
255
255
256 Created through PickleShareDB.getlink(), example::
256 Created through PickleShareDB.getlink(), example::
257
257
258 lnk = db.getlink('myobjects/test')
258 lnk = db.getlink('myobjects/test')
259 lnk.foo = 2
259 lnk.foo = 2
260 lnk.bar = lnk.foo + 5
260 lnk.bar = lnk.foo + 5
261
261
262 """
262 """
263 def __init__(self, db, keydir ):
263 def __init__(self, db, keydir ):
264 self.__dict__.update(locals())
264 self.__dict__.update(locals())
265
265
266 def __getattr__(self,key):
266 def __getattr__(self,key):
267 return self.__dict__['db'][self.__dict__['keydir']+'/' + key]
267 return self.__dict__['db'][self.__dict__['keydir']+'/' + key]
268 def __setattr__(self,key,val):
268 def __setattr__(self,key,val):
269 self.db[self.keydir+'/' + key] = val
269 self.db[self.keydir+'/' + key] = val
270 def __repr__(self):
270 def __repr__(self):
271 db = self.__dict__['db']
271 db = self.__dict__['db']
272 keys = db.keys( self.__dict__['keydir'] +"/*")
272 keys = db.keys( self.__dict__['keydir'] +"/*")
273 return "<PickleShareLink '%s': %s>" % (
273 return "<PickleShareLink '%s': %s>" % (
274 self.__dict__['keydir'],
274 self.__dict__['keydir'],
275 ";".join([Path(k).basename() for k in keys]))
275 ";".join([Path(k).basename() for k in keys]))
276
276
277
277
278 def test():
278 def test():
279 db = PickleShareDB('~/testpickleshare')
279 db = PickleShareDB('~/testpickleshare')
280 db.clear()
280 db.clear()
281 print "Should be empty:",db.items()
281 print "Should be empty:",db.items()
282 db['hello'] = 15
282 db['hello'] = 15
283 db['aku ankka'] = [1,2,313]
283 db['aku ankka'] = [1,2,313]
284 db['paths/nest/ok/keyname'] = [1,(5,46)]
284 db['paths/nest/ok/keyname'] = [1,(5,46)]
285 db.hset('hash', 'aku', 12)
285 db.hset('hash', 'aku', 12)
286 db.hset('hash', 'ankka', 313)
286 db.hset('hash', 'ankka', 313)
287 print "12 =",db.hget('hash','aku')
287 print "12 =",db.hget('hash','aku')
288 print "313 =",db.hget('hash','ankka')
288 print "313 =",db.hget('hash','ankka')
289 print "all hashed",db.hdict('hash')
289 print "all hashed",db.hdict('hash')
290 print db.keys()
290 print db.keys()
291 print db.keys('paths/nest/ok/k*')
291 print db.keys('paths/nest/ok/k*')
292 print dict(db) # snapsot of whole db
292 print dict(db) # snapsot of whole db
293 db.uncache() # frees memory, causes re-reads later
293 db.uncache() # frees memory, causes re-reads later
294
294
295 # shorthand for accessing deeply nested files
295 # shorthand for accessing deeply nested files
296 lnk = db.getlink('myobjects/test')
296 lnk = db.getlink('myobjects/test')
297 lnk.foo = 2
297 lnk.foo = 2
298 lnk.bar = lnk.foo + 5
298 lnk.bar = lnk.foo + 5
299 print lnk.bar # 7
299 print lnk.bar # 7
300
300
301 def stress():
301 def stress():
302 db = PickleShareDB('~/fsdbtest')
302 db = PickleShareDB('~/fsdbtest')
303 import time,sys
303 import time,sys
304 for i in range(1000):
304 for i in range(1000):
305 for j in range(1000):
305 for j in range(1000):
306 if i % 15 == 0 and i < 200:
306 if i % 15 == 0 and i < 200:
307 if str(j) in db:
307 if str(j) in db:
308 del db[str(j)]
308 del db[str(j)]
309 continue
309 continue
310
310
311 if j%33 == 0:
311 if j%33 == 0:
312 time.sleep(0.02)
312 time.sleep(0.02)
313
313
314 db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())]
314 db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())]
315 db.hset('hash',j, db.hget('hash',j,15) + 1 )
315 db.hset('hash',j, db.hget('hash',j,15) + 1 )
316
316
317 print i,
317 print i,
318 sys.stdout.flush()
318 sys.stdout.flush()
319 if i % 10 == 0:
319 if i % 10 == 0:
320 db.uncache()
320 db.uncache()
321
321
322 def main():
322 def main():
323 import textwrap
323 import textwrap
324 usage = textwrap.dedent("""\
324 usage = textwrap.dedent("""\
325 pickleshare - manage PickleShare databases
325 pickleshare - manage PickleShare databases
326
326
327 Usage:
327 Usage:
328
328
329 pickleshare dump /path/to/db > dump.txt
329 pickleshare dump /path/to/db > dump.txt
330 pickleshare load /path/to/db < dump.txt
330 pickleshare load /path/to/db < dump.txt
331 pickleshare test /path/to/db
331 pickleshare test /path/to/db
332 """)
332 """)
333 DB = PickleShareDB
333 DB = PickleShareDB
334 import sys
334 import sys
335 if len(sys.argv) < 2:
335 if len(sys.argv) < 2:
336 print usage
336 print usage
337 return
337 return
338
338
339 cmd = sys.argv[1]
339 cmd = sys.argv[1]
340 args = sys.argv[2:]
340 args = sys.argv[2:]
341 if cmd == 'dump':
341 if cmd == 'dump':
342 if not args: args= ['.']
342 if not args: args= ['.']
343 db = DB(args[0])
343 db = DB(args[0])
344 import pprint
344 import pprint
345 pprint.pprint(db.items())
345 pprint.pprint(db.items())
346 elif cmd == 'load':
346 elif cmd == 'load':
347 cont = sys.stdin.read()
347 cont = sys.stdin.read()
348 db = DB(args[0])
348 db = DB(args[0])
349 data = eval(cont)
349 data = eval(cont)
350 db.clear()
350 db.clear()
351 for k,v in db.items():
351 for k,v in db.items():
352 db[k] = v
352 db[k] = v
353 elif cmd == 'testwait':
353 elif cmd == 'testwait':
354 db = DB(args[0])
354 db = DB(args[0])
355 db.clear()
355 db.clear()
356 print db.waitget('250')
356 print db.waitget('250')
357 elif cmd == 'test':
357 elif cmd == 'test':
358 test()
358 test()
359 stress()
359 stress()
360
360
361 if __name__== "__main__":
361 if __name__== "__main__":
362 main()
362 main()
363
363
364
364
@@ -1,890 +1,892 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Tests for IPython.utils.traitlets.
3 Tests for IPython.utils.traitlets.
4
4
5 Authors:
5 Authors:
6
6
7 * Brian Granger
7 * Brian Granger
8 * Enthought, Inc. Some of the code in this file comes from enthought.traits
8 * Enthought, Inc. Some of the code in this file comes from enthought.traits
9 and is licensed under the BSD license. Also, many of the ideas also come
9 and is licensed under the BSD license. Also, many of the ideas also come
10 from enthought.traits even though our implementation is very different.
10 from enthought.traits even though our implementation is very different.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Imports
21 # Imports
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 import sys
24 import sys
25 from unittest import TestCase
25 from unittest import TestCase
26
26
27 from nose import SkipTest
28
27 from IPython.utils.traitlets import (
29 from IPython.utils.traitlets import (
28 HasTraits, MetaHasTraits, TraitType, Any, CBytes,
30 HasTraits, MetaHasTraits, TraitType, Any, CBytes,
29 Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError,
31 Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError,
30 Undefined, Type, This, Instance, TCPAddress, List, Tuple,
32 Undefined, Type, This, Instance, TCPAddress, List, Tuple,
31 ObjectName, DottedObjectName
33 ObjectName, DottedObjectName
32 )
34 )
33 from IPython.utils import py3compat
35 from IPython.utils import py3compat
34 from IPython.testing.decorators import skipif
36 from IPython.testing.decorators import skipif
35
37
36 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
37 # Helper classes for testing
39 # Helper classes for testing
38 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
39
41
40
42
41 class HasTraitsStub(HasTraits):
43 class HasTraitsStub(HasTraits):
42
44
43 def _notify_trait(self, name, old, new):
45 def _notify_trait(self, name, old, new):
44 self._notify_name = name
46 self._notify_name = name
45 self._notify_old = old
47 self._notify_old = old
46 self._notify_new = new
48 self._notify_new = new
47
49
48
50
49 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
50 # Test classes
52 # Test classes
51 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
52
54
53
55
54 class TestTraitType(TestCase):
56 class TestTraitType(TestCase):
55
57
56 def test_get_undefined(self):
58 def test_get_undefined(self):
57 class A(HasTraits):
59 class A(HasTraits):
58 a = TraitType
60 a = TraitType
59 a = A()
61 a = A()
60 self.assertEquals(a.a, Undefined)
62 self.assertEquals(a.a, Undefined)
61
63
62 def test_set(self):
64 def test_set(self):
63 class A(HasTraitsStub):
65 class A(HasTraitsStub):
64 a = TraitType
66 a = TraitType
65
67
66 a = A()
68 a = A()
67 a.a = 10
69 a.a = 10
68 self.assertEquals(a.a, 10)
70 self.assertEquals(a.a, 10)
69 self.assertEquals(a._notify_name, 'a')
71 self.assertEquals(a._notify_name, 'a')
70 self.assertEquals(a._notify_old, Undefined)
72 self.assertEquals(a._notify_old, Undefined)
71 self.assertEquals(a._notify_new, 10)
73 self.assertEquals(a._notify_new, 10)
72
74
73 def test_validate(self):
75 def test_validate(self):
74 class MyTT(TraitType):
76 class MyTT(TraitType):
75 def validate(self, inst, value):
77 def validate(self, inst, value):
76 return -1
78 return -1
77 class A(HasTraitsStub):
79 class A(HasTraitsStub):
78 tt = MyTT
80 tt = MyTT
79
81
80 a = A()
82 a = A()
81 a.tt = 10
83 a.tt = 10
82 self.assertEquals(a.tt, -1)
84 self.assertEquals(a.tt, -1)
83
85
84 def test_default_validate(self):
86 def test_default_validate(self):
85 class MyIntTT(TraitType):
87 class MyIntTT(TraitType):
86 def validate(self, obj, value):
88 def validate(self, obj, value):
87 if isinstance(value, int):
89 if isinstance(value, int):
88 return value
90 return value
89 self.error(obj, value)
91 self.error(obj, value)
90 class A(HasTraits):
92 class A(HasTraits):
91 tt = MyIntTT(10)
93 tt = MyIntTT(10)
92 a = A()
94 a = A()
93 self.assertEquals(a.tt, 10)
95 self.assertEquals(a.tt, 10)
94
96
95 # Defaults are validated when the HasTraits is instantiated
97 # Defaults are validated when the HasTraits is instantiated
96 class B(HasTraits):
98 class B(HasTraits):
97 tt = MyIntTT('bad default')
99 tt = MyIntTT('bad default')
98 self.assertRaises(TraitError, B)
100 self.assertRaises(TraitError, B)
99
101
100 def test_is_valid_for(self):
102 def test_is_valid_for(self):
101 class MyTT(TraitType):
103 class MyTT(TraitType):
102 def is_valid_for(self, value):
104 def is_valid_for(self, value):
103 return True
105 return True
104 class A(HasTraits):
106 class A(HasTraits):
105 tt = MyTT
107 tt = MyTT
106
108
107 a = A()
109 a = A()
108 a.tt = 10
110 a.tt = 10
109 self.assertEquals(a.tt, 10)
111 self.assertEquals(a.tt, 10)
110
112
111 def test_value_for(self):
113 def test_value_for(self):
112 class MyTT(TraitType):
114 class MyTT(TraitType):
113 def value_for(self, value):
115 def value_for(self, value):
114 return 20
116 return 20
115 class A(HasTraits):
117 class A(HasTraits):
116 tt = MyTT
118 tt = MyTT
117
119
118 a = A()
120 a = A()
119 a.tt = 10
121 a.tt = 10
120 self.assertEquals(a.tt, 20)
122 self.assertEquals(a.tt, 20)
121
123
122 def test_info(self):
124 def test_info(self):
123 class A(HasTraits):
125 class A(HasTraits):
124 tt = TraitType
126 tt = TraitType
125 a = A()
127 a = A()
126 self.assertEquals(A.tt.info(), 'any value')
128 self.assertEquals(A.tt.info(), 'any value')
127
129
128 def test_error(self):
130 def test_error(self):
129 class A(HasTraits):
131 class A(HasTraits):
130 tt = TraitType
132 tt = TraitType
131 a = A()
133 a = A()
132 self.assertRaises(TraitError, A.tt.error, a, 10)
134 self.assertRaises(TraitError, A.tt.error, a, 10)
133
135
134 def test_dynamic_initializer(self):
136 def test_dynamic_initializer(self):
135 class A(HasTraits):
137 class A(HasTraits):
136 x = Int(10)
138 x = Int(10)
137 def _x_default(self):
139 def _x_default(self):
138 return 11
140 return 11
139 class B(A):
141 class B(A):
140 x = Int(20)
142 x = Int(20)
141 class C(A):
143 class C(A):
142 def _x_default(self):
144 def _x_default(self):
143 return 21
145 return 21
144
146
145 a = A()
147 a = A()
146 self.assertEquals(a._trait_values, {})
148 self.assertEquals(a._trait_values, {})
147 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
149 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
148 self.assertEquals(a.x, 11)
150 self.assertEquals(a.x, 11)
149 self.assertEquals(a._trait_values, {'x': 11})
151 self.assertEquals(a._trait_values, {'x': 11})
150 b = B()
152 b = B()
151 self.assertEquals(b._trait_values, {'x': 20})
153 self.assertEquals(b._trait_values, {'x': 20})
152 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
154 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
153 self.assertEquals(b.x, 20)
155 self.assertEquals(b.x, 20)
154 c = C()
156 c = C()
155 self.assertEquals(c._trait_values, {})
157 self.assertEquals(c._trait_values, {})
156 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
158 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
157 self.assertEquals(c.x, 21)
159 self.assertEquals(c.x, 21)
158 self.assertEquals(c._trait_values, {'x': 21})
160 self.assertEquals(c._trait_values, {'x': 21})
159 # Ensure that the base class remains unmolested when the _default
161 # Ensure that the base class remains unmolested when the _default
160 # initializer gets overridden in a subclass.
162 # initializer gets overridden in a subclass.
161 a = A()
163 a = A()
162 c = C()
164 c = C()
163 self.assertEquals(a._trait_values, {})
165 self.assertEquals(a._trait_values, {})
164 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
166 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
165 self.assertEquals(a.x, 11)
167 self.assertEquals(a.x, 11)
166 self.assertEquals(a._trait_values, {'x': 11})
168 self.assertEquals(a._trait_values, {'x': 11})
167
169
168
170
169
171
170 class TestHasTraitsMeta(TestCase):
172 class TestHasTraitsMeta(TestCase):
171
173
172 def test_metaclass(self):
174 def test_metaclass(self):
173 self.assertEquals(type(HasTraits), MetaHasTraits)
175 self.assertEquals(type(HasTraits), MetaHasTraits)
174
176
175 class A(HasTraits):
177 class A(HasTraits):
176 a = Int
178 a = Int
177
179
178 a = A()
180 a = A()
179 self.assertEquals(type(a.__class__), MetaHasTraits)
181 self.assertEquals(type(a.__class__), MetaHasTraits)
180 self.assertEquals(a.a,0)
182 self.assertEquals(a.a,0)
181 a.a = 10
183 a.a = 10
182 self.assertEquals(a.a,10)
184 self.assertEquals(a.a,10)
183
185
184 class B(HasTraits):
186 class B(HasTraits):
185 b = Int()
187 b = Int()
186
188
187 b = B()
189 b = B()
188 self.assertEquals(b.b,0)
190 self.assertEquals(b.b,0)
189 b.b = 10
191 b.b = 10
190 self.assertEquals(b.b,10)
192 self.assertEquals(b.b,10)
191
193
192 class C(HasTraits):
194 class C(HasTraits):
193 c = Int(30)
195 c = Int(30)
194
196
195 c = C()
197 c = C()
196 self.assertEquals(c.c,30)
198 self.assertEquals(c.c,30)
197 c.c = 10
199 c.c = 10
198 self.assertEquals(c.c,10)
200 self.assertEquals(c.c,10)
199
201
200 def test_this_class(self):
202 def test_this_class(self):
201 class A(HasTraits):
203 class A(HasTraits):
202 t = This()
204 t = This()
203 tt = This()
205 tt = This()
204 class B(A):
206 class B(A):
205 tt = This()
207 tt = This()
206 ttt = This()
208 ttt = This()
207 self.assertEquals(A.t.this_class, A)
209 self.assertEquals(A.t.this_class, A)
208 self.assertEquals(B.t.this_class, A)
210 self.assertEquals(B.t.this_class, A)
209 self.assertEquals(B.tt.this_class, B)
211 self.assertEquals(B.tt.this_class, B)
210 self.assertEquals(B.ttt.this_class, B)
212 self.assertEquals(B.ttt.this_class, B)
211
213
212 class TestHasTraitsNotify(TestCase):
214 class TestHasTraitsNotify(TestCase):
213
215
214 def setUp(self):
216 def setUp(self):
215 self._notify1 = []
217 self._notify1 = []
216 self._notify2 = []
218 self._notify2 = []
217
219
218 def notify1(self, name, old, new):
220 def notify1(self, name, old, new):
219 self._notify1.append((name, old, new))
221 self._notify1.append((name, old, new))
220
222
221 def notify2(self, name, old, new):
223 def notify2(self, name, old, new):
222 self._notify2.append((name, old, new))
224 self._notify2.append((name, old, new))
223
225
224 def test_notify_all(self):
226 def test_notify_all(self):
225
227
226 class A(HasTraits):
228 class A(HasTraits):
227 a = Int
229 a = Int
228 b = Float
230 b = Float
229
231
230 a = A()
232 a = A()
231 a.on_trait_change(self.notify1)
233 a.on_trait_change(self.notify1)
232 a.a = 0
234 a.a = 0
233 self.assertEquals(len(self._notify1),0)
235 self.assertEquals(len(self._notify1),0)
234 a.b = 0.0
236 a.b = 0.0
235 self.assertEquals(len(self._notify1),0)
237 self.assertEquals(len(self._notify1),0)
236 a.a = 10
238 a.a = 10
237 self.assert_(('a',0,10) in self._notify1)
239 self.assert_(('a',0,10) in self._notify1)
238 a.b = 10.0
240 a.b = 10.0
239 self.assert_(('b',0.0,10.0) in self._notify1)
241 self.assert_(('b',0.0,10.0) in self._notify1)
240 self.assertRaises(TraitError,setattr,a,'a','bad string')
242 self.assertRaises(TraitError,setattr,a,'a','bad string')
241 self.assertRaises(TraitError,setattr,a,'b','bad string')
243 self.assertRaises(TraitError,setattr,a,'b','bad string')
242 self._notify1 = []
244 self._notify1 = []
243 a.on_trait_change(self.notify1,remove=True)
245 a.on_trait_change(self.notify1,remove=True)
244 a.a = 20
246 a.a = 20
245 a.b = 20.0
247 a.b = 20.0
246 self.assertEquals(len(self._notify1),0)
248 self.assertEquals(len(self._notify1),0)
247
249
248 def test_notify_one(self):
250 def test_notify_one(self):
249
251
250 class A(HasTraits):
252 class A(HasTraits):
251 a = Int
253 a = Int
252 b = Float
254 b = Float
253
255
254 a = A()
256 a = A()
255 a.on_trait_change(self.notify1, 'a')
257 a.on_trait_change(self.notify1, 'a')
256 a.a = 0
258 a.a = 0
257 self.assertEquals(len(self._notify1),0)
259 self.assertEquals(len(self._notify1),0)
258 a.a = 10
260 a.a = 10
259 self.assert_(('a',0,10) in self._notify1)
261 self.assert_(('a',0,10) in self._notify1)
260 self.assertRaises(TraitError,setattr,a,'a','bad string')
262 self.assertRaises(TraitError,setattr,a,'a','bad string')
261
263
262 def test_subclass(self):
264 def test_subclass(self):
263
265
264 class A(HasTraits):
266 class A(HasTraits):
265 a = Int
267 a = Int
266
268
267 class B(A):
269 class B(A):
268 b = Float
270 b = Float
269
271
270 b = B()
272 b = B()
271 self.assertEquals(b.a,0)
273 self.assertEquals(b.a,0)
272 self.assertEquals(b.b,0.0)
274 self.assertEquals(b.b,0.0)
273 b.a = 100
275 b.a = 100
274 b.b = 100.0
276 b.b = 100.0
275 self.assertEquals(b.a,100)
277 self.assertEquals(b.a,100)
276 self.assertEquals(b.b,100.0)
278 self.assertEquals(b.b,100.0)
277
279
278 def test_notify_subclass(self):
280 def test_notify_subclass(self):
279
281
280 class A(HasTraits):
282 class A(HasTraits):
281 a = Int
283 a = Int
282
284
283 class B(A):
285 class B(A):
284 b = Float
286 b = Float
285
287
286 b = B()
288 b = B()
287 b.on_trait_change(self.notify1, 'a')
289 b.on_trait_change(self.notify1, 'a')
288 b.on_trait_change(self.notify2, 'b')
290 b.on_trait_change(self.notify2, 'b')
289 b.a = 0
291 b.a = 0
290 b.b = 0.0
292 b.b = 0.0
291 self.assertEquals(len(self._notify1),0)
293 self.assertEquals(len(self._notify1),0)
292 self.assertEquals(len(self._notify2),0)
294 self.assertEquals(len(self._notify2),0)
293 b.a = 10
295 b.a = 10
294 b.b = 10.0
296 b.b = 10.0
295 self.assert_(('a',0,10) in self._notify1)
297 self.assert_(('a',0,10) in self._notify1)
296 self.assert_(('b',0.0,10.0) in self._notify2)
298 self.assert_(('b',0.0,10.0) in self._notify2)
297
299
298 def test_static_notify(self):
300 def test_static_notify(self):
299
301
300 class A(HasTraits):
302 class A(HasTraits):
301 a = Int
303 a = Int
302 _notify1 = []
304 _notify1 = []
303 def _a_changed(self, name, old, new):
305 def _a_changed(self, name, old, new):
304 self._notify1.append((name, old, new))
306 self._notify1.append((name, old, new))
305
307
306 a = A()
308 a = A()
307 a.a = 0
309 a.a = 0
308 # This is broken!!!
310 # This is broken!!!
309 self.assertEquals(len(a._notify1),0)
311 self.assertEquals(len(a._notify1),0)
310 a.a = 10
312 a.a = 10
311 self.assert_(('a',0,10) in a._notify1)
313 self.assert_(('a',0,10) in a._notify1)
312
314
313 class B(A):
315 class B(A):
314 b = Float
316 b = Float
315 _notify2 = []
317 _notify2 = []
316 def _b_changed(self, name, old, new):
318 def _b_changed(self, name, old, new):
317 self._notify2.append((name, old, new))
319 self._notify2.append((name, old, new))
318
320
319 b = B()
321 b = B()
320 b.a = 10
322 b.a = 10
321 b.b = 10.0
323 b.b = 10.0
322 self.assert_(('a',0,10) in b._notify1)
324 self.assert_(('a',0,10) in b._notify1)
323 self.assert_(('b',0.0,10.0) in b._notify2)
325 self.assert_(('b',0.0,10.0) in b._notify2)
324
326
325 def test_notify_args(self):
327 def test_notify_args(self):
326
328
327 def callback0():
329 def callback0():
328 self.cb = ()
330 self.cb = ()
329 def callback1(name):
331 def callback1(name):
330 self.cb = (name,)
332 self.cb = (name,)
331 def callback2(name, new):
333 def callback2(name, new):
332 self.cb = (name, new)
334 self.cb = (name, new)
333 def callback3(name, old, new):
335 def callback3(name, old, new):
334 self.cb = (name, old, new)
336 self.cb = (name, old, new)
335
337
336 class A(HasTraits):
338 class A(HasTraits):
337 a = Int
339 a = Int
338
340
339 a = A()
341 a = A()
340 a.on_trait_change(callback0, 'a')
342 a.on_trait_change(callback0, 'a')
341 a.a = 10
343 a.a = 10
342 self.assertEquals(self.cb,())
344 self.assertEquals(self.cb,())
343 a.on_trait_change(callback0, 'a', remove=True)
345 a.on_trait_change(callback0, 'a', remove=True)
344
346
345 a.on_trait_change(callback1, 'a')
347 a.on_trait_change(callback1, 'a')
346 a.a = 100
348 a.a = 100
347 self.assertEquals(self.cb,('a',))
349 self.assertEquals(self.cb,('a',))
348 a.on_trait_change(callback1, 'a', remove=True)
350 a.on_trait_change(callback1, 'a', remove=True)
349
351
350 a.on_trait_change(callback2, 'a')
352 a.on_trait_change(callback2, 'a')
351 a.a = 1000
353 a.a = 1000
352 self.assertEquals(self.cb,('a',1000))
354 self.assertEquals(self.cb,('a',1000))
353 a.on_trait_change(callback2, 'a', remove=True)
355 a.on_trait_change(callback2, 'a', remove=True)
354
356
355 a.on_trait_change(callback3, 'a')
357 a.on_trait_change(callback3, 'a')
356 a.a = 10000
358 a.a = 10000
357 self.assertEquals(self.cb,('a',1000,10000))
359 self.assertEquals(self.cb,('a',1000,10000))
358 a.on_trait_change(callback3, 'a', remove=True)
360 a.on_trait_change(callback3, 'a', remove=True)
359
361
360 self.assertEquals(len(a._trait_notifiers['a']),0)
362 self.assertEquals(len(a._trait_notifiers['a']),0)
361
363
362
364
363 class TestHasTraits(TestCase):
365 class TestHasTraits(TestCase):
364
366
365 def test_trait_names(self):
367 def test_trait_names(self):
366 class A(HasTraits):
368 class A(HasTraits):
367 i = Int
369 i = Int
368 f = Float
370 f = Float
369 a = A()
371 a = A()
370 self.assertEquals(a.trait_names(),['i','f'])
372 self.assertEquals(a.trait_names(),['i','f'])
371 self.assertEquals(A.class_trait_names(),['i','f'])
373 self.assertEquals(A.class_trait_names(),['i','f'])
372
374
373 def test_trait_metadata(self):
375 def test_trait_metadata(self):
374 class A(HasTraits):
376 class A(HasTraits):
375 i = Int(config_key='MY_VALUE')
377 i = Int(config_key='MY_VALUE')
376 a = A()
378 a = A()
377 self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE')
379 self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE')
378
380
379 def test_traits(self):
381 def test_traits(self):
380 class A(HasTraits):
382 class A(HasTraits):
381 i = Int
383 i = Int
382 f = Float
384 f = Float
383 a = A()
385 a = A()
384 self.assertEquals(a.traits(), dict(i=A.i, f=A.f))
386 self.assertEquals(a.traits(), dict(i=A.i, f=A.f))
385 self.assertEquals(A.class_traits(), dict(i=A.i, f=A.f))
387 self.assertEquals(A.class_traits(), dict(i=A.i, f=A.f))
386
388
387 def test_traits_metadata(self):
389 def test_traits_metadata(self):
388 class A(HasTraits):
390 class A(HasTraits):
389 i = Int(config_key='VALUE1', other_thing='VALUE2')
391 i = Int(config_key='VALUE1', other_thing='VALUE2')
390 f = Float(config_key='VALUE3', other_thing='VALUE2')
392 f = Float(config_key='VALUE3', other_thing='VALUE2')
391 j = Int(0)
393 j = Int(0)
392 a = A()
394 a = A()
393 self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j))
395 self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j))
394 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
396 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
395 self.assertEquals(traits, dict(i=A.i))
397 self.assertEquals(traits, dict(i=A.i))
396
398
397 # This passes, but it shouldn't because I am replicating a bug in
399 # This passes, but it shouldn't because I am replicating a bug in
398 # traits.
400 # traits.
399 traits = a.traits(config_key=lambda v: True)
401 traits = a.traits(config_key=lambda v: True)
400 self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j))
402 self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j))
401
403
402 def test_init(self):
404 def test_init(self):
403 class A(HasTraits):
405 class A(HasTraits):
404 i = Int()
406 i = Int()
405 x = Float()
407 x = Float()
406 a = A(i=1, x=10.0)
408 a = A(i=1, x=10.0)
407 self.assertEquals(a.i, 1)
409 self.assertEquals(a.i, 1)
408 self.assertEquals(a.x, 10.0)
410 self.assertEquals(a.x, 10.0)
409
411
410 #-----------------------------------------------------------------------------
412 #-----------------------------------------------------------------------------
411 # Tests for specific trait types
413 # Tests for specific trait types
412 #-----------------------------------------------------------------------------
414 #-----------------------------------------------------------------------------
413
415
414
416
415 class TestType(TestCase):
417 class TestType(TestCase):
416
418
417 def test_default(self):
419 def test_default(self):
418
420
419 class B(object): pass
421 class B(object): pass
420 class A(HasTraits):
422 class A(HasTraits):
421 klass = Type
423 klass = Type
422
424
423 a = A()
425 a = A()
424 self.assertEquals(a.klass, None)
426 self.assertEquals(a.klass, None)
425
427
426 a.klass = B
428 a.klass = B
427 self.assertEquals(a.klass, B)
429 self.assertEquals(a.klass, B)
428 self.assertRaises(TraitError, setattr, a, 'klass', 10)
430 self.assertRaises(TraitError, setattr, a, 'klass', 10)
429
431
430 def test_value(self):
432 def test_value(self):
431
433
432 class B(object): pass
434 class B(object): pass
433 class C(object): pass
435 class C(object): pass
434 class A(HasTraits):
436 class A(HasTraits):
435 klass = Type(B)
437 klass = Type(B)
436
438
437 a = A()
439 a = A()
438 self.assertEquals(a.klass, B)
440 self.assertEquals(a.klass, B)
439 self.assertRaises(TraitError, setattr, a, 'klass', C)
441 self.assertRaises(TraitError, setattr, a, 'klass', C)
440 self.assertRaises(TraitError, setattr, a, 'klass', object)
442 self.assertRaises(TraitError, setattr, a, 'klass', object)
441 a.klass = B
443 a.klass = B
442
444
443 def test_allow_none(self):
445 def test_allow_none(self):
444
446
445 class B(object): pass
447 class B(object): pass
446 class C(B): pass
448 class C(B): pass
447 class A(HasTraits):
449 class A(HasTraits):
448 klass = Type(B, allow_none=False)
450 klass = Type(B, allow_none=False)
449
451
450 a = A()
452 a = A()
451 self.assertEquals(a.klass, B)
453 self.assertEquals(a.klass, B)
452 self.assertRaises(TraitError, setattr, a, 'klass', None)
454 self.assertRaises(TraitError, setattr, a, 'klass', None)
453 a.klass = C
455 a.klass = C
454 self.assertEquals(a.klass, C)
456 self.assertEquals(a.klass, C)
455
457
456 def test_validate_klass(self):
458 def test_validate_klass(self):
457
459
458 class A(HasTraits):
460 class A(HasTraits):
459 klass = Type('no strings allowed')
461 klass = Type('no strings allowed')
460
462
461 self.assertRaises(ImportError, A)
463 self.assertRaises(ImportError, A)
462
464
463 class A(HasTraits):
465 class A(HasTraits):
464 klass = Type('rub.adub.Duck')
466 klass = Type('rub.adub.Duck')
465
467
466 self.assertRaises(ImportError, A)
468 self.assertRaises(ImportError, A)
467
469
468 def test_validate_default(self):
470 def test_validate_default(self):
469
471
470 class B(object): pass
472 class B(object): pass
471 class A(HasTraits):
473 class A(HasTraits):
472 klass = Type('bad default', B)
474 klass = Type('bad default', B)
473
475
474 self.assertRaises(ImportError, A)
476 self.assertRaises(ImportError, A)
475
477
476 class C(HasTraits):
478 class C(HasTraits):
477 klass = Type(None, B, allow_none=False)
479 klass = Type(None, B, allow_none=False)
478
480
479 self.assertRaises(TraitError, C)
481 self.assertRaises(TraitError, C)
480
482
481 def test_str_klass(self):
483 def test_str_klass(self):
482
484
483 class A(HasTraits):
485 class A(HasTraits):
484 klass = Type('IPython.utils.ipstruct.Struct')
486 klass = Type('IPython.utils.ipstruct.Struct')
485
487
486 from IPython.utils.ipstruct import Struct
488 from IPython.utils.ipstruct import Struct
487 a = A()
489 a = A()
488 a.klass = Struct
490 a.klass = Struct
489 self.assertEquals(a.klass, Struct)
491 self.assertEquals(a.klass, Struct)
490
492
491 self.assertRaises(TraitError, setattr, a, 'klass', 10)
493 self.assertRaises(TraitError, setattr, a, 'klass', 10)
492
494
493 class TestInstance(TestCase):
495 class TestInstance(TestCase):
494
496
495 def test_basic(self):
497 def test_basic(self):
496 class Foo(object): pass
498 class Foo(object): pass
497 class Bar(Foo): pass
499 class Bar(Foo): pass
498 class Bah(object): pass
500 class Bah(object): pass
499
501
500 class A(HasTraits):
502 class A(HasTraits):
501 inst = Instance(Foo)
503 inst = Instance(Foo)
502
504
503 a = A()
505 a = A()
504 self.assert_(a.inst is None)
506 self.assert_(a.inst is None)
505 a.inst = Foo()
507 a.inst = Foo()
506 self.assert_(isinstance(a.inst, Foo))
508 self.assert_(isinstance(a.inst, Foo))
507 a.inst = Bar()
509 a.inst = Bar()
508 self.assert_(isinstance(a.inst, Foo))
510 self.assert_(isinstance(a.inst, Foo))
509 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
511 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
510 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
512 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
511 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
513 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
512
514
513 def test_unique_default_value(self):
515 def test_unique_default_value(self):
514 class Foo(object): pass
516 class Foo(object): pass
515 class A(HasTraits):
517 class A(HasTraits):
516 inst = Instance(Foo,(),{})
518 inst = Instance(Foo,(),{})
517
519
518 a = A()
520 a = A()
519 b = A()
521 b = A()
520 self.assert_(a.inst is not b.inst)
522 self.assert_(a.inst is not b.inst)
521
523
522 def test_args_kw(self):
524 def test_args_kw(self):
523 class Foo(object):
525 class Foo(object):
524 def __init__(self, c): self.c = c
526 def __init__(self, c): self.c = c
525 class Bar(object): pass
527 class Bar(object): pass
526 class Bah(object):
528 class Bah(object):
527 def __init__(self, c, d):
529 def __init__(self, c, d):
528 self.c = c; self.d = d
530 self.c = c; self.d = d
529
531
530 class A(HasTraits):
532 class A(HasTraits):
531 inst = Instance(Foo, (10,))
533 inst = Instance(Foo, (10,))
532 a = A()
534 a = A()
533 self.assertEquals(a.inst.c, 10)
535 self.assertEquals(a.inst.c, 10)
534
536
535 class B(HasTraits):
537 class B(HasTraits):
536 inst = Instance(Bah, args=(10,), kw=dict(d=20))
538 inst = Instance(Bah, args=(10,), kw=dict(d=20))
537 b = B()
539 b = B()
538 self.assertEquals(b.inst.c, 10)
540 self.assertEquals(b.inst.c, 10)
539 self.assertEquals(b.inst.d, 20)
541 self.assertEquals(b.inst.d, 20)
540
542
541 class C(HasTraits):
543 class C(HasTraits):
542 inst = Instance(Foo)
544 inst = Instance(Foo)
543 c = C()
545 c = C()
544 self.assert_(c.inst is None)
546 self.assert_(c.inst is None)
545
547
546 def test_bad_default(self):
548 def test_bad_default(self):
547 class Foo(object): pass
549 class Foo(object): pass
548
550
549 class A(HasTraits):
551 class A(HasTraits):
550 inst = Instance(Foo, allow_none=False)
552 inst = Instance(Foo, allow_none=False)
551
553
552 self.assertRaises(TraitError, A)
554 self.assertRaises(TraitError, A)
553
555
554 def test_instance(self):
556 def test_instance(self):
555 class Foo(object): pass
557 class Foo(object): pass
556
558
557 def inner():
559 def inner():
558 class A(HasTraits):
560 class A(HasTraits):
559 inst = Instance(Foo())
561 inst = Instance(Foo())
560
562
561 self.assertRaises(TraitError, inner)
563 self.assertRaises(TraitError, inner)
562
564
563
565
564 class TestThis(TestCase):
566 class TestThis(TestCase):
565
567
566 def test_this_class(self):
568 def test_this_class(self):
567 class Foo(HasTraits):
569 class Foo(HasTraits):
568 this = This
570 this = This
569
571
570 f = Foo()
572 f = Foo()
571 self.assertEquals(f.this, None)
573 self.assertEquals(f.this, None)
572 g = Foo()
574 g = Foo()
573 f.this = g
575 f.this = g
574 self.assertEquals(f.this, g)
576 self.assertEquals(f.this, g)
575 self.assertRaises(TraitError, setattr, f, 'this', 10)
577 self.assertRaises(TraitError, setattr, f, 'this', 10)
576
578
577 def test_this_inst(self):
579 def test_this_inst(self):
578 class Foo(HasTraits):
580 class Foo(HasTraits):
579 this = This()
581 this = This()
580
582
581 f = Foo()
583 f = Foo()
582 f.this = Foo()
584 f.this = Foo()
583 self.assert_(isinstance(f.this, Foo))
585 self.assert_(isinstance(f.this, Foo))
584
586
585 def test_subclass(self):
587 def test_subclass(self):
586 class Foo(HasTraits):
588 class Foo(HasTraits):
587 t = This()
589 t = This()
588 class Bar(Foo):
590 class Bar(Foo):
589 pass
591 pass
590 f = Foo()
592 f = Foo()
591 b = Bar()
593 b = Bar()
592 f.t = b
594 f.t = b
593 b.t = f
595 b.t = f
594 self.assertEquals(f.t, b)
596 self.assertEquals(f.t, b)
595 self.assertEquals(b.t, f)
597 self.assertEquals(b.t, f)
596
598
597 def test_subclass_override(self):
599 def test_subclass_override(self):
598 class Foo(HasTraits):
600 class Foo(HasTraits):
599 t = This()
601 t = This()
600 class Bar(Foo):
602 class Bar(Foo):
601 t = This()
603 t = This()
602 f = Foo()
604 f = Foo()
603 b = Bar()
605 b = Bar()
604 f.t = b
606 f.t = b
605 self.assertEquals(f.t, b)
607 self.assertEquals(f.t, b)
606 self.assertRaises(TraitError, setattr, b, 't', f)
608 self.assertRaises(TraitError, setattr, b, 't', f)
607
609
608 class TraitTestBase(TestCase):
610 class TraitTestBase(TestCase):
609 """A best testing class for basic trait types."""
611 """A best testing class for basic trait types."""
610
612
611 def assign(self, value):
613 def assign(self, value):
612 self.obj.value = value
614 self.obj.value = value
613
615
614 def coerce(self, value):
616 def coerce(self, value):
615 return value
617 return value
616
618
617 def test_good_values(self):
619 def test_good_values(self):
618 if hasattr(self, '_good_values'):
620 if hasattr(self, '_good_values'):
619 for value in self._good_values:
621 for value in self._good_values:
620 self.assign(value)
622 self.assign(value)
621 self.assertEquals(self.obj.value, self.coerce(value))
623 self.assertEquals(self.obj.value, self.coerce(value))
622
624
623 def test_bad_values(self):
625 def test_bad_values(self):
624 if hasattr(self, '_bad_values'):
626 if hasattr(self, '_bad_values'):
625 for value in self._bad_values:
627 for value in self._bad_values:
626 try:
628 try:
627 self.assertRaises(TraitError, self.assign, value)
629 self.assertRaises(TraitError, self.assign, value)
628 except AssertionError:
630 except AssertionError:
629 assert False, value
631 assert False, value
630
632
631 def test_default_value(self):
633 def test_default_value(self):
632 if hasattr(self, '_default_value'):
634 if hasattr(self, '_default_value'):
633 self.assertEquals(self._default_value, self.obj.value)
635 self.assertEquals(self._default_value, self.obj.value)
634
636
635 def tearDown(self):
637 def tearDown(self):
636 # restore default value after tests, if set
638 # restore default value after tests, if set
637 if hasattr(self, '_default_value'):
639 if hasattr(self, '_default_value'):
638 self.obj.value = self._default_value
640 self.obj.value = self._default_value
639
641
640
642
641 class AnyTrait(HasTraits):
643 class AnyTrait(HasTraits):
642
644
643 value = Any
645 value = Any
644
646
645 class AnyTraitTest(TraitTestBase):
647 class AnyTraitTest(TraitTestBase):
646
648
647 obj = AnyTrait()
649 obj = AnyTrait()
648
650
649 _default_value = None
651 _default_value = None
650 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
652 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
651 _bad_values = []
653 _bad_values = []
652
654
653
655
654 class IntTrait(HasTraits):
656 class IntTrait(HasTraits):
655
657
656 value = Int(99)
658 value = Int(99)
657
659
658 class TestInt(TraitTestBase):
660 class TestInt(TraitTestBase):
659
661
660 obj = IntTrait()
662 obj = IntTrait()
661 _default_value = 99
663 _default_value = 99
662 _good_values = [10, -10]
664 _good_values = [10, -10]
663 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j,
665 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j,
664 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
666 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
665 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
667 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
666 if not py3compat.PY3:
668 if not py3compat.PY3:
667 _bad_values.extend([10L, -10L, 10*sys.maxint, -10*sys.maxint])
669 _bad_values.extend([10L, -10L, 10*sys.maxint, -10*sys.maxint])
668
670
669
671
670 class LongTrait(HasTraits):
672 class LongTrait(HasTraits):
671
673
672 value = Long(99L)
674 value = Long(99L)
673
675
674 class TestLong(TraitTestBase):
676 class TestLong(TraitTestBase):
675
677
676 obj = LongTrait()
678 obj = LongTrait()
677
679
678 _default_value = 99L
680 _default_value = 99L
679 _good_values = [10, -10, 10L, -10L]
681 _good_values = [10, -10, 10L, -10L]
680 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
682 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
681 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
683 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
682 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
684 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
683 u'-10.1']
685 u'-10.1']
684 if not py3compat.PY3:
686 if not py3compat.PY3:
685 # maxint undefined on py3, because int == long
687 # maxint undefined on py3, because int == long
686 _good_values.extend([10*sys.maxint, -10*sys.maxint])
688 _good_values.extend([10*sys.maxint, -10*sys.maxint])
687
689
688 @skipif(py3compat.PY3, "not relevant on py3")
690 @skipif(py3compat.PY3, "not relevant on py3")
689 def test_cast_small(self):
691 def test_cast_small(self):
690 """Long casts ints to long"""
692 """Long casts ints to long"""
691 self.obj.value = 10
693 self.obj.value = 10
692 self.assertEquals(type(self.obj.value), long)
694 self.assertEquals(type(self.obj.value), long)
693
695
694
696
695 class IntegerTrait(HasTraits):
697 class IntegerTrait(HasTraits):
696 value = Integer(1)
698 value = Integer(1)
697
699
698 class TestInteger(TestLong):
700 class TestInteger(TestLong):
699 obj = IntegerTrait()
701 obj = IntegerTrait()
700 _default_value = 1
702 _default_value = 1
701
703
702 def coerce(self, n):
704 def coerce(self, n):
703 return int(n)
705 return int(n)
704
706
705 @skipif(py3compat.PY3, "not relevant on py3")
707 @skipif(py3compat.PY3, "not relevant on py3")
706 def test_cast_small(self):
708 def test_cast_small(self):
707 """Integer casts small longs to int"""
709 """Integer casts small longs to int"""
708 if py3compat.PY3:
710 if py3compat.PY3:
709 raise SkipTest("not relevant on py3")
711 raise SkipTest("not relevant on py3")
710
712
711 self.obj.value = 100L
713 self.obj.value = 100L
712 self.assertEquals(type(self.obj.value), int)
714 self.assertEquals(type(self.obj.value), int)
713
715
714
716
715 class FloatTrait(HasTraits):
717 class FloatTrait(HasTraits):
716
718
717 value = Float(99.0)
719 value = Float(99.0)
718
720
719 class TestFloat(TraitTestBase):
721 class TestFloat(TraitTestBase):
720
722
721 obj = FloatTrait()
723 obj = FloatTrait()
722
724
723 _default_value = 99.0
725 _default_value = 99.0
724 _good_values = [10, -10, 10.1, -10.1]
726 _good_values = [10, -10, 10.1, -10.1]
725 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None,
727 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None,
726 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
728 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
727 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
729 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
728 if not py3compat.PY3:
730 if not py3compat.PY3:
729 _bad_values.extend([10L, -10L])
731 _bad_values.extend([10L, -10L])
730
732
731
733
732 class ComplexTrait(HasTraits):
734 class ComplexTrait(HasTraits):
733
735
734 value = Complex(99.0-99.0j)
736 value = Complex(99.0-99.0j)
735
737
736 class TestComplex(TraitTestBase):
738 class TestComplex(TraitTestBase):
737
739
738 obj = ComplexTrait()
740 obj = ComplexTrait()
739
741
740 _default_value = 99.0-99.0j
742 _default_value = 99.0-99.0j
741 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
743 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
742 10.1j, 10.1+10.1j, 10.1-10.1j]
744 10.1j, 10.1+10.1j, 10.1-10.1j]
743 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
745 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
744 if not py3compat.PY3:
746 if not py3compat.PY3:
745 _bad_values.extend([10L, -10L])
747 _bad_values.extend([10L, -10L])
746
748
747
749
748 class BytesTrait(HasTraits):
750 class BytesTrait(HasTraits):
749
751
750 value = Bytes(b'string')
752 value = Bytes(b'string')
751
753
752 class TestBytes(TraitTestBase):
754 class TestBytes(TraitTestBase):
753
755
754 obj = BytesTrait()
756 obj = BytesTrait()
755
757
756 _default_value = b'string'
758 _default_value = b'string'
757 _good_values = [b'10', b'-10', b'10L',
759 _good_values = [b'10', b'-10', b'10L',
758 b'-10L', b'10.1', b'-10.1', b'string']
760 b'-10L', b'10.1', b'-10.1', b'string']
759 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
761 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
760 ['ten'],{'ten': 10},(10,), None, u'string']
762 ['ten'],{'ten': 10},(10,), None, u'string']
761
763
762
764
763 class UnicodeTrait(HasTraits):
765 class UnicodeTrait(HasTraits):
764
766
765 value = Unicode(u'unicode')
767 value = Unicode(u'unicode')
766
768
767 class TestUnicode(TraitTestBase):
769 class TestUnicode(TraitTestBase):
768
770
769 obj = UnicodeTrait()
771 obj = UnicodeTrait()
770
772
771 _default_value = u'unicode'
773 _default_value = u'unicode'
772 _good_values = ['10', '-10', '10L', '-10L', '10.1',
774 _good_values = ['10', '-10', '10L', '-10L', '10.1',
773 '-10.1', '', u'', 'string', u'string', u"€"]
775 '-10.1', '', u'', 'string', u'string', u"€"]
774 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
776 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
775 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
777 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
776
778
777
779
778 class ObjectNameTrait(HasTraits):
780 class ObjectNameTrait(HasTraits):
779 value = ObjectName("abc")
781 value = ObjectName("abc")
780
782
781 class TestObjectName(TraitTestBase):
783 class TestObjectName(TraitTestBase):
782 obj = ObjectNameTrait()
784 obj = ObjectNameTrait()
783
785
784 _default_value = "abc"
786 _default_value = "abc"
785 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
787 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
786 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
788 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
787 object(), object]
789 object(), object]
788 if sys.version_info[0] < 3:
790 if sys.version_info[0] < 3:
789 _bad_values.append(u"þ")
791 _bad_values.append(u"þ")
790 else:
792 else:
791 _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131).
793 _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131).
792
794
793
795
794 class DottedObjectNameTrait(HasTraits):
796 class DottedObjectNameTrait(HasTraits):
795 value = DottedObjectName("a.b")
797 value = DottedObjectName("a.b")
796
798
797 class TestDottedObjectName(TraitTestBase):
799 class TestDottedObjectName(TraitTestBase):
798 obj = DottedObjectNameTrait()
800 obj = DottedObjectNameTrait()
799
801
800 _default_value = "a.b"
802 _default_value = "a.b"
801 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
803 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
802 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc."]
804 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc."]
803 if sys.version_info[0] < 3:
805 if sys.version_info[0] < 3:
804 _bad_values.append(u"t.þ")
806 _bad_values.append(u"t.þ")
805 else:
807 else:
806 _good_values.append(u"t.þ")
808 _good_values.append(u"t.þ")
807
809
808
810
809 class TCPAddressTrait(HasTraits):
811 class TCPAddressTrait(HasTraits):
810
812
811 value = TCPAddress()
813 value = TCPAddress()
812
814
813 class TestTCPAddress(TraitTestBase):
815 class TestTCPAddress(TraitTestBase):
814
816
815 obj = TCPAddressTrait()
817 obj = TCPAddressTrait()
816
818
817 _default_value = ('127.0.0.1',0)
819 _default_value = ('127.0.0.1',0)
818 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
820 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
819 _bad_values = [(0,0),('localhost',10.0),('localhost',-1)]
821 _bad_values = [(0,0),('localhost',10.0),('localhost',-1)]
820
822
821 class ListTrait(HasTraits):
823 class ListTrait(HasTraits):
822
824
823 value = List(Int)
825 value = List(Int)
824
826
825 class TestList(TraitTestBase):
827 class TestList(TraitTestBase):
826
828
827 obj = ListTrait()
829 obj = ListTrait()
828
830
829 _default_value = []
831 _default_value = []
830 _good_values = [[], [1], range(10)]
832 _good_values = [[], [1], range(10)]
831 _bad_values = [10, [1,'a'], 'a', (1,2)]
833 _bad_values = [10, [1,'a'], 'a', (1,2)]
832
834
833 class LenListTrait(HasTraits):
835 class LenListTrait(HasTraits):
834
836
835 value = List(Int, [0], minlen=1, maxlen=2)
837 value = List(Int, [0], minlen=1, maxlen=2)
836
838
837 class TestLenList(TraitTestBase):
839 class TestLenList(TraitTestBase):
838
840
839 obj = LenListTrait()
841 obj = LenListTrait()
840
842
841 _default_value = [0]
843 _default_value = [0]
842 _good_values = [[1], range(2)]
844 _good_values = [[1], range(2)]
843 _bad_values = [10, [1,'a'], 'a', (1,2), [], range(3)]
845 _bad_values = [10, [1,'a'], 'a', (1,2), [], range(3)]
844
846
845 class TupleTrait(HasTraits):
847 class TupleTrait(HasTraits):
846
848
847 value = Tuple(Int)
849 value = Tuple(Int)
848
850
849 class TestTupleTrait(TraitTestBase):
851 class TestTupleTrait(TraitTestBase):
850
852
851 obj = TupleTrait()
853 obj = TupleTrait()
852
854
853 _default_value = None
855 _default_value = None
854 _good_values = [(1,), None,(0,)]
856 _good_values = [(1,), None,(0,)]
855 _bad_values = [10, (1,2), [1],('a'), ()]
857 _bad_values = [10, (1,2), [1],('a'), ()]
856
858
857 def test_invalid_args(self):
859 def test_invalid_args(self):
858 self.assertRaises(TypeError, Tuple, 5)
860 self.assertRaises(TypeError, Tuple, 5)
859 self.assertRaises(TypeError, Tuple, default_value='hello')
861 self.assertRaises(TypeError, Tuple, default_value='hello')
860 t = Tuple(Int, CBytes, default_value=(1,5))
862 t = Tuple(Int, CBytes, default_value=(1,5))
861
863
862 class LooseTupleTrait(HasTraits):
864 class LooseTupleTrait(HasTraits):
863
865
864 value = Tuple((1,2,3))
866 value = Tuple((1,2,3))
865
867
866 class TestLooseTupleTrait(TraitTestBase):
868 class TestLooseTupleTrait(TraitTestBase):
867
869
868 obj = LooseTupleTrait()
870 obj = LooseTupleTrait()
869
871
870 _default_value = (1,2,3)
872 _default_value = (1,2,3)
871 _good_values = [(1,), None, (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
873 _good_values = [(1,), None, (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
872 _bad_values = [10, 'hello', [1], []]
874 _bad_values = [10, 'hello', [1], []]
873
875
874 def test_invalid_args(self):
876 def test_invalid_args(self):
875 self.assertRaises(TypeError, Tuple, 5)
877 self.assertRaises(TypeError, Tuple, 5)
876 self.assertRaises(TypeError, Tuple, default_value='hello')
878 self.assertRaises(TypeError, Tuple, default_value='hello')
877 t = Tuple(Int, CBytes, default_value=(1,5))
879 t = Tuple(Int, CBytes, default_value=(1,5))
878
880
879
881
880 class MultiTupleTrait(HasTraits):
882 class MultiTupleTrait(HasTraits):
881
883
882 value = Tuple(Int, Bytes, default_value=[99,b'bottles'])
884 value = Tuple(Int, Bytes, default_value=[99,b'bottles'])
883
885
884 class TestMultiTuple(TraitTestBase):
886 class TestMultiTuple(TraitTestBase):
885
887
886 obj = MultiTupleTrait()
888 obj = MultiTupleTrait()
887
889
888 _default_value = (99,b'bottles')
890 _default_value = (99,b'bottles')
889 _good_values = [(1,b'a'), (2,b'b')]
891 _good_values = [(1,b'a'), (2,b'b')]
890 _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
892 _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
@@ -1,91 +1,91 b''
1 """Tab-completion over zmq"""
1 """Tab-completion over zmq"""
2
2
3 # Trying to get print statements to work during completion, not very
3 # Trying to get print statements to work during completion, not very
4 # successfully...
4 # successfully...
5 from __future__ import print_function
5 from __future__ import print_function
6
6
7 import itertools
7 import itertools
8 try:
8 try:
9 import readline
9 import readline
10 except ImportError:
10 except ImportError:
11 readline = None
11 readline = None
12 import rlcompleter
12 import rlcompleter
13 import time
13 import time
14
14
15 import session
15 import session
16
16
17 class KernelCompleter(object):
17 class KernelCompleter(object):
18 """Kernel-side completion machinery."""
18 """Kernel-side completion machinery."""
19 def __init__(self, namespace):
19 def __init__(self, namespace):
20 self.namespace = namespace
20 self.namespace = namespace
21 self.completer = rlcompleter.Completer(namespace)
21 self.completer = rlcompleter.Completer(namespace)
22
22
23 def complete(self, line, text):
23 def complete(self, line, text):
24 # We'll likely use linel later even if now it's not used for anything
24 # We'll likely use linel later even if now it's not used for anything
25 matches = []
25 matches = []
26 complete = self.completer.complete
26 complete = self.completer.complete
27 for state in itertools.count():
27 for state in itertools.count():
28 comp = complete(text, state)
28 comp = complete(text, state)
29 if comp is None:
29 if comp is None:
30 break
30 break
31 matches.append(comp)
31 matches.append(comp)
32 return matches
32 return matches
33
33
34
34
35 class ClientCompleter(object):
35 class ClientCompleter(object):
36 """Client-side completion machinery.
36 """Client-side completion machinery.
37
37
38 How it works: self.complete will be called multiple times, with
38 How it works: self.complete will be called multiple times, with
39 state=0,1,2,... When state=0 it should compute ALL the completion matches,
39 state=0,1,2,... When state=0 it should compute ALL the completion matches,
40 and then return them for each value of state."""
40 and then return them for each value of state."""
41
41
42 def __init__(self, client, session, socket):
42 def __init__(self, client, session, socket):
43 # ugly, but we get called asynchronously and need access to some
43 # ugly, but we get called asynchronously and need access to some
44 # client state, like backgrounded code
44 # client state, like backgrounded code
45 assert readline is not None, "ClientCompleter depends on readline"
45 assert readline is not None, "ClientCompleter depends on readline"
46 self.client = client
46 self.client = client
47 self.session = session
47 self.session = session
48 self.socket = socket
48 self.socket = socket
49 self.matches = []
49 self.matches = []
50
50
51 def request_completion(self, text):
51 def request_completion(self, text):
52 # Get full line to give to the kernel in case it wants more info.
52 # Get full line to give to the kernel in case it wants more info.
53 line = readline.get_line_buffer()
53 line = readline.get_line_buffer()
54 # send completion request to kernel
54 # send completion request to kernel
55 msg = self.session.send(self.socket,
55 msg = self.session.send(self.socket,
56 'complete_request',
56 'complete_request',
57 dict(text=text, line=line))
57 dict(text=text, line=line))
58
58
59 # Give the kernel up to 0.5s to respond
59 # Give the kernel up to 0.5s to respond
60 for i in range(5):
60 for i in range(5):
61 ident,rep = self.session.recv(self.socket)
61 ident,rep = self.session.recv(self.socket)
62 rep = Message(rep)
62 rep = session.Message(rep)
63 if rep is not None and rep.msg_type == 'complete_reply':
63 if rep is not None and rep.msg_type == 'complete_reply':
64 matches = rep.content.matches
64 matches = rep.content.matches
65 break
65 break
66 time.sleep(0.1)
66 time.sleep(0.1)
67 else:
67 else:
68 # timeout
68 # timeout
69 print ('TIMEOUT') # Can't see this message...
69 print ('TIMEOUT') # Can't see this message...
70 matches = None
70 matches = None
71 return matches
71 return matches
72
72
73 def complete(self, text, state):
73 def complete(self, text, state):
74
74
75 if self.client.backgrounded > 0:
75 if self.client.backgrounded > 0:
76 print("\n[Not completing, background tasks active]")
76 print("\n[Not completing, background tasks active]")
77 print(readline.get_line_buffer(), end='')
77 print(readline.get_line_buffer(), end='')
78 return None
78 return None
79
79
80 if state==0:
80 if state==0:
81 matches = self.request_completion(text)
81 matches = self.request_completion(text)
82 if matches is None:
82 if matches is None:
83 self.matches = []
83 self.matches = []
84 print('WARNING: Kernel timeout on tab completion.')
84 print('WARNING: Kernel timeout on tab completion.')
85 else:
85 else:
86 self.matches = matches
86 self.matches = matches
87
87
88 try:
88 try:
89 return self.matches[state]
89 return self.matches[state]
90 except IndexError:
90 except IndexError:
91 return None
91 return None
@@ -1,196 +1,197 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive frontend that talks to a kernel over 0MQ.
2 """A simple interactive frontend that talks to a kernel over 0MQ.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Imports
6 # Imports
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # stdlib
8 # stdlib
9 import cPickle as pickle
9 import cPickle as pickle
10 import code
10 import code
11 import readline
11 import readline
12 import sys
12 import sys
13 import time
13 import time
14 import uuid
14 import uuid
15
15
16 # our own
16 # our own
17 import zmq
17 import zmq
18 import session
18 import session
19 import completer
19 import completer
20 from IPython.utils.localinterfaces import LOCALHOST
20 from IPython.utils.localinterfaces import LOCALHOST
21 from IPython.zmq.session import Message
21
22
22 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
23 # Classes and functions
24 # Classes and functions
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25
26
26 class Console(code.InteractiveConsole):
27 class Console(code.InteractiveConsole):
27
28
28 def __init__(self, locals=None, filename="<console>",
29 def __init__(self, locals=None, filename="<console>",
29 session = session,
30 session = session,
30 request_socket=None,
31 request_socket=None,
31 sub_socket=None):
32 sub_socket=None):
32 code.InteractiveConsole.__init__(self, locals, filename)
33 code.InteractiveConsole.__init__(self, locals, filename)
33 self.session = session
34 self.session = session
34 self.request_socket = request_socket
35 self.request_socket = request_socket
35 self.sub_socket = sub_socket
36 self.sub_socket = sub_socket
36 self.backgrounded = 0
37 self.backgrounded = 0
37 self.messages = {}
38 self.messages = {}
38
39
39 # Set tab completion
40 # Set tab completion
40 self.completer = completer.ClientCompleter(self, session, request_socket)
41 self.completer = completer.ClientCompleter(self, session, request_socket)
41 readline.parse_and_bind('tab: complete')
42 readline.parse_and_bind('tab: complete')
42 readline.parse_and_bind('set show-all-if-ambiguous on')
43 readline.parse_and_bind('set show-all-if-ambiguous on')
43 readline.set_completer(self.completer.complete)
44 readline.set_completer(self.completer.complete)
44
45
45 # Set system prompts
46 # Set system prompts
46 sys.ps1 = 'Py>>> '
47 sys.ps1 = 'Py>>> '
47 sys.ps2 = ' ... '
48 sys.ps2 = ' ... '
48 sys.ps3 = 'Out : '
49 sys.ps3 = 'Out : '
49 # Build dict of handlers for message types
50 # Build dict of handlers for message types
50 self.handlers = {}
51 self.handlers = {}
51 for msg_type in ['pyin', 'pyout', 'pyerr', 'stream']:
52 for msg_type in ['pyin', 'pyout', 'pyerr', 'stream']:
52 self.handlers[msg_type] = getattr(self, 'handle_%s' % msg_type)
53 self.handlers[msg_type] = getattr(self, 'handle_%s' % msg_type)
53
54
54 def handle_pyin(self, omsg):
55 def handle_pyin(self, omsg):
55 if omsg.parent_header.session == self.session.session:
56 if omsg.parent_header.session == self.session.session:
56 return
57 return
57 c = omsg.content.code.rstrip()
58 c = omsg.content.code.rstrip()
58 if c:
59 if c:
59 print '[IN from %s]' % omsg.parent_header.username
60 print '[IN from %s]' % omsg.parent_header.username
60 print c
61 print c
61
62
62 def handle_pyout(self, omsg):
63 def handle_pyout(self, omsg):
63 #print omsg # dbg
64 #print omsg # dbg
64 if omsg.parent_header.session == self.session.session:
65 if omsg.parent_header.session == self.session.session:
65 print "%s%s" % (sys.ps3, omsg.content.data)
66 print "%s%s" % (sys.ps3, omsg.content.data)
66 else:
67 else:
67 print '[Out from %s]' % omsg.parent_header.username
68 print '[Out from %s]' % omsg.parent_header.username
68 print omsg.content.data
69 print omsg.content.data
69
70
70 def print_pyerr(self, err):
71 def print_pyerr(self, err):
71 print >> sys.stderr, err.etype,':', err.evalue
72 print >> sys.stderr, err.etype,':', err.evalue
72 print >> sys.stderr, ''.join(err.traceback)
73 print >> sys.stderr, ''.join(err.traceback)
73
74
74 def handle_pyerr(self, omsg):
75 def handle_pyerr(self, omsg):
75 if omsg.parent_header.session == self.session.session:
76 if omsg.parent_header.session == self.session.session:
76 return
77 return
77 print >> sys.stderr, '[ERR from %s]' % omsg.parent_header.username
78 print >> sys.stderr, '[ERR from %s]' % omsg.parent_header.username
78 self.print_pyerr(omsg.content)
79 self.print_pyerr(omsg.content)
79
80
80 def handle_stream(self, omsg):
81 def handle_stream(self, omsg):
81 if omsg.content.name == 'stdout':
82 if omsg.content.name == 'stdout':
82 outstream = sys.stdout
83 outstream = sys.stdout
83 else:
84 else:
84 outstream = sys.stderr
85 outstream = sys.stderr
85 print >> outstream, '*ERR*',
86 print >> outstream, '*ERR*',
86 print >> outstream, omsg.content.data,
87 print >> outstream, omsg.content.data,
87
88
88 def handle_output(self, omsg):
89 def handle_output(self, omsg):
89 handler = self.handlers.get(omsg.msg_type, None)
90 handler = self.handlers.get(omsg.msg_type, None)
90 if handler is not None:
91 if handler is not None:
91 handler(omsg)
92 handler(omsg)
92
93
93 def recv_output(self):
94 def recv_output(self):
94 while True:
95 while True:
95 ident,msg = self.session.recv(self.sub_socket)
96 ident,msg = self.session.recv(self.sub_socket)
96 if msg is None:
97 if msg is None:
97 break
98 break
98 self.handle_output(Message(msg))
99 self.handle_output(Message(msg))
99
100
100 def handle_reply(self, rep):
101 def handle_reply(self, rep):
101 # Handle any side effects on output channels
102 # Handle any side effects on output channels
102 self.recv_output()
103 self.recv_output()
103 # Now, dispatch on the possible reply types we must handle
104 # Now, dispatch on the possible reply types we must handle
104 if rep is None:
105 if rep is None:
105 return
106 return
106 if rep.content.status == 'error':
107 if rep.content.status == 'error':
107 self.print_pyerr(rep.content)
108 self.print_pyerr(rep.content)
108 elif rep.content.status == 'aborted':
109 elif rep.content.status == 'aborted':
109 print >> sys.stderr, "ERROR: ABORTED"
110 print >> sys.stderr, "ERROR: ABORTED"
110 ab = self.messages[rep.parent_header.msg_id].content
111 ab = self.messages[rep.parent_header.msg_id].content
111 if 'code' in ab:
112 if 'code' in ab:
112 print >> sys.stderr, ab.code
113 print >> sys.stderr, ab.code
113 else:
114 else:
114 print >> sys.stderr, ab
115 print >> sys.stderr, ab
115
116
116 def recv_reply(self):
117 def recv_reply(self):
117 ident,rep = self.session.recv(self.request_socket)
118 ident,rep = self.session.recv(self.request_socket)
118 mrep = Message(rep)
119 mrep = Message(rep)
119 self.handle_reply(mrep)
120 self.handle_reply(mrep)
120 return mrep
121 return mrep
121
122
122 def runcode(self, code):
123 def runcode(self, code):
123 # We can't pickle code objects, so fetch the actual source
124 # We can't pickle code objects, so fetch the actual source
124 src = '\n'.join(self.buffer)
125 src = '\n'.join(self.buffer)
125
126
126 # for non-background inputs, if we do have previoiusly backgrounded
127 # for non-background inputs, if we do have previoiusly backgrounded
127 # jobs, check to see if they've produced results
128 # jobs, check to see if they've produced results
128 if not src.endswith(';'):
129 if not src.endswith(';'):
129 while self.backgrounded > 0:
130 while self.backgrounded > 0:
130 #print 'checking background'
131 #print 'checking background'
131 rep = self.recv_reply()
132 rep = self.recv_reply()
132 if rep:
133 if rep:
133 self.backgrounded -= 1
134 self.backgrounded -= 1
134 time.sleep(0.05)
135 time.sleep(0.05)
135
136
136 # Send code execution message to kernel
137 # Send code execution message to kernel
137 omsg = self.session.send(self.request_socket,
138 omsg = self.session.send(self.request_socket,
138 'execute_request', dict(code=src))
139 'execute_request', dict(code=src))
139 self.messages[omsg.header.msg_id] = omsg
140 self.messages[omsg.header.msg_id] = omsg
140
141
141 # Fake asynchronicity by letting the user put ';' at the end of the line
142 # Fake asynchronicity by letting the user put ';' at the end of the line
142 if src.endswith(';'):
143 if src.endswith(';'):
143 self.backgrounded += 1
144 self.backgrounded += 1
144 return
145 return
145
146
146 # For foreground jobs, wait for reply
147 # For foreground jobs, wait for reply
147 while True:
148 while True:
148 rep = self.recv_reply()
149 rep = self.recv_reply()
149 if rep is not None:
150 if rep is not None:
150 break
151 break
151 self.recv_output()
152 self.recv_output()
152 time.sleep(0.05)
153 time.sleep(0.05)
153 else:
154 else:
154 # We exited without hearing back from the kernel!
155 # We exited without hearing back from the kernel!
155 print >> sys.stderr, 'ERROR!!! kernel never got back to us!!!'
156 print >> sys.stderr, 'ERROR!!! kernel never got back to us!!!'
156
157
157
158
158 class InteractiveClient(object):
159 class InteractiveClient(object):
159 def __init__(self, session, request_socket, sub_socket):
160 def __init__(self, session, request_socket, sub_socket):
160 self.session = session
161 self.session = session
161 self.request_socket = request_socket
162 self.request_socket = request_socket
162 self.sub_socket = sub_socket
163 self.sub_socket = sub_socket
163 self.console = Console(None, '<zmq-console>',
164 self.console = Console(None, '<zmq-console>',
164 session, request_socket, sub_socket)
165 session, request_socket, sub_socket)
165
166
166 def interact(self):
167 def interact(self):
167 self.console.interact()
168 self.console.interact()
168
169
169
170
170 def main():
171 def main():
171 # Defaults
172 # Defaults
172 #ip = '192.168.2.109'
173 #ip = '192.168.2.109'
173 ip = LOCALHOST
174 ip = LOCALHOST
174 #ip = '99.146.222.252'
175 #ip = '99.146.222.252'
175 port_base = 5575
176 port_base = 5575
176 connection = ('tcp://%s' % ip) + ':%i'
177 connection = ('tcp://%s' % ip) + ':%i'
177 req_conn = connection % port_base
178 req_conn = connection % port_base
178 sub_conn = connection % (port_base+1)
179 sub_conn = connection % (port_base+1)
179
180
180 # Create initial sockets
181 # Create initial sockets
181 c = zmq.Context()
182 c = zmq.Context()
182 request_socket = c.socket(zmq.DEALER)
183 request_socket = c.socket(zmq.DEALER)
183 request_socket.connect(req_conn)
184 request_socket.connect(req_conn)
184
185
185 sub_socket = c.socket(zmq.SUB)
186 sub_socket = c.socket(zmq.SUB)
186 sub_socket.connect(sub_conn)
187 sub_socket.connect(sub_conn)
187 sub_socket.setsockopt(zmq.SUBSCRIBE, '')
188 sub_socket.setsockopt(zmq.SUBSCRIBE, '')
188
189
189 # Make session and user-facing client
190 # Make session and user-facing client
190 sess = session.Session()
191 sess = session.Session()
191 client = InteractiveClient(sess, request_socket, sub_socket)
192 client = InteractiveClient(sess, request_socket, sub_socket)
192 client.interact()
193 client.interact()
193
194
194
195
195 if __name__ == '__main__':
196 if __name__ == '__main__':
196 main()
197 main()
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now