Show More
@@ -1,702 +1,702 b'' | |||
|
1 | 1 | """A simple configuration system. |
|
2 | 2 | |
|
3 | 3 | Authors |
|
4 | 4 | ------- |
|
5 | 5 | * Brian Granger |
|
6 | 6 | * Fernando Perez |
|
7 | 7 | * Min RK |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Copyright (C) 2008-2011 The IPython Development Team |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Imports |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | import __builtin__ as builtin_mod |
|
22 | 22 | import os |
|
23 | 23 | import re |
|
24 | 24 | import sys |
|
25 | 25 | |
|
26 | 26 | from IPython.external import argparse |
|
27 | 27 | from IPython.utils.path import filefind, get_ipython_dir |
|
28 | 28 | from IPython.utils import py3compat, text, warn |
|
29 | 29 | |
|
30 | 30 | #----------------------------------------------------------------------------- |
|
31 | 31 | # Exceptions |
|
32 | 32 | #----------------------------------------------------------------------------- |
|
33 | 33 | |
|
34 | 34 | |
|
35 | 35 | class ConfigError(Exception): |
|
36 | 36 | pass |
|
37 | 37 | |
|
38 | 38 | class ConfigLoaderError(ConfigError): |
|
39 | 39 | pass |
|
40 | 40 | |
|
41 | 41 | class ConfigFileNotFound(ConfigError): |
|
42 | 42 | pass |
|
43 | 43 | |
|
44 | 44 | class ArgumentError(ConfigLoaderError): |
|
45 | 45 | pass |
|
46 | 46 | |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | # Argparse fix |
|
49 | 49 | #----------------------------------------------------------------------------- |
|
50 | 50 | |
|
51 | 51 | # Unfortunately argparse by default prints help messages to stderr instead of |
|
52 | 52 | # stdout. This makes it annoying to capture long help screens at the command |
|
53 | 53 | # line, since one must know how to pipe stderr, which many users don't know how |
|
54 | 54 | # to do. So we override the print_help method with one that defaults to |
|
55 | 55 | # stdout and use our class instead. |
|
56 | 56 | |
|
57 | 57 | class ArgumentParser(argparse.ArgumentParser): |
|
58 | 58 | """Simple argparse subclass that prints help to stdout by default.""" |
|
59 | 59 | |
|
60 | 60 | def print_help(self, file=None): |
|
61 | 61 | if file is None: |
|
62 | 62 | file = sys.stdout |
|
63 | 63 | return super(ArgumentParser, self).print_help(file) |
|
64 | 64 | |
|
65 | 65 | print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__ |
|
66 | 66 | |
|
67 | 67 | #----------------------------------------------------------------------------- |
|
68 | 68 | # Config class for holding config information |
|
69 | 69 | #----------------------------------------------------------------------------- |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | class Config(dict): |
|
73 | 73 | """An attribute based dict that can do smart merges.""" |
|
74 | 74 | |
|
75 | 75 | def __init__(self, *args, **kwds): |
|
76 | 76 | dict.__init__(self, *args, **kwds) |
|
77 | 77 | # This sets self.__dict__ = self, but it has to be done this way |
|
78 | 78 | # because we are also overriding __setattr__. |
|
79 | 79 | dict.__setattr__(self, '__dict__', self) |
|
80 | 80 | |
|
81 | 81 | def _merge(self, other): |
|
82 | 82 | to_update = {} |
|
83 | 83 | for k, v in other.iteritems(): |
|
84 | 84 | if not self.has_key(k): |
|
85 | 85 | to_update[k] = v |
|
86 | 86 | else: # I have this key |
|
87 | 87 | if isinstance(v, Config): |
|
88 | 88 | # Recursively merge common sub Configs |
|
89 | 89 | self[k]._merge(v) |
|
90 | 90 | else: |
|
91 | 91 | # Plain updates for non-Configs |
|
92 | 92 | to_update[k] = v |
|
93 | 93 | |
|
94 | 94 | self.update(to_update) |
|
95 | 95 | |
|
96 | 96 | def _is_section_key(self, key): |
|
97 | 97 | if key[0].upper()==key[0] and not key.startswith('_'): |
|
98 | 98 | return True |
|
99 | 99 | else: |
|
100 | 100 | return False |
|
101 | 101 | |
|
102 | 102 | def __contains__(self, key): |
|
103 | 103 | if self._is_section_key(key): |
|
104 | 104 | return True |
|
105 | 105 | else: |
|
106 | 106 | return super(Config, self).__contains__(key) |
|
107 | 107 | # .has_key is deprecated for dictionaries. |
|
108 | 108 | has_key = __contains__ |
|
109 | 109 | |
|
110 | 110 | def _has_section(self, key): |
|
111 | 111 | if self._is_section_key(key): |
|
112 | 112 | if super(Config, self).__contains__(key): |
|
113 | 113 | return True |
|
114 | 114 | return False |
|
115 | 115 | |
|
116 | 116 | def copy(self): |
|
117 | 117 | return type(self)(dict.copy(self)) |
|
118 | 118 | |
|
119 | 119 | def __copy__(self): |
|
120 | 120 | return self.copy() |
|
121 | 121 | |
|
122 | 122 | def __deepcopy__(self, memo): |
|
123 | 123 | import copy |
|
124 | 124 | return type(self)(copy.deepcopy(self.items())) |
|
125 | 125 | |
|
126 | 126 | def __getitem__(self, key): |
|
127 | 127 | # We cannot use directly self._is_section_key, because it triggers |
|
128 | 128 | # infinite recursion on top of PyPy. Instead, we manually fish the |
|
129 | 129 | # bound method. |
|
130 | 130 | is_section_key = self.__class__._is_section_key.__get__(self) |
|
131 | 131 | |
|
132 | 132 | # Because we use this for an exec namespace, we need to delegate |
|
133 | 133 | # the lookup of names in __builtin__ to itself. This means |
|
134 | 134 | # that you can't have section or attribute names that are |
|
135 | 135 | # builtins. |
|
136 | 136 | try: |
|
137 | 137 | return getattr(builtin_mod, key) |
|
138 | 138 | except AttributeError: |
|
139 | 139 | pass |
|
140 | 140 | if is_section_key(key): |
|
141 | 141 | try: |
|
142 | 142 | return dict.__getitem__(self, key) |
|
143 | 143 | except KeyError: |
|
144 | 144 | c = Config() |
|
145 | 145 | dict.__setitem__(self, key, c) |
|
146 | 146 | return c |
|
147 | 147 | else: |
|
148 | 148 | return dict.__getitem__(self, key) |
|
149 | 149 | |
|
150 | 150 | def __setitem__(self, key, value): |
|
151 | 151 | # Don't allow names in __builtin__ to be modified. |
|
152 | 152 | if hasattr(builtin_mod, key): |
|
153 | 153 | raise ConfigError('Config variable names cannot have the same name ' |
|
154 | 154 | 'as a Python builtin: %s' % key) |
|
155 | 155 | if self._is_section_key(key): |
|
156 | 156 | if not isinstance(value, Config): |
|
157 | 157 | raise ValueError('values whose keys begin with an uppercase ' |
|
158 | 158 | 'char must be Config instances: %r, %r' % (key, value)) |
|
159 | 159 | else: |
|
160 | 160 | dict.__setitem__(self, key, value) |
|
161 | 161 | |
|
162 | 162 | def __getattr__(self, key): |
|
163 | 163 | try: |
|
164 | 164 | return self.__getitem__(key) |
|
165 | 165 | except KeyError, e: |
|
166 | 166 | raise AttributeError(e) |
|
167 | 167 | |
|
168 | 168 | def __setattr__(self, key, value): |
|
169 | 169 | try: |
|
170 | 170 | self.__setitem__(key, value) |
|
171 | 171 | except KeyError, e: |
|
172 | 172 | raise AttributeError(e) |
|
173 | 173 | |
|
174 | 174 | def __delattr__(self, key): |
|
175 | 175 | try: |
|
176 | 176 | dict.__delitem__(self, key) |
|
177 | 177 | except KeyError, e: |
|
178 | 178 | raise AttributeError(e) |
|
179 | 179 | |
|
180 | 180 | |
|
181 | 181 | #----------------------------------------------------------------------------- |
|
182 | 182 | # Config loading classes |
|
183 | 183 | #----------------------------------------------------------------------------- |
|
184 | 184 | |
|
185 | 185 | |
|
186 | 186 | class ConfigLoader(object): |
|
187 | 187 | """A object for loading configurations from just about anywhere. |
|
188 | 188 | |
|
189 | 189 | The resulting configuration is packaged as a :class:`Struct`. |
|
190 | 190 | |
|
191 | 191 | Notes |
|
192 | 192 | ----- |
|
193 | 193 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
194 | 194 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
195 | 195 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
196 | 196 | not implement complex logic for finding config files. It does not handle |
|
197 | 197 | default values or merge multiple configs. These things need to be |
|
198 | 198 | handled elsewhere. |
|
199 | 199 | """ |
|
200 | 200 | |
|
201 | 201 | def __init__(self): |
|
202 | 202 | """A base class for config loaders. |
|
203 | 203 | |
|
204 | 204 | Examples |
|
205 | 205 | -------- |
|
206 | 206 | |
|
207 | 207 | >>> cl = ConfigLoader() |
|
208 | 208 | >>> config = cl.load_config() |
|
209 | 209 | >>> config |
|
210 | 210 | {} |
|
211 | 211 | """ |
|
212 | 212 | self.clear() |
|
213 | 213 | |
|
214 | 214 | def clear(self): |
|
215 | 215 | self.config = Config() |
|
216 | 216 | |
|
217 | 217 | def load_config(self): |
|
218 | 218 | """Load a config from somewhere, return a :class:`Config` instance. |
|
219 | 219 | |
|
220 | 220 | Usually, this will cause self.config to be set and then returned. |
|
221 | 221 | However, in most cases, :meth:`ConfigLoader.clear` should be called |
|
222 | 222 | to erase any previous state. |
|
223 | 223 | """ |
|
224 | 224 | self.clear() |
|
225 | 225 | return self.config |
|
226 | 226 | |
|
227 | 227 | |
|
228 | 228 | class FileConfigLoader(ConfigLoader): |
|
229 | 229 | """A base class for file based configurations. |
|
230 | 230 | |
|
231 | 231 | As we add more file based config loaders, the common logic should go |
|
232 | 232 | here. |
|
233 | 233 | """ |
|
234 | 234 | pass |
|
235 | 235 | |
|
236 | 236 | |
|
237 | 237 | class PyFileConfigLoader(FileConfigLoader): |
|
238 | 238 | """A config loader for pure python files. |
|
239 | 239 | |
|
240 | 240 | This calls execfile on a plain python file and looks for attributes |
|
241 | 241 | that are all caps. These attribute are added to the config Struct. |
|
242 | 242 | """ |
|
243 | 243 | |
|
244 | 244 | def __init__(self, filename, path=None): |
|
245 | 245 | """Build a config loader for a filename and path. |
|
246 | 246 | |
|
247 | 247 | Parameters |
|
248 | 248 | ---------- |
|
249 | 249 | filename : str |
|
250 | 250 | The file name of the config file. |
|
251 | 251 | path : str, list, tuple |
|
252 | 252 | The path to search for the config file on, or a sequence of |
|
253 | 253 | paths to try in order. |
|
254 | 254 | """ |
|
255 | 255 | super(PyFileConfigLoader, self).__init__() |
|
256 | 256 | self.filename = filename |
|
257 | 257 | self.path = path |
|
258 | 258 | self.full_filename = '' |
|
259 | 259 | self.data = None |
|
260 | 260 | |
|
261 | 261 | def load_config(self): |
|
262 | 262 | """Load the config from a file and return it as a Struct.""" |
|
263 | 263 | self.clear() |
|
264 | 264 | try: |
|
265 | 265 | self._find_file() |
|
266 | 266 | except IOError as e: |
|
267 | 267 | raise ConfigFileNotFound(str(e)) |
|
268 | 268 | self._read_file_as_dict() |
|
269 | 269 | self._convert_to_config() |
|
270 | 270 | return self.config |
|
271 | 271 | |
|
272 | 272 | def _find_file(self): |
|
273 | 273 | """Try to find the file by searching the paths.""" |
|
274 | 274 | self.full_filename = filefind(self.filename, self.path) |
|
275 | 275 | |
|
276 | 276 | def _read_file_as_dict(self): |
|
277 | 277 | """Load the config file into self.config, with recursive loading.""" |
|
278 | 278 | # This closure is made available in the namespace that is used |
|
279 | 279 | # to exec the config file. It allows users to call |
|
280 | 280 | # load_subconfig('myconfig.py') to load config files recursively. |
|
281 | 281 | # It needs to be a closure because it has references to self.path |
|
282 | 282 | # and self.config. The sub-config is loaded with the same path |
|
283 | 283 | # as the parent, but it uses an empty config which is then merged |
|
284 | 284 | # with the parents. |
|
285 | 285 | |
|
286 | 286 | # If a profile is specified, the config file will be loaded |
|
287 | 287 | # from that profile |
|
288 | 288 | |
|
289 | 289 | def load_subconfig(fname, profile=None): |
|
290 | 290 | # import here to prevent circular imports |
|
291 | 291 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
292 | 292 | if profile is not None: |
|
293 | 293 | try: |
|
294 | 294 | profile_dir = ProfileDir.find_profile_dir_by_name( |
|
295 | 295 | get_ipython_dir(), |
|
296 | 296 | profile, |
|
297 | 297 | ) |
|
298 | 298 | except ProfileDirError: |
|
299 | 299 | return |
|
300 | 300 | path = profile_dir.location |
|
301 | 301 | else: |
|
302 | 302 | path = self.path |
|
303 | 303 | loader = PyFileConfigLoader(fname, path) |
|
304 | 304 | try: |
|
305 | 305 | sub_config = loader.load_config() |
|
306 | 306 | except ConfigFileNotFound: |
|
307 | 307 | # Pass silently if the sub config is not there. This happens |
|
308 | 308 | # when a user s using a profile, but not the default config. |
|
309 | 309 | pass |
|
310 | 310 | else: |
|
311 | 311 | self.config._merge(sub_config) |
|
312 | 312 | |
|
313 | 313 | # Again, this needs to be a closure and should be used in config |
|
314 | 314 | # files to get the config being loaded. |
|
315 | 315 | def get_config(): |
|
316 | 316 | return self.config |
|
317 | 317 | |
|
318 | 318 | namespace = dict(load_subconfig=load_subconfig, get_config=get_config) |
|
319 | 319 | fs_encoding = sys.getfilesystemencoding() or 'ascii' |
|
320 | 320 | conf_filename = self.full_filename.encode(fs_encoding) |
|
321 | 321 | py3compat.execfile(conf_filename, namespace) |
|
322 | 322 | |
|
323 | 323 | def _convert_to_config(self): |
|
324 | 324 | if self.data is None: |
|
325 | 325 | ConfigLoaderError('self.data does not exist') |
|
326 | 326 | |
|
327 | 327 | |
|
328 | 328 | class CommandLineConfigLoader(ConfigLoader): |
|
329 | 329 | """A config loader for command line arguments. |
|
330 | 330 | |
|
331 | 331 | As we add more command line based loaders, the common logic should go |
|
332 | 332 | here. |
|
333 | 333 | """ |
|
334 | 334 | |
|
335 | 335 | def _exec_config_str(self, lhs, rhs): |
|
336 | 336 | """execute self.config.<lhs>=<rhs> |
|
337 | 337 | |
|
338 | 338 | * expands ~ with expanduser |
|
339 | 339 | * tries to assign with raw exec, otherwise assigns with just the string, |
|
340 | 340 | allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* |
|
341 | 341 | equivalent are `--C.a=4` and `--C.a='4'`. |
|
342 | 342 | """ |
|
343 | 343 | rhs = os.path.expanduser(rhs) |
|
344 | 344 | exec_str = 'self.config.' + lhs + '=' + rhs |
|
345 | 345 | try: |
|
346 | 346 | # Try to see if regular Python syntax will work. This |
|
347 | 347 | # won't handle strings as the quote marks are removed |
|
348 | 348 | # by the system shell. |
|
349 | 349 | exec exec_str in locals(), globals() |
|
350 | 350 | except (NameError, SyntaxError): |
|
351 | 351 | # This case happens if the rhs is a string but without |
|
352 | 352 | # the quote marks. Use repr, to get quote marks, and |
|
353 | 353 | # 'u' prefix and see if |
|
354 | 354 | # it succeeds. If it still fails, we let it raise. |
|
355 | 355 | exec_str = u'self.config.' + lhs + '= rhs' |
|
356 | 356 | exec exec_str in locals(), globals() |
|
357 | 357 | |
|
358 | 358 | def _load_flag(self, cfg): |
|
359 | 359 | """update self.config from a flag, which can be a dict or Config""" |
|
360 | 360 | if isinstance(cfg, (dict, Config)): |
|
361 | 361 | # don't clobber whole config sections, update |
|
362 | 362 | # each section from config: |
|
363 | 363 | for sec,c in cfg.iteritems(): |
|
364 | 364 | self.config[sec].update(c) |
|
365 | 365 | else: |
|
366 |
raise |
|
|
366 | raise TypeError("Invalid flag: %r" % cfg) | |
|
367 | 367 | |
|
368 | 368 | # raw --identifier=value pattern |
|
369 | 369 | # but *also* accept '-' as wordsep, for aliases |
|
370 | 370 | # accepts: --foo=a |
|
371 | 371 | # --Class.trait=value |
|
372 | 372 | # --alias-name=value |
|
373 | 373 | # rejects: -foo=value |
|
374 | 374 | # --foo |
|
375 | 375 | # --Class.trait |
|
376 | 376 | kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*') |
|
377 | 377 | |
|
378 | 378 | # just flags, no assignments, with two *or one* leading '-' |
|
379 | 379 | # accepts: --foo |
|
380 | 380 | # -foo-bar-again |
|
381 | 381 | # rejects: --anything=anything |
|
382 | 382 | # --two.word |
|
383 | 383 | |
|
384 | 384 | flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$') |
|
385 | 385 | |
|
386 | 386 | class KeyValueConfigLoader(CommandLineConfigLoader): |
|
387 | 387 | """A config loader that loads key value pairs from the command line. |
|
388 | 388 | |
|
389 | 389 | This allows command line options to be gives in the following form:: |
|
390 | 390 | |
|
391 | 391 | ipython --profile="foo" --InteractiveShell.autocall=False |
|
392 | 392 | """ |
|
393 | 393 | |
|
394 | 394 | def __init__(self, argv=None, aliases=None, flags=None): |
|
395 | 395 | """Create a key value pair config loader. |
|
396 | 396 | |
|
397 | 397 | Parameters |
|
398 | 398 | ---------- |
|
399 | 399 | argv : list |
|
400 | 400 | A list that has the form of sys.argv[1:] which has unicode |
|
401 | 401 | elements of the form u"key=value". If this is None (default), |
|
402 | 402 | then sys.argv[1:] will be used. |
|
403 | 403 | aliases : dict |
|
404 | 404 | A dict of aliases for configurable traits. |
|
405 | 405 | Keys are the short aliases, Values are the resolved trait. |
|
406 | 406 | Of the form: `{'alias' : 'Configurable.trait'}` |
|
407 | 407 | flags : dict |
|
408 | 408 | A dict of flags, keyed by str name. Vaues can be Config objects, |
|
409 | 409 | dicts, or "key=value" strings. If Config or dict, when the flag |
|
410 | 410 | is triggered, The flag is loaded as `self.config.update(m)`. |
|
411 | 411 | |
|
412 | 412 | Returns |
|
413 | 413 | ------- |
|
414 | 414 | config : Config |
|
415 | 415 | The resulting Config object. |
|
416 | 416 | |
|
417 | 417 | Examples |
|
418 | 418 | -------- |
|
419 | 419 | |
|
420 | 420 | >>> from IPython.config.loader import KeyValueConfigLoader |
|
421 | 421 | >>> cl = KeyValueConfigLoader() |
|
422 | 422 | >>> cl.load_config(["--A.name='brian'","--B.number=0"]) |
|
423 | 423 | {'A': {'name': 'brian'}, 'B': {'number': 0}} |
|
424 | 424 | """ |
|
425 | 425 | self.clear() |
|
426 | 426 | if argv is None: |
|
427 | 427 | argv = sys.argv[1:] |
|
428 | 428 | self.argv = argv |
|
429 | 429 | self.aliases = aliases or {} |
|
430 | 430 | self.flags = flags or {} |
|
431 | 431 | |
|
432 | 432 | |
|
433 | 433 | def clear(self): |
|
434 | 434 | super(KeyValueConfigLoader, self).clear() |
|
435 | 435 | self.extra_args = [] |
|
436 | 436 | |
|
437 | 437 | |
|
438 | 438 | def _decode_argv(self, argv, enc=None): |
|
439 | 439 | """decode argv if bytes, using stin.encoding, falling back on default enc""" |
|
440 | 440 | uargv = [] |
|
441 | 441 | if enc is None: |
|
442 | 442 | enc = text.getdefaultencoding() |
|
443 | 443 | for arg in argv: |
|
444 | 444 | if not isinstance(arg, unicode): |
|
445 | 445 | # only decode if not already decoded |
|
446 | 446 | arg = arg.decode(enc) |
|
447 | 447 | uargv.append(arg) |
|
448 | 448 | return uargv |
|
449 | 449 | |
|
450 | 450 | |
|
451 | 451 | def load_config(self, argv=None, aliases=None, flags=None): |
|
452 | 452 | """Parse the configuration and generate the Config object. |
|
453 | 453 | |
|
454 | 454 | After loading, any arguments that are not key-value or |
|
455 | 455 | flags will be stored in self.extra_args - a list of |
|
456 | 456 | unparsed command-line arguments. This is used for |
|
457 | 457 | arguments such as input files or subcommands. |
|
458 | 458 | |
|
459 | 459 | Parameters |
|
460 | 460 | ---------- |
|
461 | 461 | argv : list, optional |
|
462 | 462 | A list that has the form of sys.argv[1:] which has unicode |
|
463 | 463 | elements of the form u"key=value". If this is None (default), |
|
464 | 464 | then self.argv will be used. |
|
465 | 465 | aliases : dict |
|
466 | 466 | A dict of aliases for configurable traits. |
|
467 | 467 | Keys are the short aliases, Values are the resolved trait. |
|
468 | 468 | Of the form: `{'alias' : 'Configurable.trait'}` |
|
469 | 469 | flags : dict |
|
470 | 470 | A dict of flags, keyed by str name. Values can be Config objects |
|
471 | 471 | or dicts. When the flag is triggered, The config is loaded as |
|
472 | 472 | `self.config.update(cfg)`. |
|
473 | 473 | """ |
|
474 | 474 | from IPython.config.configurable import Configurable |
|
475 | 475 | |
|
476 | 476 | self.clear() |
|
477 | 477 | if argv is None: |
|
478 | 478 | argv = self.argv |
|
479 | 479 | if aliases is None: |
|
480 | 480 | aliases = self.aliases |
|
481 | 481 | if flags is None: |
|
482 | 482 | flags = self.flags |
|
483 | 483 | |
|
484 | 484 | # ensure argv is a list of unicode strings: |
|
485 | 485 | uargv = self._decode_argv(argv) |
|
486 | 486 | for idx,raw in enumerate(uargv): |
|
487 | 487 | # strip leading '-' |
|
488 | 488 | item = raw.lstrip('-') |
|
489 | 489 | |
|
490 | 490 | if raw == '--': |
|
491 | 491 | # don't parse arguments after '--' |
|
492 | 492 | # this is useful for relaying arguments to scripts, e.g. |
|
493 | 493 | # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py |
|
494 | 494 | self.extra_args.extend(uargv[idx+1:]) |
|
495 | 495 | break |
|
496 | 496 | |
|
497 | 497 | if kv_pattern.match(raw): |
|
498 | 498 | lhs,rhs = item.split('=',1) |
|
499 | 499 | # Substitute longnames for aliases. |
|
500 | 500 | if lhs in aliases: |
|
501 | 501 | lhs = aliases[lhs] |
|
502 | 502 | if '.' not in lhs: |
|
503 | 503 | # probably a mistyped alias, but not technically illegal |
|
504 | 504 | warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs) |
|
505 | 505 | try: |
|
506 | 506 | self._exec_config_str(lhs, rhs) |
|
507 | 507 | except Exception: |
|
508 | 508 | raise ArgumentError("Invalid argument: '%s'" % raw) |
|
509 | 509 | |
|
510 | 510 | elif flag_pattern.match(raw): |
|
511 | 511 | if item in flags: |
|
512 | 512 | cfg,help = flags[item] |
|
513 | 513 | self._load_flag(cfg) |
|
514 | 514 | else: |
|
515 | 515 | raise ArgumentError("Unrecognized flag: '%s'"%raw) |
|
516 | 516 | elif raw.startswith('-'): |
|
517 | 517 | kv = '--'+item |
|
518 | 518 | if kv_pattern.match(kv): |
|
519 | 519 | raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv)) |
|
520 | 520 | else: |
|
521 | 521 | raise ArgumentError("Invalid argument: '%s'"%raw) |
|
522 | 522 | else: |
|
523 | 523 | # keep all args that aren't valid in a list, |
|
524 | 524 | # in case our parent knows what to do with them. |
|
525 | 525 | self.extra_args.append(item) |
|
526 | 526 | return self.config |
|
527 | 527 | |
|
528 | 528 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
529 | 529 | """A loader that uses the argparse module to load from the command line.""" |
|
530 | 530 | |
|
531 | 531 | def __init__(self, argv=None, aliases=None, flags=None, *parser_args, **parser_kw): |
|
532 | 532 | """Create a config loader for use with argparse. |
|
533 | 533 | |
|
534 | 534 | Parameters |
|
535 | 535 | ---------- |
|
536 | 536 | |
|
537 | 537 | argv : optional, list |
|
538 | 538 | If given, used to read command-line arguments from, otherwise |
|
539 | 539 | sys.argv[1:] is used. |
|
540 | 540 | |
|
541 | 541 | parser_args : tuple |
|
542 | 542 | A tuple of positional arguments that will be passed to the |
|
543 | 543 | constructor of :class:`argparse.ArgumentParser`. |
|
544 | 544 | |
|
545 | 545 | parser_kw : dict |
|
546 | 546 | A tuple of keyword arguments that will be passed to the |
|
547 | 547 | constructor of :class:`argparse.ArgumentParser`. |
|
548 | 548 | |
|
549 | 549 | Returns |
|
550 | 550 | ------- |
|
551 | 551 | config : Config |
|
552 | 552 | The resulting Config object. |
|
553 | 553 | """ |
|
554 | 554 | super(CommandLineConfigLoader, self).__init__() |
|
555 | 555 | self.clear() |
|
556 | 556 | if argv is None: |
|
557 | 557 | argv = sys.argv[1:] |
|
558 | 558 | self.argv = argv |
|
559 | 559 | self.aliases = aliases or {} |
|
560 | 560 | self.flags = flags or {} |
|
561 | 561 | |
|
562 | 562 | self.parser_args = parser_args |
|
563 | 563 | self.version = parser_kw.pop("version", None) |
|
564 | 564 | kwargs = dict(argument_default=argparse.SUPPRESS) |
|
565 | 565 | kwargs.update(parser_kw) |
|
566 | 566 | self.parser_kw = kwargs |
|
567 | 567 | |
|
568 | 568 | def load_config(self, argv=None, aliases=None, flags=None): |
|
569 | 569 | """Parse command line arguments and return as a Config object. |
|
570 | 570 | |
|
571 | 571 | Parameters |
|
572 | 572 | ---------- |
|
573 | 573 | |
|
574 | 574 | args : optional, list |
|
575 | 575 | If given, a list with the structure of sys.argv[1:] to parse |
|
576 | 576 | arguments from. If not given, the instance's self.argv attribute |
|
577 | 577 | (given at construction time) is used.""" |
|
578 | 578 | self.clear() |
|
579 | 579 | if argv is None: |
|
580 | 580 | argv = self.argv |
|
581 | 581 | if aliases is None: |
|
582 | 582 | aliases = self.aliases |
|
583 | 583 | if flags is None: |
|
584 | 584 | flags = self.flags |
|
585 | 585 | self._create_parser(aliases, flags) |
|
586 | 586 | self._parse_args(argv) |
|
587 | 587 | self._convert_to_config() |
|
588 | 588 | return self.config |
|
589 | 589 | |
|
590 | 590 | def get_extra_args(self): |
|
591 | 591 | if hasattr(self, 'extra_args'): |
|
592 | 592 | return self.extra_args |
|
593 | 593 | else: |
|
594 | 594 | return [] |
|
595 | 595 | |
|
596 | 596 | def _create_parser(self, aliases=None, flags=None): |
|
597 | 597 | self.parser = ArgumentParser(*self.parser_args, **self.parser_kw) |
|
598 | 598 | self._add_arguments(aliases, flags) |
|
599 | 599 | |
|
600 | 600 | def _add_arguments(self, aliases=None, flags=None): |
|
601 | 601 | raise NotImplementedError("subclasses must implement _add_arguments") |
|
602 | 602 | |
|
603 | 603 | def _parse_args(self, args): |
|
604 | 604 | """self.parser->self.parsed_data""" |
|
605 | 605 | # decode sys.argv to support unicode command-line options |
|
606 | 606 | enc = text.getdefaultencoding() |
|
607 | 607 | uargs = [py3compat.cast_unicode(a, enc) for a in args] |
|
608 | 608 | self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs) |
|
609 | 609 | |
|
610 | 610 | def _convert_to_config(self): |
|
611 | 611 | """self.parsed_data->self.config""" |
|
612 | 612 | for k, v in vars(self.parsed_data).iteritems(): |
|
613 | 613 | exec "self.config.%s = v"%k in locals(), globals() |
|
614 | 614 | |
|
615 | 615 | class KVArgParseConfigLoader(ArgParseConfigLoader): |
|
616 | 616 | """A config loader that loads aliases and flags with argparse, |
|
617 | 617 | but will use KVLoader for the rest. This allows better parsing |
|
618 | 618 | of common args, such as `ipython -c 'print 5'`, but still gets |
|
619 | 619 | arbitrary config with `ipython --InteractiveShell.use_readline=False`""" |
|
620 | 620 | |
|
621 | 621 | def _convert_to_config(self): |
|
622 | 622 | """self.parsed_data->self.config""" |
|
623 | 623 | for k, v in vars(self.parsed_data).iteritems(): |
|
624 | 624 | self._exec_config_str(k, v) |
|
625 | 625 | |
|
626 | 626 | def _add_arguments(self, aliases=None, flags=None): |
|
627 | 627 | self.alias_flags = {} |
|
628 | 628 | # print aliases, flags |
|
629 | 629 | if aliases is None: |
|
630 | 630 | aliases = self.aliases |
|
631 | 631 | if flags is None: |
|
632 | 632 | flags = self.flags |
|
633 | 633 | paa = self.parser.add_argument |
|
634 | 634 | for key,value in aliases.iteritems(): |
|
635 | 635 | if key in flags: |
|
636 | 636 | # flags |
|
637 | 637 | nargs = '?' |
|
638 | 638 | else: |
|
639 | 639 | nargs = None |
|
640 | 640 | if len(key) is 1: |
|
641 | 641 | paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs) |
|
642 | 642 | else: |
|
643 | 643 | paa('--'+key, type=unicode, dest=value, nargs=nargs) |
|
644 | 644 | for key, (value, help) in flags.iteritems(): |
|
645 | 645 | if key in self.aliases: |
|
646 | 646 | # |
|
647 | 647 | self.alias_flags[self.aliases[key]] = value |
|
648 | 648 | continue |
|
649 | 649 | if len(key) is 1: |
|
650 | 650 | paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value) |
|
651 | 651 | else: |
|
652 | 652 | paa('--'+key, action='append_const', dest='_flags', const=value) |
|
653 | 653 | |
|
654 | 654 | def _convert_to_config(self): |
|
655 | 655 | """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" |
|
656 | 656 | # remove subconfigs list from namespace before transforming the Namespace |
|
657 | 657 | if '_flags' in self.parsed_data: |
|
658 | 658 | subcs = self.parsed_data._flags |
|
659 | 659 | del self.parsed_data._flags |
|
660 | 660 | else: |
|
661 | 661 | subcs = [] |
|
662 | 662 | |
|
663 | 663 | for k, v in vars(self.parsed_data).iteritems(): |
|
664 | 664 | if v is None: |
|
665 | 665 | # it was a flag that shares the name of an alias |
|
666 | 666 | subcs.append(self.alias_flags[k]) |
|
667 | 667 | else: |
|
668 | 668 | # eval the KV assignment |
|
669 | 669 | self._exec_config_str(k, v) |
|
670 | 670 | |
|
671 | 671 | for subc in subcs: |
|
672 | 672 | self._load_flag(subc) |
|
673 | 673 | |
|
674 | 674 | if self.extra_args: |
|
675 | 675 | sub_parser = KeyValueConfigLoader() |
|
676 | 676 | sub_parser.load_config(self.extra_args) |
|
677 | 677 | self.config._merge(sub_parser.config) |
|
678 | 678 | self.extra_args = sub_parser.extra_args |
|
679 | 679 | |
|
680 | 680 | |
|
681 | 681 | def load_pyconfig_files(config_files, path): |
|
682 | 682 | """Load multiple Python config files, merging each of them in turn. |
|
683 | 683 | |
|
684 | 684 | Parameters |
|
685 | 685 | ========== |
|
686 | 686 | config_files : list of str |
|
687 | 687 | List of config files names to load and merge into the config. |
|
688 | 688 | path : unicode |
|
689 | 689 | The full path to the location of the config files. |
|
690 | 690 | """ |
|
691 | 691 | config = Config() |
|
692 | 692 | for cf in config_files: |
|
693 | 693 | loader = PyFileConfigLoader(cf, path=path) |
|
694 | 694 | try: |
|
695 | 695 | next_config = loader.load_config() |
|
696 | 696 | except ConfigFileNotFound: |
|
697 | 697 | pass |
|
698 | 698 | except: |
|
699 | 699 | raise |
|
700 | 700 | else: |
|
701 | 701 | config._merge(next_config) |
|
702 | 702 | return config |
@@ -1,3813 +1,3808 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008-2011 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import __builtin__ as builtin_mod |
|
19 | 19 | import __future__ |
|
20 | 20 | import bdb |
|
21 | 21 | import inspect |
|
22 | 22 | import imp |
|
23 | 23 | import os |
|
24 | 24 | import sys |
|
25 | 25 | import shutil |
|
26 | 26 | import re |
|
27 | 27 | import time |
|
28 | 28 | import gc |
|
29 | 29 | from StringIO import StringIO |
|
30 | 30 | from getopt import getopt,GetoptError |
|
31 | 31 | from pprint import pformat |
|
32 | 32 | from xmlrpclib import ServerProxy |
|
33 | 33 | |
|
34 | 34 | # cProfile was added in Python2.5 |
|
35 | 35 | try: |
|
36 | 36 | import cProfile as profile |
|
37 | 37 | import pstats |
|
38 | 38 | except ImportError: |
|
39 | 39 | # profile isn't bundled by default in Debian for license reasons |
|
40 | 40 | try: |
|
41 | 41 | import profile,pstats |
|
42 | 42 | except ImportError: |
|
43 | 43 | profile = pstats = None |
|
44 | 44 | |
|
45 | 45 | import IPython |
|
46 | 46 | from IPython.core import debugger, oinspect |
|
47 | 47 | from IPython.core.error import TryNext |
|
48 | 48 | from IPython.core.error import UsageError |
|
49 | 49 | from IPython.core.error import StdinNotImplementedError |
|
50 | 50 | from IPython.core.fakemodule import FakeModule |
|
51 | 51 | from IPython.core.profiledir import ProfileDir |
|
52 | 52 | from IPython.core.macro import Macro |
|
53 | 53 | from IPython.core import magic_arguments, page |
|
54 | 54 | from IPython.core.prefilter import ESC_MAGIC |
|
55 | 55 | from IPython.core.pylabtools import mpl_runner |
|
56 | 56 | from IPython.testing.skipdoctest import skip_doctest |
|
57 | 57 | from IPython.utils import py3compat |
|
58 | 58 | from IPython.utils.io import file_read, nlprint |
|
59 | 59 | from IPython.utils.module_paths import find_mod |
|
60 | 60 | from IPython.utils.path import get_py_filename, unquote_filename |
|
61 | 61 | from IPython.utils.process import arg_split, abbrev_cwd |
|
62 | 62 | from IPython.utils.terminal import set_term_title |
|
63 | 63 | from IPython.utils.text import LSString, SList, format_screen |
|
64 | 64 | from IPython.utils.timing import clock, clock2 |
|
65 | 65 | from IPython.utils.warn import warn, error |
|
66 | 66 | from IPython.utils.ipstruct import Struct |
|
67 | 67 | from IPython.config.application import Application |
|
68 | 68 | |
|
69 | 69 | #----------------------------------------------------------------------------- |
|
70 | 70 | # Utility functions |
|
71 | 71 | #----------------------------------------------------------------------------- |
|
72 | 72 | |
|
73 | 73 | def on_off(tag): |
|
74 | 74 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
75 | 75 | return ['OFF','ON'][tag] |
|
76 | 76 | |
|
77 | 77 | class Bunch: pass |
|
78 | 78 | |
|
79 | 79 | def compress_dhist(dh): |
|
80 | 80 | head, tail = dh[:-10], dh[-10:] |
|
81 | 81 | |
|
82 | 82 | newhead = [] |
|
83 | 83 | done = set() |
|
84 | 84 | for h in head: |
|
85 | 85 | if h in done: |
|
86 | 86 | continue |
|
87 | 87 | newhead.append(h) |
|
88 | 88 | done.add(h) |
|
89 | 89 | |
|
90 | 90 | return newhead + tail |
|
91 | 91 | |
|
92 | 92 | def needs_local_scope(func): |
|
93 | 93 | """Decorator to mark magic functions which need to local scope to run.""" |
|
94 | 94 | func.needs_local_scope = True |
|
95 | 95 | return func |
|
96 | 96 | |
|
97 | 97 | |
|
98 | 98 | # Used for exception handling in magic_edit |
|
99 | 99 | class MacroToEdit(ValueError): pass |
|
100 | 100 | |
|
101 | 101 | # Taken from PEP 263, this is the official encoding regexp. |
|
102 | 102 | _encoding_declaration_re = re.compile(r"^#.*coding[:=]\s*([-\w.]+)") |
|
103 | 103 | |
|
104 | 104 | #*************************************************************************** |
|
105 | 105 | # Main class implementing Magic functionality |
|
106 | 106 | |
|
107 | 107 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
108 | 108 | # on construction of the main InteractiveShell object. Something odd is going |
|
109 | 109 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
110 | 110 | # eventually this needs to be clarified. |
|
111 | 111 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
112 | 112 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
113 | 113 | # make Magic a configurable that InteractiveShell does not subclass. |
|
114 | 114 | |
|
115 | 115 | class Magic: |
|
116 | 116 | """Magic functions for InteractiveShell. |
|
117 | 117 | |
|
118 | 118 | Shell functions which can be reached as %function_name. All magic |
|
119 | 119 | functions should accept a string, which they can parse for their own |
|
120 | 120 | needs. This can make some functions easier to type, eg `%cd ../` |
|
121 | 121 | vs. `%cd("../")` |
|
122 | 122 | |
|
123 | 123 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
124 | 124 | at the command line, but it is is needed in the definition. """ |
|
125 | 125 | |
|
126 | 126 | # class globals |
|
127 | 127 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
128 | 128 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
129 | 129 | |
|
130 | 130 | |
|
131 | 131 | configurables = None |
|
132 | 132 | #...................................................................... |
|
133 | 133 | # some utility functions |
|
134 | 134 | |
|
135 | 135 | def __init__(self,shell): |
|
136 | 136 | |
|
137 | 137 | self.options_table = {} |
|
138 | 138 | if profile is None: |
|
139 | 139 | self.magic_prun = self.profile_missing_notice |
|
140 | 140 | self.shell = shell |
|
141 | 141 | if self.configurables is None: |
|
142 | 142 | self.configurables = [] |
|
143 | 143 | |
|
144 | 144 | # namespace for holding state we may need |
|
145 | 145 | self._magic_state = Bunch() |
|
146 | 146 | |
|
147 | 147 | def profile_missing_notice(self, *args, **kwargs): |
|
148 | 148 | error("""\ |
|
149 | 149 | The profile module could not be found. It has been removed from the standard |
|
150 | 150 | python packages because of its non-free license. To use profiling, install the |
|
151 | 151 | python-profiler package from non-free.""") |
|
152 | 152 | |
|
153 | 153 | def default_option(self,fn,optstr): |
|
154 | 154 | """Make an entry in the options_table for fn, with value optstr""" |
|
155 | 155 | |
|
156 | 156 | if fn not in self.lsmagic(): |
|
157 | 157 | error("%s is not a magic function" % fn) |
|
158 | 158 | self.options_table[fn] = optstr |
|
159 | 159 | |
|
160 | 160 | def lsmagic(self): |
|
161 | 161 | """Return a list of currently available magic functions. |
|
162 | 162 | |
|
163 | 163 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
164 | 164 | ['magic_ls','magic_cd',...]""" |
|
165 | 165 | |
|
166 | 166 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
167 | 167 | |
|
168 | 168 | # magics in class definition |
|
169 | 169 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
170 | 170 | callable(Magic.__dict__[fn]) |
|
171 | 171 | # in instance namespace (run-time user additions) |
|
172 | 172 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
173 | 173 | callable(self.__dict__[fn]) |
|
174 | 174 | # and bound magics by user (so they can access self): |
|
175 | 175 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
176 | 176 | callable(self.__class__.__dict__[fn]) |
|
177 | 177 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
178 | 178 | filter(inst_magic,self.__dict__.keys()) + \ |
|
179 | 179 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
180 | 180 | out = [] |
|
181 | 181 | for fn in set(magics): |
|
182 | 182 | out.append(fn.replace('magic_','',1)) |
|
183 | 183 | out.sort() |
|
184 | 184 | return out |
|
185 | 185 | |
|
186 | 186 | def extract_input_lines(self, range_str, raw=False): |
|
187 | 187 | """Return as a string a set of input history slices. |
|
188 | 188 | |
|
189 | 189 | Parameters |
|
190 | 190 | ---------- |
|
191 | 191 | range_str : string |
|
192 | 192 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
193 | 193 | since this function is for use by magic functions which get their |
|
194 | 194 | arguments as strings. The number before the / is the session |
|
195 | 195 | number: ~n goes n back from the current session. |
|
196 | 196 | |
|
197 | 197 | Optional Parameters: |
|
198 | 198 | - raw(False): by default, the processed input is used. If this is |
|
199 | 199 | true, the raw input history is used instead. |
|
200 | 200 | |
|
201 | 201 | Note that slices can be called with two notations: |
|
202 | 202 | |
|
203 | 203 | N:M -> standard python form, means including items N...(M-1). |
|
204 | 204 | |
|
205 | 205 | N-M -> include items N..M (closed endpoint).""" |
|
206 | 206 | lines = self.shell.history_manager.\ |
|
207 | 207 | get_range_by_str(range_str, raw=raw) |
|
208 | 208 | return "\n".join(x for _, _, x in lines) |
|
209 | 209 | |
|
210 | 210 | def arg_err(self,func): |
|
211 | 211 | """Print docstring if incorrect arguments were passed""" |
|
212 | 212 | print 'Error in arguments:' |
|
213 | 213 | print oinspect.getdoc(func) |
|
214 | 214 | |
|
215 | 215 | def format_latex(self,strng): |
|
216 | 216 | """Format a string for latex inclusion.""" |
|
217 | 217 | |
|
218 | 218 | # Characters that need to be escaped for latex: |
|
219 | 219 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
220 | 220 | # Magic command names as headers: |
|
221 | 221 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
222 | 222 | re.MULTILINE) |
|
223 | 223 | # Magic commands |
|
224 | 224 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
225 | 225 | re.MULTILINE) |
|
226 | 226 | # Paragraph continue |
|
227 | 227 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
228 | 228 | |
|
229 | 229 | # The "\n" symbol |
|
230 | 230 | newline_re = re.compile(r'\\n') |
|
231 | 231 | |
|
232 | 232 | # Now build the string for output: |
|
233 | 233 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
234 | 234 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
235 | 235 | strng) |
|
236 | 236 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
237 | 237 | strng = par_re.sub(r'\\\\',strng) |
|
238 | 238 | strng = escape_re.sub(r'\\\1',strng) |
|
239 | 239 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
240 | 240 | return strng |
|
241 | 241 | |
|
242 | 242 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
243 | 243 | """Parse options passed to an argument string. |
|
244 | 244 | |
|
245 | 245 | The interface is similar to that of getopt(), but it returns back a |
|
246 | 246 | Struct with the options as keys and the stripped argument string still |
|
247 | 247 | as a string. |
|
248 | 248 | |
|
249 | 249 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
250 | 250 | This allows us to easily expand variables, glob files, quote |
|
251 | 251 | arguments, etc. |
|
252 | 252 | |
|
253 | 253 | Options: |
|
254 | 254 | -mode: default 'string'. If given as 'list', the argument string is |
|
255 | 255 | returned as a list (split on whitespace) instead of a string. |
|
256 | 256 | |
|
257 | 257 | -list_all: put all option values in lists. Normally only options |
|
258 | 258 | appearing more than once are put in a list. |
|
259 | 259 | |
|
260 | 260 | -posix (True): whether to split the input line in POSIX mode or not, |
|
261 | 261 | as per the conventions outlined in the shlex module from the |
|
262 | 262 | standard library.""" |
|
263 | 263 | |
|
264 | 264 | # inject default options at the beginning of the input line |
|
265 | 265 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
266 | 266 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
267 | 267 | |
|
268 | 268 | mode = kw.get('mode','string') |
|
269 | 269 | if mode not in ['string','list']: |
|
270 | 270 | raise ValueError,'incorrect mode given: %s' % mode |
|
271 | 271 | # Get options |
|
272 | 272 | list_all = kw.get('list_all',0) |
|
273 | 273 | posix = kw.get('posix', os.name == 'posix') |
|
274 | 274 | strict = kw.get('strict', True) |
|
275 | 275 | |
|
276 | 276 | # Check if we have more than one argument to warrant extra processing: |
|
277 | 277 | odict = {} # Dictionary with options |
|
278 | 278 | args = arg_str.split() |
|
279 | 279 | if len(args) >= 1: |
|
280 | 280 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
281 | 281 | # need to look for options |
|
282 | 282 | argv = arg_split(arg_str, posix, strict) |
|
283 | 283 | # Do regular option processing |
|
284 | 284 | try: |
|
285 | 285 | opts,args = getopt(argv,opt_str,*long_opts) |
|
286 | 286 | except GetoptError,e: |
|
287 | 287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
288 | 288 | " ".join(long_opts))) |
|
289 | 289 | for o,a in opts: |
|
290 | 290 | if o.startswith('--'): |
|
291 | 291 | o = o[2:] |
|
292 | 292 | else: |
|
293 | 293 | o = o[1:] |
|
294 | 294 | try: |
|
295 | 295 | odict[o].append(a) |
|
296 | 296 | except AttributeError: |
|
297 | 297 | odict[o] = [odict[o],a] |
|
298 | 298 | except KeyError: |
|
299 | 299 | if list_all: |
|
300 | 300 | odict[o] = [a] |
|
301 | 301 | else: |
|
302 | 302 | odict[o] = a |
|
303 | 303 | |
|
304 | 304 | # Prepare opts,args for return |
|
305 | 305 | opts = Struct(odict) |
|
306 | 306 | if mode == 'string': |
|
307 | 307 | args = ' '.join(args) |
|
308 | 308 | |
|
309 | 309 | return opts,args |
|
310 | 310 | |
|
311 | 311 | #...................................................................... |
|
312 | 312 | # And now the actual magic functions |
|
313 | 313 | |
|
314 | 314 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
315 | 315 | def magic_lsmagic(self, parameter_s = ''): |
|
316 | 316 | """List currently available magic functions.""" |
|
317 | 317 | mesc = ESC_MAGIC |
|
318 | 318 | print 'Available magic functions:\n'+mesc+\ |
|
319 | 319 | (' '+mesc).join(self.lsmagic()) |
|
320 | 320 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
321 | 321 | return None |
|
322 | 322 | |
|
323 | 323 | def magic_magic(self, parameter_s = ''): |
|
324 | 324 | """Print information about the magic function system. |
|
325 | 325 | |
|
326 | 326 | Supported formats: -latex, -brief, -rest |
|
327 | 327 | """ |
|
328 | 328 | |
|
329 | 329 | mode = '' |
|
330 | 330 | try: |
|
331 | 331 | if parameter_s.split()[0] == '-latex': |
|
332 | 332 | mode = 'latex' |
|
333 | 333 | if parameter_s.split()[0] == '-brief': |
|
334 | 334 | mode = 'brief' |
|
335 | 335 | if parameter_s.split()[0] == '-rest': |
|
336 | 336 | mode = 'rest' |
|
337 | 337 | rest_docs = [] |
|
338 | 338 | except: |
|
339 | 339 | pass |
|
340 | 340 | |
|
341 | 341 | magic_docs = [] |
|
342 | 342 | for fname in self.lsmagic(): |
|
343 | 343 | mname = 'magic_' + fname |
|
344 | 344 | for space in (Magic,self,self.__class__): |
|
345 | 345 | try: |
|
346 | 346 | fn = space.__dict__[mname] |
|
347 | 347 | except KeyError: |
|
348 | 348 | pass |
|
349 | 349 | else: |
|
350 | 350 | break |
|
351 | 351 | if mode == 'brief': |
|
352 | 352 | # only first line |
|
353 | 353 | if fn.__doc__: |
|
354 | 354 | fndoc = fn.__doc__.split('\n',1)[0] |
|
355 | 355 | else: |
|
356 | 356 | fndoc = 'No documentation' |
|
357 | 357 | else: |
|
358 | 358 | if fn.__doc__: |
|
359 | 359 | fndoc = fn.__doc__.rstrip() |
|
360 | 360 | else: |
|
361 | 361 | fndoc = 'No documentation' |
|
362 | 362 | |
|
363 | 363 | |
|
364 | 364 | if mode == 'rest': |
|
365 | 365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
366 | 366 | fname,fndoc)) |
|
367 | 367 | |
|
368 | 368 | else: |
|
369 | 369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
370 | 370 | fname,fndoc)) |
|
371 | 371 | |
|
372 | 372 | magic_docs = ''.join(magic_docs) |
|
373 | 373 | |
|
374 | 374 | if mode == 'rest': |
|
375 | 375 | return "".join(rest_docs) |
|
376 | 376 | |
|
377 | 377 | if mode == 'latex': |
|
378 | 378 | print self.format_latex(magic_docs) |
|
379 | 379 | return |
|
380 | 380 | else: |
|
381 | 381 | magic_docs = format_screen(magic_docs) |
|
382 | 382 | if mode == 'brief': |
|
383 | 383 | return magic_docs |
|
384 | 384 | |
|
385 | 385 | outmsg = """ |
|
386 | 386 | IPython's 'magic' functions |
|
387 | 387 | =========================== |
|
388 | 388 | |
|
389 | 389 | The magic function system provides a series of functions which allow you to |
|
390 | 390 | control the behavior of IPython itself, plus a lot of system-type |
|
391 | 391 | features. All these functions are prefixed with a % character, but parameters |
|
392 | 392 | are given without parentheses or quotes. |
|
393 | 393 | |
|
394 | 394 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
395 | 395 | %automagic function), you don't need to type in the % explicitly. By default, |
|
396 | 396 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
397 | 397 | |
|
398 | 398 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
399 | 399 | to 'mydir', if it exists. |
|
400 | 400 | |
|
401 | 401 | For a list of the available magic functions, use %lsmagic. For a description |
|
402 | 402 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
403 | 403 | |
|
404 | 404 | Currently the magic system has the following functions:\n""" |
|
405 | 405 | |
|
406 | 406 | mesc = ESC_MAGIC |
|
407 | 407 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
408 | 408 | "\n\n%s%s\n\n%s" % (outmsg, |
|
409 | 409 | magic_docs,mesc,mesc, |
|
410 | 410 | (' '+mesc).join(self.lsmagic()), |
|
411 | 411 | Magic.auto_status[self.shell.automagic] ) ) |
|
412 | 412 | page.page(outmsg) |
|
413 | 413 | |
|
414 | 414 | def magic_automagic(self, parameter_s = ''): |
|
415 | 415 | """Make magic functions callable without having to type the initial %. |
|
416 | 416 | |
|
417 | 417 | Without argumentsl toggles on/off (when off, you must call it as |
|
418 | 418 | %automagic, of course). With arguments it sets the value, and you can |
|
419 | 419 | use any of (case insensitive): |
|
420 | 420 | |
|
421 | 421 | - on,1,True: to activate |
|
422 | 422 | |
|
423 | 423 | - off,0,False: to deactivate. |
|
424 | 424 | |
|
425 | 425 | Note that magic functions have lowest priority, so if there's a |
|
426 | 426 | variable whose name collides with that of a magic fn, automagic won't |
|
427 | 427 | work for that function (you get the variable instead). However, if you |
|
428 | 428 | delete the variable (del var), the previously shadowed magic function |
|
429 | 429 | becomes visible to automagic again.""" |
|
430 | 430 | |
|
431 | 431 | arg = parameter_s.lower() |
|
432 | 432 | if parameter_s in ('on','1','true'): |
|
433 | 433 | self.shell.automagic = True |
|
434 | 434 | elif parameter_s in ('off','0','false'): |
|
435 | 435 | self.shell.automagic = False |
|
436 | 436 | else: |
|
437 | 437 | self.shell.automagic = not self.shell.automagic |
|
438 | 438 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
439 | 439 | |
|
440 | 440 | @skip_doctest |
|
441 | 441 | def magic_autocall(self, parameter_s = ''): |
|
442 | 442 | """Make functions callable without having to type parentheses. |
|
443 | 443 | |
|
444 | 444 | Usage: |
|
445 | 445 | |
|
446 | 446 | %autocall [mode] |
|
447 | 447 | |
|
448 | 448 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
449 | 449 | value is toggled on and off (remembering the previous state). |
|
450 | 450 | |
|
451 | 451 | In more detail, these values mean: |
|
452 | 452 | |
|
453 | 453 | 0 -> fully disabled |
|
454 | 454 | |
|
455 | 455 | 1 -> active, but do not apply if there are no arguments on the line. |
|
456 | 456 | |
|
457 | 457 | In this mode, you get:: |
|
458 | 458 | |
|
459 | 459 | In [1]: callable |
|
460 | 460 | Out[1]: <built-in function callable> |
|
461 | 461 | |
|
462 | 462 | In [2]: callable 'hello' |
|
463 | 463 | ------> callable('hello') |
|
464 | 464 | Out[2]: False |
|
465 | 465 | |
|
466 | 466 | 2 -> Active always. Even if no arguments are present, the callable |
|
467 | 467 | object is called:: |
|
468 | 468 | |
|
469 | 469 | In [2]: float |
|
470 | 470 | ------> float() |
|
471 | 471 | Out[2]: 0.0 |
|
472 | 472 | |
|
473 | 473 | Note that even with autocall off, you can still use '/' at the start of |
|
474 | 474 | a line to treat the first argument on the command line as a function |
|
475 | 475 | and add parentheses to it:: |
|
476 | 476 | |
|
477 | 477 | In [8]: /str 43 |
|
478 | 478 | ------> str(43) |
|
479 | 479 | Out[8]: '43' |
|
480 | 480 | |
|
481 | 481 | # all-random (note for auto-testing) |
|
482 | 482 | """ |
|
483 | 483 | |
|
484 | 484 | if parameter_s: |
|
485 | 485 | arg = int(parameter_s) |
|
486 | 486 | else: |
|
487 | 487 | arg = 'toggle' |
|
488 | 488 | |
|
489 | 489 | if not arg in (0,1,2,'toggle'): |
|
490 | 490 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
491 | 491 | return |
|
492 | 492 | |
|
493 | 493 | if arg in (0,1,2): |
|
494 | 494 | self.shell.autocall = arg |
|
495 | 495 | else: # toggle |
|
496 | 496 | if self.shell.autocall: |
|
497 | 497 | self._magic_state.autocall_save = self.shell.autocall |
|
498 | 498 | self.shell.autocall = 0 |
|
499 | 499 | else: |
|
500 | 500 | try: |
|
501 | 501 | self.shell.autocall = self._magic_state.autocall_save |
|
502 | 502 | except AttributeError: |
|
503 | 503 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
504 | 504 | |
|
505 | 505 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
506 | 506 | |
|
507 | 507 | |
|
508 | 508 | def magic_page(self, parameter_s=''): |
|
509 | 509 | """Pretty print the object and display it through a pager. |
|
510 | 510 | |
|
511 | 511 | %page [options] OBJECT |
|
512 | 512 | |
|
513 | 513 | If no object is given, use _ (last output). |
|
514 | 514 | |
|
515 | 515 | Options: |
|
516 | 516 | |
|
517 | 517 | -r: page str(object), don't pretty-print it.""" |
|
518 | 518 | |
|
519 | 519 | # After a function contributed by Olivier Aubert, slightly modified. |
|
520 | 520 | |
|
521 | 521 | # Process options/args |
|
522 | 522 | opts,args = self.parse_options(parameter_s,'r') |
|
523 | 523 | raw = 'r' in opts |
|
524 | 524 | |
|
525 | 525 | oname = args and args or '_' |
|
526 | 526 | info = self._ofind(oname) |
|
527 | 527 | if info['found']: |
|
528 | 528 | txt = (raw and str or pformat)( info['obj'] ) |
|
529 | 529 | page.page(txt) |
|
530 | 530 | else: |
|
531 | 531 | print 'Object `%s` not found' % oname |
|
532 | 532 | |
|
533 | 533 | def magic_profile(self, parameter_s=''): |
|
534 | 534 | """Print your currently active IPython profile.""" |
|
535 | 535 | from IPython.core.application import BaseIPythonApplication |
|
536 | 536 | if BaseIPythonApplication.initialized(): |
|
537 | 537 | print BaseIPythonApplication.instance().profile |
|
538 | 538 | else: |
|
539 | 539 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
540 | 540 | |
|
541 | 541 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
542 | 542 | """Provide detailed information about an object. |
|
543 | 543 | |
|
544 | 544 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
545 | 545 | |
|
546 | 546 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
547 | 547 | |
|
548 | 548 | |
|
549 | 549 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
550 | 550 | detail_level = 0 |
|
551 | 551 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
552 | 552 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
553 | 553 | pinfo,qmark1,oname,qmark2 = \ |
|
554 | 554 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
555 | 555 | if pinfo or qmark1 or qmark2: |
|
556 | 556 | detail_level = 1 |
|
557 | 557 | if "*" in oname: |
|
558 | 558 | self.magic_psearch(oname) |
|
559 | 559 | else: |
|
560 | 560 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
561 | 561 | namespaces=namespaces) |
|
562 | 562 | |
|
563 | 563 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
564 | 564 | """Provide extra detailed information about an object. |
|
565 | 565 | |
|
566 | 566 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
567 | 567 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
568 | 568 | namespaces=namespaces) |
|
569 | 569 | |
|
570 | 570 | @skip_doctest |
|
571 | 571 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
572 | 572 | """Print the definition header for any callable object. |
|
573 | 573 | |
|
574 | 574 | If the object is a class, print the constructor information. |
|
575 | 575 | |
|
576 | 576 | Examples |
|
577 | 577 | -------- |
|
578 | 578 | :: |
|
579 | 579 | |
|
580 | 580 | In [3]: %pdef urllib.urlopen |
|
581 | 581 | urllib.urlopen(url, data=None, proxies=None) |
|
582 | 582 | """ |
|
583 | 583 | self._inspect('pdef',parameter_s, namespaces) |
|
584 | 584 | |
|
585 | 585 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
586 | 586 | """Print the docstring for an object. |
|
587 | 587 | |
|
588 | 588 | If the given object is a class, it will print both the class and the |
|
589 | 589 | constructor docstrings.""" |
|
590 | 590 | self._inspect('pdoc',parameter_s, namespaces) |
|
591 | 591 | |
|
592 | 592 | def magic_psource(self, parameter_s='', namespaces=None): |
|
593 | 593 | """Print (or run through pager) the source code for an object.""" |
|
594 | 594 | self._inspect('psource',parameter_s, namespaces) |
|
595 | 595 | |
|
596 | 596 | def magic_pfile(self, parameter_s=''): |
|
597 | 597 | """Print (or run through pager) the file where an object is defined. |
|
598 | 598 | |
|
599 | 599 | The file opens at the line where the object definition begins. IPython |
|
600 | 600 | will honor the environment variable PAGER if set, and otherwise will |
|
601 | 601 | do its best to print the file in a convenient form. |
|
602 | 602 | |
|
603 | 603 | If the given argument is not an object currently defined, IPython will |
|
604 | 604 | try to interpret it as a filename (automatically adding a .py extension |
|
605 | 605 | if needed). You can thus use %pfile as a syntax highlighting code |
|
606 | 606 | viewer.""" |
|
607 | 607 | |
|
608 | 608 | # first interpret argument as an object name |
|
609 | 609 | out = self._inspect('pfile',parameter_s) |
|
610 | 610 | # if not, try the input as a filename |
|
611 | 611 | if out == 'not found': |
|
612 | 612 | try: |
|
613 | 613 | filename = get_py_filename(parameter_s) |
|
614 | 614 | except IOError,msg: |
|
615 | 615 | print msg |
|
616 | 616 | return |
|
617 | 617 | page.page(self.shell.inspector.format(file(filename).read())) |
|
618 | 618 | |
|
619 | 619 | def magic_psearch(self, parameter_s=''): |
|
620 | 620 | """Search for object in namespaces by wildcard. |
|
621 | 621 | |
|
622 | 622 | %psearch [options] PATTERN [OBJECT TYPE] |
|
623 | 623 | |
|
624 | 624 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
625 | 625 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
626 | 626 | rest of the command line must be unchanged (options come first), so |
|
627 | 627 | for example the following forms are equivalent |
|
628 | 628 | |
|
629 | 629 | %psearch -i a* function |
|
630 | 630 | -i a* function? |
|
631 | 631 | ?-i a* function |
|
632 | 632 | |
|
633 | 633 | Arguments: |
|
634 | 634 | |
|
635 | 635 | PATTERN |
|
636 | 636 | |
|
637 | 637 | where PATTERN is a string containing * as a wildcard similar to its |
|
638 | 638 | use in a shell. The pattern is matched in all namespaces on the |
|
639 | 639 | search path. By default objects starting with a single _ are not |
|
640 | 640 | matched, many IPython generated objects have a single |
|
641 | 641 | underscore. The default is case insensitive matching. Matching is |
|
642 | 642 | also done on the attributes of objects and not only on the objects |
|
643 | 643 | in a module. |
|
644 | 644 | |
|
645 | 645 | [OBJECT TYPE] |
|
646 | 646 | |
|
647 | 647 | Is the name of a python type from the types module. The name is |
|
648 | 648 | given in lowercase without the ending type, ex. StringType is |
|
649 | 649 | written string. By adding a type here only objects matching the |
|
650 | 650 | given type are matched. Using all here makes the pattern match all |
|
651 | 651 | types (this is the default). |
|
652 | 652 | |
|
653 | 653 | Options: |
|
654 | 654 | |
|
655 | 655 | -a: makes the pattern match even objects whose names start with a |
|
656 | 656 | single underscore. These names are normally omitted from the |
|
657 | 657 | search. |
|
658 | 658 | |
|
659 | 659 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
660 | 660 | these options are given, the default is read from your configuration |
|
661 | 661 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
662 | 662 | If this option is not specified in your configuration file, IPython's |
|
663 | 663 | internal default is to do a case sensitive search. |
|
664 | 664 | |
|
665 | 665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
666 | 666 | specify can be searched in any of the following namespaces: |
|
667 | 667 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
668 | 668 | 'builtin' and 'user' are the search defaults. Note that you should |
|
669 | 669 | not use quotes when specifying namespaces. |
|
670 | 670 | |
|
671 | 671 | 'Builtin' contains the python module builtin, 'user' contains all |
|
672 | 672 | user data, 'alias' only contain the shell aliases and no python |
|
673 | 673 | objects, 'internal' contains objects used by IPython. The |
|
674 | 674 | 'user_global' namespace is only used by embedded IPython instances, |
|
675 | 675 | and it contains module-level globals. You can add namespaces to the |
|
676 | 676 | search with -s or exclude them with -e (these options can be given |
|
677 | 677 | more than once). |
|
678 | 678 | |
|
679 | 679 | Examples |
|
680 | 680 | -------- |
|
681 | 681 | :: |
|
682 | 682 | |
|
683 | 683 | %psearch a* -> objects beginning with an a |
|
684 | 684 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
685 | 685 | %psearch a* function -> all functions beginning with an a |
|
686 | 686 | %psearch re.e* -> objects beginning with an e in module re |
|
687 | 687 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
688 | 688 | %psearch r*.* string -> all strings in modules beginning with r |
|
689 | 689 | |
|
690 | 690 | Case sensitive search:: |
|
691 | 691 | |
|
692 | 692 | %psearch -c a* list all object beginning with lower case a |
|
693 | 693 | |
|
694 | 694 | Show objects beginning with a single _:: |
|
695 | 695 | |
|
696 | 696 | %psearch -a _* list objects beginning with a single underscore""" |
|
697 | 697 | try: |
|
698 | 698 | parameter_s.encode('ascii') |
|
699 | 699 | except UnicodeEncodeError: |
|
700 | 700 | print 'Python identifiers can only contain ascii characters.' |
|
701 | 701 | return |
|
702 | 702 | |
|
703 | 703 | # default namespaces to be searched |
|
704 | 704 | def_search = ['user_local', 'user_global', 'builtin'] |
|
705 | 705 | |
|
706 | 706 | # Process options/args |
|
707 | 707 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
708 | 708 | opt = opts.get |
|
709 | 709 | shell = self.shell |
|
710 | 710 | psearch = shell.inspector.psearch |
|
711 | 711 | |
|
712 | 712 | # select case options |
|
713 | 713 | if opts.has_key('i'): |
|
714 | 714 | ignore_case = True |
|
715 | 715 | elif opts.has_key('c'): |
|
716 | 716 | ignore_case = False |
|
717 | 717 | else: |
|
718 | 718 | ignore_case = not shell.wildcards_case_sensitive |
|
719 | 719 | |
|
720 | 720 | # Build list of namespaces to search from user options |
|
721 | 721 | def_search.extend(opt('s',[])) |
|
722 | 722 | ns_exclude = ns_exclude=opt('e',[]) |
|
723 | 723 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
724 | 724 | |
|
725 | 725 | # Call the actual search |
|
726 | 726 | try: |
|
727 | 727 | psearch(args,shell.ns_table,ns_search, |
|
728 | 728 | show_all=opt('a'),ignore_case=ignore_case) |
|
729 | 729 | except: |
|
730 | 730 | shell.showtraceback() |
|
731 | 731 | |
|
732 | 732 | @skip_doctest |
|
733 | 733 | def magic_who_ls(self, parameter_s=''): |
|
734 | 734 | """Return a sorted list of all interactive variables. |
|
735 | 735 | |
|
736 | 736 | If arguments are given, only variables of types matching these |
|
737 | 737 | arguments are returned. |
|
738 | 738 | |
|
739 | 739 | Examples |
|
740 | 740 | -------- |
|
741 | 741 | |
|
742 | 742 | Define two variables and list them with who_ls:: |
|
743 | 743 | |
|
744 | 744 | In [1]: alpha = 123 |
|
745 | 745 | |
|
746 | 746 | In [2]: beta = 'test' |
|
747 | 747 | |
|
748 | 748 | In [3]: %who_ls |
|
749 | 749 | Out[3]: ['alpha', 'beta'] |
|
750 | 750 | |
|
751 | 751 | In [4]: %who_ls int |
|
752 | 752 | Out[4]: ['alpha'] |
|
753 | 753 | |
|
754 | 754 | In [5]: %who_ls str |
|
755 | 755 | Out[5]: ['beta'] |
|
756 | 756 | """ |
|
757 | 757 | |
|
758 | 758 | user_ns = self.shell.user_ns |
|
759 | 759 | user_ns_hidden = self.shell.user_ns_hidden |
|
760 | 760 | out = [ i for i in user_ns |
|
761 | 761 | if not i.startswith('_') \ |
|
762 | 762 | and not i in user_ns_hidden ] |
|
763 | 763 | |
|
764 | 764 | typelist = parameter_s.split() |
|
765 | 765 | if typelist: |
|
766 | 766 | typeset = set(typelist) |
|
767 | 767 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
768 | 768 | |
|
769 | 769 | out.sort() |
|
770 | 770 | return out |
|
771 | 771 | |
|
772 | 772 | @skip_doctest |
|
773 | 773 | def magic_who(self, parameter_s=''): |
|
774 | 774 | """Print all interactive variables, with some minimal formatting. |
|
775 | 775 | |
|
776 | 776 | If any arguments are given, only variables whose type matches one of |
|
777 | 777 | these are printed. For example:: |
|
778 | 778 | |
|
779 | 779 | %who function str |
|
780 | 780 | |
|
781 | 781 | will only list functions and strings, excluding all other types of |
|
782 | 782 | variables. To find the proper type names, simply use type(var) at a |
|
783 | 783 | command line to see how python prints type names. For example: |
|
784 | 784 | |
|
785 | 785 | :: |
|
786 | 786 | |
|
787 | 787 | In [1]: type('hello')\\ |
|
788 | 788 | Out[1]: <type 'str'> |
|
789 | 789 | |
|
790 | 790 | indicates that the type name for strings is 'str'. |
|
791 | 791 | |
|
792 | 792 | ``%who`` always excludes executed names loaded through your configuration |
|
793 | 793 | file and things which are internal to IPython. |
|
794 | 794 | |
|
795 | 795 | This is deliberate, as typically you may load many modules and the |
|
796 | 796 | purpose of %who is to show you only what you've manually defined. |
|
797 | 797 | |
|
798 | 798 | Examples |
|
799 | 799 | -------- |
|
800 | 800 | |
|
801 | 801 | Define two variables and list them with who:: |
|
802 | 802 | |
|
803 | 803 | In [1]: alpha = 123 |
|
804 | 804 | |
|
805 | 805 | In [2]: beta = 'test' |
|
806 | 806 | |
|
807 | 807 | In [3]: %who |
|
808 | 808 | alpha beta |
|
809 | 809 | |
|
810 | 810 | In [4]: %who int |
|
811 | 811 | alpha |
|
812 | 812 | |
|
813 | 813 | In [5]: %who str |
|
814 | 814 | beta |
|
815 | 815 | """ |
|
816 | 816 | |
|
817 | 817 | varlist = self.magic_who_ls(parameter_s) |
|
818 | 818 | if not varlist: |
|
819 | 819 | if parameter_s: |
|
820 | 820 | print 'No variables match your requested type.' |
|
821 | 821 | else: |
|
822 | 822 | print 'Interactive namespace is empty.' |
|
823 | 823 | return |
|
824 | 824 | |
|
825 | 825 | # if we have variables, move on... |
|
826 | 826 | count = 0 |
|
827 | 827 | for i in varlist: |
|
828 | 828 | print i+'\t', |
|
829 | 829 | count += 1 |
|
830 | 830 | if count > 8: |
|
831 | 831 | count = 0 |
|
832 | 832 | |
|
833 | 833 | |
|
834 | 834 | |
|
835 | 835 | @skip_doctest |
|
836 | 836 | def magic_whos(self, parameter_s=''): |
|
837 | 837 | """Like %who, but gives some extra information about each variable. |
|
838 | 838 | |
|
839 | 839 | The same type filtering of %who can be applied here. |
|
840 | 840 | |
|
841 | 841 | For all variables, the type is printed. Additionally it prints: |
|
842 | 842 | |
|
843 | 843 | - For {},[],(): their length. |
|
844 | 844 | |
|
845 | 845 | - For numpy arrays, a summary with shape, number of |
|
846 | 846 | elements, typecode and size in memory. |
|
847 | 847 | |
|
848 | 848 | - Everything else: a string representation, snipping their middle if |
|
849 | 849 | too long. |
|
850 | 850 | |
|
851 | 851 | Examples |
|
852 | 852 | -------- |
|
853 | 853 | |
|
854 | 854 | Define two variables and list them with whos:: |
|
855 | 855 | |
|
856 | 856 | In [1]: alpha = 123 |
|
857 | 857 | |
|
858 | 858 | In [2]: beta = 'test' |
|
859 | 859 | |
|
860 | 860 | In [3]: %whos |
|
861 | 861 | Variable Type Data/Info |
|
862 | 862 | -------------------------------- |
|
863 | 863 | alpha int 123 |
|
864 | 864 | beta str test |
|
865 | 865 | """ |
|
866 | 866 | |
|
867 | 867 | varnames = self.magic_who_ls(parameter_s) |
|
868 | 868 | if not varnames: |
|
869 | 869 | if parameter_s: |
|
870 | 870 | print 'No variables match your requested type.' |
|
871 | 871 | else: |
|
872 | 872 | print 'Interactive namespace is empty.' |
|
873 | 873 | return |
|
874 | 874 | |
|
875 | 875 | # if we have variables, move on... |
|
876 | 876 | |
|
877 | 877 | # for these types, show len() instead of data: |
|
878 | 878 | seq_types = ['dict', 'list', 'tuple'] |
|
879 | 879 | |
|
880 | 880 | # for numpy arrays, display summary info |
|
881 | 881 | ndarray_type = None |
|
882 | 882 | if 'numpy' in sys.modules: |
|
883 | 883 | try: |
|
884 | 884 | from numpy import ndarray |
|
885 | 885 | except ImportError: |
|
886 | 886 | pass |
|
887 | 887 | else: |
|
888 | 888 | ndarray_type = ndarray.__name__ |
|
889 | 889 | |
|
890 | 890 | # Find all variable names and types so we can figure out column sizes |
|
891 | 891 | def get_vars(i): |
|
892 | 892 | return self.shell.user_ns[i] |
|
893 | 893 | |
|
894 | 894 | # some types are well known and can be shorter |
|
895 | 895 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
896 | 896 | def type_name(v): |
|
897 | 897 | tn = type(v).__name__ |
|
898 | 898 | return abbrevs.get(tn,tn) |
|
899 | 899 | |
|
900 | 900 | varlist = map(get_vars,varnames) |
|
901 | 901 | |
|
902 | 902 | typelist = [] |
|
903 | 903 | for vv in varlist: |
|
904 | 904 | tt = type_name(vv) |
|
905 | 905 | |
|
906 | 906 | if tt=='instance': |
|
907 | 907 | typelist.append( abbrevs.get(str(vv.__class__), |
|
908 | 908 | str(vv.__class__))) |
|
909 | 909 | else: |
|
910 | 910 | typelist.append(tt) |
|
911 | 911 | |
|
912 | 912 | # column labels and # of spaces as separator |
|
913 | 913 | varlabel = 'Variable' |
|
914 | 914 | typelabel = 'Type' |
|
915 | 915 | datalabel = 'Data/Info' |
|
916 | 916 | colsep = 3 |
|
917 | 917 | # variable format strings |
|
918 | 918 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
919 | 919 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
920 | 920 | # find the size of the columns to format the output nicely |
|
921 | 921 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
922 | 922 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
923 | 923 | # table header |
|
924 | 924 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
925 | 925 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
926 | 926 | # and the table itself |
|
927 | 927 | kb = 1024 |
|
928 | 928 | Mb = 1048576 # kb**2 |
|
929 | 929 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
930 | 930 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
931 | 931 | if vtype in seq_types: |
|
932 | 932 | print "n="+str(len(var)) |
|
933 | 933 | elif vtype == ndarray_type: |
|
934 | 934 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
935 | 935 | if vtype==ndarray_type: |
|
936 | 936 | # numpy |
|
937 | 937 | vsize = var.size |
|
938 | 938 | vbytes = vsize*var.itemsize |
|
939 | 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 | 941 | if vbytes < 100000: |
|
947 | 942 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
948 | 943 | else: |
|
949 | 944 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
950 | 945 | if vbytes < Mb: |
|
951 | 946 | print '(%s kb)' % (vbytes/kb,) |
|
952 | 947 | else: |
|
953 | 948 | print '(%s Mb)' % (vbytes/Mb,) |
|
954 | 949 | else: |
|
955 | 950 | try: |
|
956 | 951 | vstr = str(var) |
|
957 | 952 | except UnicodeEncodeError: |
|
958 | 953 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
959 | 954 | 'backslashreplace') |
|
960 | 955 | vstr = vstr.replace('\n','\\n') |
|
961 | 956 | if len(vstr) < 50: |
|
962 | 957 | print vstr |
|
963 | 958 | else: |
|
964 | 959 | print vstr[:25] + "<...>" + vstr[-25:] |
|
965 | 960 | |
|
966 | 961 | def magic_reset(self, parameter_s=''): |
|
967 | 962 | """Resets the namespace by removing all names defined by the user, if |
|
968 | 963 | called without arguments, or by removing some types of objects, such |
|
969 | 964 | as everything currently in IPython's In[] and Out[] containers (see |
|
970 | 965 | the parameters for details). |
|
971 | 966 | |
|
972 | 967 | Parameters |
|
973 | 968 | ---------- |
|
974 | 969 | -f : force reset without asking for confirmation. |
|
975 | 970 | |
|
976 | 971 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
977 | 972 | References to objects may be kept. By default (without this option), |
|
978 | 973 | we do a 'hard' reset, giving you a new session and removing all |
|
979 | 974 | references to objects from the current session. |
|
980 | 975 | |
|
981 | 976 | in : reset input history |
|
982 | 977 | |
|
983 | 978 | out : reset output history |
|
984 | 979 | |
|
985 | 980 | dhist : reset directory history |
|
986 | 981 | |
|
987 | 982 | array : reset only variables that are NumPy arrays |
|
988 | 983 | |
|
989 | 984 | See Also |
|
990 | 985 | -------- |
|
991 | 986 | magic_reset_selective : invoked as ``%reset_selective`` |
|
992 | 987 | |
|
993 | 988 | Examples |
|
994 | 989 | -------- |
|
995 | 990 | :: |
|
996 | 991 | |
|
997 | 992 | In [6]: a = 1 |
|
998 | 993 | |
|
999 | 994 | In [7]: a |
|
1000 | 995 | Out[7]: 1 |
|
1001 | 996 | |
|
1002 | 997 | In [8]: 'a' in _ip.user_ns |
|
1003 | 998 | Out[8]: True |
|
1004 | 999 | |
|
1005 | 1000 | In [9]: %reset -f |
|
1006 | 1001 | |
|
1007 | 1002 | In [1]: 'a' in _ip.user_ns |
|
1008 | 1003 | Out[1]: False |
|
1009 | 1004 | |
|
1010 | 1005 | In [2]: %reset -f in |
|
1011 | 1006 | Flushing input history |
|
1012 | 1007 | |
|
1013 | 1008 | In [3]: %reset -f dhist in |
|
1014 | 1009 | Flushing directory history |
|
1015 | 1010 | Flushing input history |
|
1016 | 1011 | |
|
1017 | 1012 | Notes |
|
1018 | 1013 | ----- |
|
1019 | 1014 | Calling this magic from clients that do not implement standard input, |
|
1020 | 1015 | such as the ipython notebook interface, will reset the namespace |
|
1021 | 1016 | without confirmation. |
|
1022 | 1017 | """ |
|
1023 | 1018 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
1024 | 1019 | if 'f' in opts: |
|
1025 | 1020 | ans = True |
|
1026 | 1021 | else: |
|
1027 | 1022 | try: |
|
1028 | 1023 | ans = self.shell.ask_yes_no( |
|
1029 | 1024 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') |
|
1030 | 1025 | except StdinNotImplementedError: |
|
1031 | 1026 | ans = True |
|
1032 | 1027 | if not ans: |
|
1033 | 1028 | print 'Nothing done.' |
|
1034 | 1029 | return |
|
1035 | 1030 | |
|
1036 | 1031 | if 's' in opts: # Soft reset |
|
1037 | 1032 | user_ns = self.shell.user_ns |
|
1038 | 1033 | for i in self.magic_who_ls(): |
|
1039 | 1034 | del(user_ns[i]) |
|
1040 | 1035 | elif len(args) == 0: # Hard reset |
|
1041 | 1036 | self.shell.reset(new_session = False) |
|
1042 | 1037 | |
|
1043 | 1038 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
1044 | 1039 | ip = self.shell |
|
1045 | 1040 | user_ns = self.user_ns # local lookup, heavily used |
|
1046 | 1041 | |
|
1047 | 1042 | for target in args: |
|
1048 | 1043 | target = target.lower() # make matches case insensitive |
|
1049 | 1044 | if target == 'out': |
|
1050 | 1045 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
1051 | 1046 | self.displayhook.flush() |
|
1052 | 1047 | |
|
1053 | 1048 | elif target == 'in': |
|
1054 | 1049 | print "Flushing input history" |
|
1055 | 1050 | pc = self.displayhook.prompt_count + 1 |
|
1056 | 1051 | for n in range(1, pc): |
|
1057 | 1052 | key = '_i'+repr(n) |
|
1058 | 1053 | user_ns.pop(key,None) |
|
1059 | 1054 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
1060 | 1055 | hm = ip.history_manager |
|
1061 | 1056 | # don't delete these, as %save and %macro depending on the length |
|
1062 | 1057 | # of these lists to be preserved |
|
1063 | 1058 | hm.input_hist_parsed[:] = [''] * pc |
|
1064 | 1059 | hm.input_hist_raw[:] = [''] * pc |
|
1065 | 1060 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
1066 | 1061 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
1067 | 1062 | |
|
1068 | 1063 | elif target == 'array': |
|
1069 | 1064 | # Support cleaning up numpy arrays |
|
1070 | 1065 | try: |
|
1071 | 1066 | from numpy import ndarray |
|
1072 | 1067 | # This must be done with items and not iteritems because we're |
|
1073 | 1068 | # going to modify the dict in-place. |
|
1074 | 1069 | for x,val in user_ns.items(): |
|
1075 | 1070 | if isinstance(val,ndarray): |
|
1076 | 1071 | del user_ns[x] |
|
1077 | 1072 | except ImportError: |
|
1078 | 1073 | print "reset array only works if Numpy is available." |
|
1079 | 1074 | |
|
1080 | 1075 | elif target == 'dhist': |
|
1081 | 1076 | print "Flushing directory history" |
|
1082 | 1077 | del user_ns['_dh'][:] |
|
1083 | 1078 | |
|
1084 | 1079 | else: |
|
1085 | 1080 | print "Don't know how to reset ", |
|
1086 | 1081 | print target + ", please run `%reset?` for details" |
|
1087 | 1082 | |
|
1088 | 1083 | gc.collect() |
|
1089 | 1084 | |
|
1090 | 1085 | def magic_reset_selective(self, parameter_s=''): |
|
1091 | 1086 | """Resets the namespace by removing names defined by the user. |
|
1092 | 1087 | |
|
1093 | 1088 | Input/Output history are left around in case you need them. |
|
1094 | 1089 | |
|
1095 | 1090 | %reset_selective [-f] regex |
|
1096 | 1091 | |
|
1097 | 1092 | No action is taken if regex is not included |
|
1098 | 1093 | |
|
1099 | 1094 | Options |
|
1100 | 1095 | -f : force reset without asking for confirmation. |
|
1101 | 1096 | |
|
1102 | 1097 | See Also |
|
1103 | 1098 | -------- |
|
1104 | 1099 | magic_reset : invoked as ``%reset`` |
|
1105 | 1100 | |
|
1106 | 1101 | Examples |
|
1107 | 1102 | -------- |
|
1108 | 1103 | |
|
1109 | 1104 | We first fully reset the namespace so your output looks identical to |
|
1110 | 1105 | this example for pedagogical reasons; in practice you do not need a |
|
1111 | 1106 | full reset:: |
|
1112 | 1107 | |
|
1113 | 1108 | In [1]: %reset -f |
|
1114 | 1109 | |
|
1115 | 1110 | Now, with a clean namespace we can make a few variables and use |
|
1116 | 1111 | ``%reset_selective`` to only delete names that match our regexp:: |
|
1117 | 1112 | |
|
1118 | 1113 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1119 | 1114 | |
|
1120 | 1115 | In [3]: who_ls |
|
1121 | 1116 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1122 | 1117 | |
|
1123 | 1118 | In [4]: %reset_selective -f b[2-3]m |
|
1124 | 1119 | |
|
1125 | 1120 | In [5]: who_ls |
|
1126 | 1121 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1127 | 1122 | |
|
1128 | 1123 | In [6]: %reset_selective -f d |
|
1129 | 1124 | |
|
1130 | 1125 | In [7]: who_ls |
|
1131 | 1126 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1132 | 1127 | |
|
1133 | 1128 | In [8]: %reset_selective -f c |
|
1134 | 1129 | |
|
1135 | 1130 | In [9]: who_ls |
|
1136 | 1131 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1137 | 1132 | |
|
1138 | 1133 | In [10]: %reset_selective -f b |
|
1139 | 1134 | |
|
1140 | 1135 | In [11]: who_ls |
|
1141 | 1136 | Out[11]: ['a'] |
|
1142 | 1137 | |
|
1143 | 1138 | Notes |
|
1144 | 1139 | ----- |
|
1145 | 1140 | Calling this magic from clients that do not implement standard input, |
|
1146 | 1141 | such as the ipython notebook interface, will reset the namespace |
|
1147 | 1142 | without confirmation. |
|
1148 | 1143 | """ |
|
1149 | 1144 | |
|
1150 | 1145 | opts, regex = self.parse_options(parameter_s,'f') |
|
1151 | 1146 | |
|
1152 | 1147 | if opts.has_key('f'): |
|
1153 | 1148 | ans = True |
|
1154 | 1149 | else: |
|
1155 | 1150 | try: |
|
1156 | 1151 | ans = self.shell.ask_yes_no( |
|
1157 | 1152 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
1158 | 1153 | default='n') |
|
1159 | 1154 | except StdinNotImplementedError: |
|
1160 | 1155 | ans = True |
|
1161 | 1156 | if not ans: |
|
1162 | 1157 | print 'Nothing done.' |
|
1163 | 1158 | return |
|
1164 | 1159 | user_ns = self.shell.user_ns |
|
1165 | 1160 | if not regex: |
|
1166 | 1161 | print 'No regex pattern specified. Nothing done.' |
|
1167 | 1162 | return |
|
1168 | 1163 | else: |
|
1169 | 1164 | try: |
|
1170 | 1165 | m = re.compile(regex) |
|
1171 | 1166 | except TypeError: |
|
1172 | 1167 | raise TypeError('regex must be a string or compiled pattern') |
|
1173 | 1168 | for i in self.magic_who_ls(): |
|
1174 | 1169 | if m.search(i): |
|
1175 | 1170 | del(user_ns[i]) |
|
1176 | 1171 | |
|
1177 | 1172 | def magic_xdel(self, parameter_s=''): |
|
1178 | 1173 | """Delete a variable, trying to clear it from anywhere that |
|
1179 | 1174 | IPython's machinery has references to it. By default, this uses |
|
1180 | 1175 | the identity of the named object in the user namespace to remove |
|
1181 | 1176 | references held under other names. The object is also removed |
|
1182 | 1177 | from the output history. |
|
1183 | 1178 | |
|
1184 | 1179 | Options |
|
1185 | 1180 | -n : Delete the specified name from all namespaces, without |
|
1186 | 1181 | checking their identity. |
|
1187 | 1182 | """ |
|
1188 | 1183 | opts, varname = self.parse_options(parameter_s,'n') |
|
1189 | 1184 | try: |
|
1190 | 1185 | self.shell.del_var(varname, ('n' in opts)) |
|
1191 | 1186 | except (NameError, ValueError) as e: |
|
1192 | 1187 | print type(e).__name__ +": "+ str(e) |
|
1193 | 1188 | |
|
1194 | 1189 | def magic_logstart(self,parameter_s=''): |
|
1195 | 1190 | """Start logging anywhere in a session. |
|
1196 | 1191 | |
|
1197 | 1192 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1198 | 1193 | |
|
1199 | 1194 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1200 | 1195 | current directory, in 'rotate' mode (see below). |
|
1201 | 1196 | |
|
1202 | 1197 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1203 | 1198 | history up to that point and then continues logging. |
|
1204 | 1199 | |
|
1205 | 1200 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1206 | 1201 | of (note that the modes are given unquoted):\\ |
|
1207 | 1202 | append: well, that says it.\\ |
|
1208 | 1203 | backup: rename (if exists) to name~ and start name.\\ |
|
1209 | 1204 | global: single logfile in your home dir, appended to.\\ |
|
1210 | 1205 | over : overwrite existing log.\\ |
|
1211 | 1206 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1212 | 1207 | |
|
1213 | 1208 | Options: |
|
1214 | 1209 | |
|
1215 | 1210 | -o: log also IPython's output. In this mode, all commands which |
|
1216 | 1211 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1217 | 1212 | their corresponding input line. The output lines are always |
|
1218 | 1213 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1219 | 1214 | Python code. |
|
1220 | 1215 | |
|
1221 | 1216 | Since this marker is always the same, filtering only the output from |
|
1222 | 1217 | a log is very easy, using for example a simple awk call:: |
|
1223 | 1218 | |
|
1224 | 1219 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1225 | 1220 | |
|
1226 | 1221 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1227 | 1222 | input, so that user lines are logged in their final form, converted |
|
1228 | 1223 | into valid Python. For example, %Exit is logged as |
|
1229 | 1224 | _ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1230 | 1225 | exactly as typed, with no transformations applied. |
|
1231 | 1226 | |
|
1232 | 1227 | -t: put timestamps before each input line logged (these are put in |
|
1233 | 1228 | comments).""" |
|
1234 | 1229 | |
|
1235 | 1230 | opts,par = self.parse_options(parameter_s,'ort') |
|
1236 | 1231 | log_output = 'o' in opts |
|
1237 | 1232 | log_raw_input = 'r' in opts |
|
1238 | 1233 | timestamp = 't' in opts |
|
1239 | 1234 | |
|
1240 | 1235 | logger = self.shell.logger |
|
1241 | 1236 | |
|
1242 | 1237 | # if no args are given, the defaults set in the logger constructor by |
|
1243 | 1238 | # ipython remain valid |
|
1244 | 1239 | if par: |
|
1245 | 1240 | try: |
|
1246 | 1241 | logfname,logmode = par.split() |
|
1247 | 1242 | except: |
|
1248 | 1243 | logfname = par |
|
1249 | 1244 | logmode = 'backup' |
|
1250 | 1245 | else: |
|
1251 | 1246 | logfname = logger.logfname |
|
1252 | 1247 | logmode = logger.logmode |
|
1253 | 1248 | # put logfname into rc struct as if it had been called on the command |
|
1254 | 1249 | # line, so it ends up saved in the log header Save it in case we need |
|
1255 | 1250 | # to restore it... |
|
1256 | 1251 | old_logfile = self.shell.logfile |
|
1257 | 1252 | if logfname: |
|
1258 | 1253 | logfname = os.path.expanduser(logfname) |
|
1259 | 1254 | self.shell.logfile = logfname |
|
1260 | 1255 | |
|
1261 | 1256 | loghead = '# IPython log file\n\n' |
|
1262 | 1257 | try: |
|
1263 | 1258 | started = logger.logstart(logfname,loghead,logmode, |
|
1264 | 1259 | log_output,timestamp,log_raw_input) |
|
1265 | 1260 | except: |
|
1266 | 1261 | self.shell.logfile = old_logfile |
|
1267 | 1262 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1268 | 1263 | else: |
|
1269 | 1264 | # log input history up to this point, optionally interleaving |
|
1270 | 1265 | # output if requested |
|
1271 | 1266 | |
|
1272 | 1267 | if timestamp: |
|
1273 | 1268 | # disable timestamping for the previous history, since we've |
|
1274 | 1269 | # lost those already (no time machine here). |
|
1275 | 1270 | logger.timestamp = False |
|
1276 | 1271 | |
|
1277 | 1272 | if log_raw_input: |
|
1278 | 1273 | input_hist = self.shell.history_manager.input_hist_raw |
|
1279 | 1274 | else: |
|
1280 | 1275 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1281 | 1276 | |
|
1282 | 1277 | if log_output: |
|
1283 | 1278 | log_write = logger.log_write |
|
1284 | 1279 | output_hist = self.shell.history_manager.output_hist |
|
1285 | 1280 | for n in range(1,len(input_hist)-1): |
|
1286 | 1281 | log_write(input_hist[n].rstrip() + '\n') |
|
1287 | 1282 | if n in output_hist: |
|
1288 | 1283 | log_write(repr(output_hist[n]),'output') |
|
1289 | 1284 | else: |
|
1290 | 1285 | logger.log_write('\n'.join(input_hist[1:])) |
|
1291 | 1286 | logger.log_write('\n') |
|
1292 | 1287 | if timestamp: |
|
1293 | 1288 | # re-enable timestamping |
|
1294 | 1289 | logger.timestamp = True |
|
1295 | 1290 | |
|
1296 | 1291 | print ('Activating auto-logging. ' |
|
1297 | 1292 | 'Current session state plus future input saved.') |
|
1298 | 1293 | logger.logstate() |
|
1299 | 1294 | |
|
1300 | 1295 | def magic_logstop(self,parameter_s=''): |
|
1301 | 1296 | """Fully stop logging and close log file. |
|
1302 | 1297 | |
|
1303 | 1298 | In order to start logging again, a new %logstart call needs to be made, |
|
1304 | 1299 | possibly (though not necessarily) with a new filename, mode and other |
|
1305 | 1300 | options.""" |
|
1306 | 1301 | self.logger.logstop() |
|
1307 | 1302 | |
|
1308 | 1303 | def magic_logoff(self,parameter_s=''): |
|
1309 | 1304 | """Temporarily stop logging. |
|
1310 | 1305 | |
|
1311 | 1306 | You must have previously started logging.""" |
|
1312 | 1307 | self.shell.logger.switch_log(0) |
|
1313 | 1308 | |
|
1314 | 1309 | def magic_logon(self,parameter_s=''): |
|
1315 | 1310 | """Restart logging. |
|
1316 | 1311 | |
|
1317 | 1312 | This function is for restarting logging which you've temporarily |
|
1318 | 1313 | stopped with %logoff. For starting logging for the first time, you |
|
1319 | 1314 | must use the %logstart function, which allows you to specify an |
|
1320 | 1315 | optional log filename.""" |
|
1321 | 1316 | |
|
1322 | 1317 | self.shell.logger.switch_log(1) |
|
1323 | 1318 | |
|
1324 | 1319 | def magic_logstate(self,parameter_s=''): |
|
1325 | 1320 | """Print the status of the logging system.""" |
|
1326 | 1321 | |
|
1327 | 1322 | self.shell.logger.logstate() |
|
1328 | 1323 | |
|
1329 | 1324 | def magic_pdb(self, parameter_s=''): |
|
1330 | 1325 | """Control the automatic calling of the pdb interactive debugger. |
|
1331 | 1326 | |
|
1332 | 1327 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1333 | 1328 | argument it works as a toggle. |
|
1334 | 1329 | |
|
1335 | 1330 | When an exception is triggered, IPython can optionally call the |
|
1336 | 1331 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1337 | 1332 | this feature on and off. |
|
1338 | 1333 | |
|
1339 | 1334 | The initial state of this feature is set in your configuration |
|
1340 | 1335 | file (the option is ``InteractiveShell.pdb``). |
|
1341 | 1336 | |
|
1342 | 1337 | If you want to just activate the debugger AFTER an exception has fired, |
|
1343 | 1338 | without having to type '%pdb on' and rerunning your code, you can use |
|
1344 | 1339 | the %debug magic.""" |
|
1345 | 1340 | |
|
1346 | 1341 | par = parameter_s.strip().lower() |
|
1347 | 1342 | |
|
1348 | 1343 | if par: |
|
1349 | 1344 | try: |
|
1350 | 1345 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1351 | 1346 | except KeyError: |
|
1352 | 1347 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1353 | 1348 | 'or nothing for a toggle.') |
|
1354 | 1349 | return |
|
1355 | 1350 | else: |
|
1356 | 1351 | # toggle |
|
1357 | 1352 | new_pdb = not self.shell.call_pdb |
|
1358 | 1353 | |
|
1359 | 1354 | # set on the shell |
|
1360 | 1355 | self.shell.call_pdb = new_pdb |
|
1361 | 1356 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1362 | 1357 | |
|
1363 | 1358 | def magic_debug(self, parameter_s=''): |
|
1364 | 1359 | """Activate the interactive debugger in post-mortem mode. |
|
1365 | 1360 | |
|
1366 | 1361 | If an exception has just occurred, this lets you inspect its stack |
|
1367 | 1362 | frames interactively. Note that this will always work only on the last |
|
1368 | 1363 | traceback that occurred, so you must call this quickly after an |
|
1369 | 1364 | exception that you wish to inspect has fired, because if another one |
|
1370 | 1365 | occurs, it clobbers the previous one. |
|
1371 | 1366 | |
|
1372 | 1367 | If you want IPython to automatically do this on every exception, see |
|
1373 | 1368 | the %pdb magic for more details. |
|
1374 | 1369 | """ |
|
1375 | 1370 | self.shell.debugger(force=True) |
|
1376 | 1371 | |
|
1377 | 1372 | @skip_doctest |
|
1378 | 1373 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1379 | 1374 | opts=None,arg_lst=None,prog_ns=None): |
|
1380 | 1375 | |
|
1381 | 1376 | """Run a statement through the python code profiler. |
|
1382 | 1377 | |
|
1383 | 1378 | Usage: |
|
1384 | 1379 | %prun [options] statement |
|
1385 | 1380 | |
|
1386 | 1381 | The given statement (which doesn't require quote marks) is run via the |
|
1387 | 1382 | python profiler in a manner similar to the profile.run() function. |
|
1388 | 1383 | Namespaces are internally managed to work correctly; profile.run |
|
1389 | 1384 | cannot be used in IPython because it makes certain assumptions about |
|
1390 | 1385 | namespaces which do not hold under IPython. |
|
1391 | 1386 | |
|
1392 | 1387 | Options: |
|
1393 | 1388 | |
|
1394 | 1389 | -l <limit>: you can place restrictions on what or how much of the |
|
1395 | 1390 | profile gets printed. The limit value can be: |
|
1396 | 1391 | |
|
1397 | 1392 | * A string: only information for function names containing this string |
|
1398 | 1393 | is printed. |
|
1399 | 1394 | |
|
1400 | 1395 | * An integer: only these many lines are printed. |
|
1401 | 1396 | |
|
1402 | 1397 | * A float (between 0 and 1): this fraction of the report is printed |
|
1403 | 1398 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1404 | 1399 | |
|
1405 | 1400 | You can combine several limits with repeated use of the option. For |
|
1406 | 1401 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1407 | 1402 | information about class constructors. |
|
1408 | 1403 | |
|
1409 | 1404 | -r: return the pstats.Stats object generated by the profiling. This |
|
1410 | 1405 | object has all the information about the profile in it, and you can |
|
1411 | 1406 | later use it for further analysis or in other functions. |
|
1412 | 1407 | |
|
1413 | 1408 | -s <key>: sort profile by given key. You can provide more than one key |
|
1414 | 1409 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1415 | 1410 | default sorting key is 'time'. |
|
1416 | 1411 | |
|
1417 | 1412 | The following is copied verbatim from the profile documentation |
|
1418 | 1413 | referenced below: |
|
1419 | 1414 | |
|
1420 | 1415 | When more than one key is provided, additional keys are used as |
|
1421 | 1416 | secondary criteria when the there is equality in all keys selected |
|
1422 | 1417 | before them. |
|
1423 | 1418 | |
|
1424 | 1419 | Abbreviations can be used for any key names, as long as the |
|
1425 | 1420 | abbreviation is unambiguous. The following are the keys currently |
|
1426 | 1421 | defined: |
|
1427 | 1422 | |
|
1428 | 1423 | Valid Arg Meaning |
|
1429 | 1424 | "calls" call count |
|
1430 | 1425 | "cumulative" cumulative time |
|
1431 | 1426 | "file" file name |
|
1432 | 1427 | "module" file name |
|
1433 | 1428 | "pcalls" primitive call count |
|
1434 | 1429 | "line" line number |
|
1435 | 1430 | "name" function name |
|
1436 | 1431 | "nfl" name/file/line |
|
1437 | 1432 | "stdname" standard name |
|
1438 | 1433 | "time" internal time |
|
1439 | 1434 | |
|
1440 | 1435 | Note that all sorts on statistics are in descending order (placing |
|
1441 | 1436 | most time consuming items first), where as name, file, and line number |
|
1442 | 1437 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1443 | 1438 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1444 | 1439 | sort of the name as printed, which means that the embedded line |
|
1445 | 1440 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1446 | 1441 | would (if the file names were the same) appear in the string order |
|
1447 | 1442 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1448 | 1443 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1449 | 1444 | sort_stats("name", "file", "line"). |
|
1450 | 1445 | |
|
1451 | 1446 | -T <filename>: save profile results as shown on screen to a text |
|
1452 | 1447 | file. The profile is still shown on screen. |
|
1453 | 1448 | |
|
1454 | 1449 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1455 | 1450 | filename. This data is in a format understood by the pstats module, and |
|
1456 | 1451 | is generated by a call to the dump_stats() method of profile |
|
1457 | 1452 | objects. The profile is still shown on screen. |
|
1458 | 1453 | |
|
1459 | 1454 | -q: suppress output to the pager. Best used with -T and/or -D above. |
|
1460 | 1455 | |
|
1461 | 1456 | If you want to run complete programs under the profiler's control, use |
|
1462 | 1457 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1463 | 1458 | contains profiler specific options as described here. |
|
1464 | 1459 | |
|
1465 | 1460 | You can read the complete documentation for the profile module with:: |
|
1466 | 1461 | |
|
1467 | 1462 | In [1]: import profile; profile.help() |
|
1468 | 1463 | """ |
|
1469 | 1464 | |
|
1470 | 1465 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1471 | 1466 | |
|
1472 | 1467 | if user_mode: # regular user call |
|
1473 | 1468 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', |
|
1474 | 1469 | list_all=1, posix=False) |
|
1475 | 1470 | namespace = self.shell.user_ns |
|
1476 | 1471 | else: # called to run a program by %run -p |
|
1477 | 1472 | try: |
|
1478 | 1473 | filename = get_py_filename(arg_lst[0]) |
|
1479 | 1474 | except IOError as e: |
|
1480 | 1475 | try: |
|
1481 | 1476 | msg = str(e) |
|
1482 | 1477 | except UnicodeError: |
|
1483 | 1478 | msg = e.message |
|
1484 | 1479 | error(msg) |
|
1485 | 1480 | return |
|
1486 | 1481 | |
|
1487 | 1482 | arg_str = 'execfile(filename,prog_ns)' |
|
1488 | 1483 | namespace = { |
|
1489 | 1484 | 'execfile': self.shell.safe_execfile, |
|
1490 | 1485 | 'prog_ns': prog_ns, |
|
1491 | 1486 | 'filename': filename |
|
1492 | 1487 | } |
|
1493 | 1488 | |
|
1494 | 1489 | opts.merge(opts_def) |
|
1495 | 1490 | |
|
1496 | 1491 | prof = profile.Profile() |
|
1497 | 1492 | try: |
|
1498 | 1493 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1499 | 1494 | sys_exit = '' |
|
1500 | 1495 | except SystemExit: |
|
1501 | 1496 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1502 | 1497 | |
|
1503 | 1498 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1504 | 1499 | |
|
1505 | 1500 | lims = opts.l |
|
1506 | 1501 | if lims: |
|
1507 | 1502 | lims = [] # rebuild lims with ints/floats/strings |
|
1508 | 1503 | for lim in opts.l: |
|
1509 | 1504 | try: |
|
1510 | 1505 | lims.append(int(lim)) |
|
1511 | 1506 | except ValueError: |
|
1512 | 1507 | try: |
|
1513 | 1508 | lims.append(float(lim)) |
|
1514 | 1509 | except ValueError: |
|
1515 | 1510 | lims.append(lim) |
|
1516 | 1511 | |
|
1517 | 1512 | # Trap output. |
|
1518 | 1513 | stdout_trap = StringIO() |
|
1519 | 1514 | |
|
1520 | 1515 | if hasattr(stats,'stream'): |
|
1521 | 1516 | # In newer versions of python, the stats object has a 'stream' |
|
1522 | 1517 | # attribute to write into. |
|
1523 | 1518 | stats.stream = stdout_trap |
|
1524 | 1519 | stats.print_stats(*lims) |
|
1525 | 1520 | else: |
|
1526 | 1521 | # For older versions, we manually redirect stdout during printing |
|
1527 | 1522 | sys_stdout = sys.stdout |
|
1528 | 1523 | try: |
|
1529 | 1524 | sys.stdout = stdout_trap |
|
1530 | 1525 | stats.print_stats(*lims) |
|
1531 | 1526 | finally: |
|
1532 | 1527 | sys.stdout = sys_stdout |
|
1533 | 1528 | |
|
1534 | 1529 | output = stdout_trap.getvalue() |
|
1535 | 1530 | output = output.rstrip() |
|
1536 | 1531 | |
|
1537 | 1532 | if 'q' not in opts: |
|
1538 | 1533 | page.page(output) |
|
1539 | 1534 | print sys_exit, |
|
1540 | 1535 | |
|
1541 | 1536 | dump_file = opts.D[0] |
|
1542 | 1537 | text_file = opts.T[0] |
|
1543 | 1538 | if dump_file: |
|
1544 | 1539 | dump_file = unquote_filename(dump_file) |
|
1545 | 1540 | prof.dump_stats(dump_file) |
|
1546 | 1541 | print '\n*** Profile stats marshalled to file',\ |
|
1547 | 1542 | `dump_file`+'.',sys_exit |
|
1548 | 1543 | if text_file: |
|
1549 | 1544 | text_file = unquote_filename(text_file) |
|
1550 | 1545 | pfile = file(text_file,'w') |
|
1551 | 1546 | pfile.write(output) |
|
1552 | 1547 | pfile.close() |
|
1553 | 1548 | print '\n*** Profile printout saved to text file',\ |
|
1554 | 1549 | `text_file`+'.',sys_exit |
|
1555 | 1550 | |
|
1556 | 1551 | if opts.has_key('r'): |
|
1557 | 1552 | return stats |
|
1558 | 1553 | else: |
|
1559 | 1554 | return None |
|
1560 | 1555 | |
|
1561 | 1556 | @skip_doctest |
|
1562 | 1557 | def magic_run(self, parameter_s ='', runner=None, |
|
1563 | 1558 | file_finder=get_py_filename): |
|
1564 | 1559 | """Run the named file inside IPython as a program. |
|
1565 | 1560 | |
|
1566 | 1561 | Usage:\\ |
|
1567 | 1562 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1568 | 1563 | |
|
1569 | 1564 | Parameters after the filename are passed as command-line arguments to |
|
1570 | 1565 | the program (put in sys.argv). Then, control returns to IPython's |
|
1571 | 1566 | prompt. |
|
1572 | 1567 | |
|
1573 | 1568 | This is similar to running at a system prompt:\\ |
|
1574 | 1569 | $ python file args\\ |
|
1575 | 1570 | but with the advantage of giving you IPython's tracebacks, and of |
|
1576 | 1571 | loading all variables into your interactive namespace for further use |
|
1577 | 1572 | (unless -p is used, see below). |
|
1578 | 1573 | |
|
1579 | 1574 | The file is executed in a namespace initially consisting only of |
|
1580 | 1575 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1581 | 1576 | sees its environment as if it were being run as a stand-alone program |
|
1582 | 1577 | (except for sharing global objects such as previously imported |
|
1583 | 1578 | modules). But after execution, the IPython interactive namespace gets |
|
1584 | 1579 | updated with all variables defined in the program (except for __name__ |
|
1585 | 1580 | and sys.argv). This allows for very convenient loading of code for |
|
1586 | 1581 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1587 | 1582 | |
|
1588 | 1583 | Options: |
|
1589 | 1584 | |
|
1590 | 1585 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1591 | 1586 | without extension (as python does under import). This allows running |
|
1592 | 1587 | scripts and reloading the definitions in them without calling code |
|
1593 | 1588 | protected by an ' if __name__ == "__main__" ' clause. |
|
1594 | 1589 | |
|
1595 | 1590 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1596 | 1591 | is useful if you are experimenting with code written in a text editor |
|
1597 | 1592 | which depends on variables defined interactively. |
|
1598 | 1593 | |
|
1599 | 1594 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1600 | 1595 | being run. This is particularly useful if IPython is being used to |
|
1601 | 1596 | run unittests, which always exit with a sys.exit() call. In such |
|
1602 | 1597 | cases you are interested in the output of the test results, not in |
|
1603 | 1598 | seeing a traceback of the unittest module. |
|
1604 | 1599 | |
|
1605 | 1600 | -t: print timing information at the end of the run. IPython will give |
|
1606 | 1601 | you an estimated CPU time consumption for your script, which under |
|
1607 | 1602 | Unix uses the resource module to avoid the wraparound problems of |
|
1608 | 1603 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1609 | 1604 | is also given (for Windows platforms this is reported as 0.0). |
|
1610 | 1605 | |
|
1611 | 1606 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1612 | 1607 | must be an integer indicating how many times you want the script to |
|
1613 | 1608 | run. The final timing report will include total and per run results. |
|
1614 | 1609 | |
|
1615 | 1610 | For example (testing the script uniq_stable.py):: |
|
1616 | 1611 | |
|
1617 | 1612 | In [1]: run -t uniq_stable |
|
1618 | 1613 | |
|
1619 | 1614 | IPython CPU timings (estimated):\\ |
|
1620 | 1615 | User : 0.19597 s.\\ |
|
1621 | 1616 | System: 0.0 s.\\ |
|
1622 | 1617 | |
|
1623 | 1618 | In [2]: run -t -N5 uniq_stable |
|
1624 | 1619 | |
|
1625 | 1620 | IPython CPU timings (estimated):\\ |
|
1626 | 1621 | Total runs performed: 5\\ |
|
1627 | 1622 | Times : Total Per run\\ |
|
1628 | 1623 | User : 0.910862 s, 0.1821724 s.\\ |
|
1629 | 1624 | System: 0.0 s, 0.0 s. |
|
1630 | 1625 | |
|
1631 | 1626 | -d: run your program under the control of pdb, the Python debugger. |
|
1632 | 1627 | This allows you to execute your program step by step, watch variables, |
|
1633 | 1628 | etc. Internally, what IPython does is similar to calling: |
|
1634 | 1629 | |
|
1635 | 1630 | pdb.run('execfile("YOURFILENAME")') |
|
1636 | 1631 | |
|
1637 | 1632 | with a breakpoint set on line 1 of your file. You can change the line |
|
1638 | 1633 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1639 | 1634 | (where N must be an integer). For example:: |
|
1640 | 1635 | |
|
1641 | 1636 | %run -d -b40 myscript |
|
1642 | 1637 | |
|
1643 | 1638 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1644 | 1639 | the first breakpoint must be set on a line which actually does |
|
1645 | 1640 | something (not a comment or docstring) for it to stop execution. |
|
1646 | 1641 | |
|
1647 | 1642 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1648 | 1643 | first enter 'c' (without quotes) to start execution up to the first |
|
1649 | 1644 | breakpoint. |
|
1650 | 1645 | |
|
1651 | 1646 | Entering 'help' gives information about the use of the debugger. You |
|
1652 | 1647 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1653 | 1648 | at a prompt. |
|
1654 | 1649 | |
|
1655 | 1650 | -p: run program under the control of the Python profiler module (which |
|
1656 | 1651 | prints a detailed report of execution times, function calls, etc). |
|
1657 | 1652 | |
|
1658 | 1653 | You can pass other options after -p which affect the behavior of the |
|
1659 | 1654 | profiler itself. See the docs for %prun for details. |
|
1660 | 1655 | |
|
1661 | 1656 | In this mode, the program's variables do NOT propagate back to the |
|
1662 | 1657 | IPython interactive namespace (because they remain in the namespace |
|
1663 | 1658 | where the profiler executes them). |
|
1664 | 1659 | |
|
1665 | 1660 | Internally this triggers a call to %prun, see its documentation for |
|
1666 | 1661 | details on the options available specifically for profiling. |
|
1667 | 1662 | |
|
1668 | 1663 | There is one special usage for which the text above doesn't apply: |
|
1669 | 1664 | if the filename ends with .ipy, the file is run as ipython script, |
|
1670 | 1665 | just as if the commands were written on IPython prompt. |
|
1671 | 1666 | |
|
1672 | 1667 | -m: specify module name to load instead of script path. Similar to |
|
1673 | 1668 | the -m option for the python interpreter. Use this option last if you |
|
1674 | 1669 | want to combine with other %run options. Unlike the python interpreter |
|
1675 | 1670 | only source modules are allowed no .pyc or .pyo files. |
|
1676 | 1671 | For example:: |
|
1677 | 1672 | |
|
1678 | 1673 | %run -m example |
|
1679 | 1674 | |
|
1680 | 1675 | will run the example module. |
|
1681 | 1676 | |
|
1682 | 1677 | """ |
|
1683 | 1678 | |
|
1684 | 1679 | # get arguments and set sys.argv for program to be run. |
|
1685 | 1680 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', |
|
1686 | 1681 | mode='list', list_all=1) |
|
1687 | 1682 | if "m" in opts: |
|
1688 | 1683 | modulename = opts["m"][0] |
|
1689 | 1684 | modpath = find_mod(modulename) |
|
1690 | 1685 | if modpath is None: |
|
1691 | 1686 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
1692 | 1687 | return |
|
1693 | 1688 | arg_lst = [modpath] + arg_lst |
|
1694 | 1689 | try: |
|
1695 | 1690 | filename = file_finder(arg_lst[0]) |
|
1696 | 1691 | except IndexError: |
|
1697 | 1692 | warn('you must provide at least a filename.') |
|
1698 | 1693 | print '\n%run:\n', oinspect.getdoc(self.magic_run) |
|
1699 | 1694 | return |
|
1700 | 1695 | except IOError as e: |
|
1701 | 1696 | try: |
|
1702 | 1697 | msg = str(e) |
|
1703 | 1698 | except UnicodeError: |
|
1704 | 1699 | msg = e.message |
|
1705 | 1700 | error(msg) |
|
1706 | 1701 | return |
|
1707 | 1702 | |
|
1708 | 1703 | if filename.lower().endswith('.ipy'): |
|
1709 | 1704 | self.shell.safe_execfile_ipy(filename) |
|
1710 | 1705 | return |
|
1711 | 1706 | |
|
1712 | 1707 | # Control the response to exit() calls made by the script being run |
|
1713 | 1708 | exit_ignore = 'e' in opts |
|
1714 | 1709 | |
|
1715 | 1710 | # Make sure that the running script gets a proper sys.argv as if it |
|
1716 | 1711 | # were run from a system shell. |
|
1717 | 1712 | save_argv = sys.argv # save it for later restoring |
|
1718 | 1713 | |
|
1719 | 1714 | # simulate shell expansion on arguments, at least tilde expansion |
|
1720 | 1715 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] |
|
1721 | 1716 | |
|
1722 | 1717 | sys.argv = [filename] + args # put in the proper filename |
|
1723 | 1718 | # protect sys.argv from potential unicode strings on Python 2: |
|
1724 | 1719 | if not py3compat.PY3: |
|
1725 | 1720 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
1726 | 1721 | |
|
1727 | 1722 | if 'i' in opts: |
|
1728 | 1723 | # Run in user's interactive namespace |
|
1729 | 1724 | prog_ns = self.shell.user_ns |
|
1730 | 1725 | __name__save = self.shell.user_ns['__name__'] |
|
1731 | 1726 | prog_ns['__name__'] = '__main__' |
|
1732 | 1727 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1733 | 1728 | else: |
|
1734 | 1729 | # Run in a fresh, empty namespace |
|
1735 | 1730 | if 'n' in opts: |
|
1736 | 1731 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1737 | 1732 | else: |
|
1738 | 1733 | name = '__main__' |
|
1739 | 1734 | |
|
1740 | 1735 | main_mod = self.shell.new_main_mod() |
|
1741 | 1736 | prog_ns = main_mod.__dict__ |
|
1742 | 1737 | prog_ns['__name__'] = name |
|
1743 | 1738 | |
|
1744 | 1739 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1745 | 1740 | # set the __file__ global in the script's namespace |
|
1746 | 1741 | prog_ns['__file__'] = filename |
|
1747 | 1742 | |
|
1748 | 1743 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1749 | 1744 | # that, if we overwrite __main__, we replace it at the end |
|
1750 | 1745 | main_mod_name = prog_ns['__name__'] |
|
1751 | 1746 | |
|
1752 | 1747 | if main_mod_name == '__main__': |
|
1753 | 1748 | restore_main = sys.modules['__main__'] |
|
1754 | 1749 | else: |
|
1755 | 1750 | restore_main = False |
|
1756 | 1751 | |
|
1757 | 1752 | # This needs to be undone at the end to prevent holding references to |
|
1758 | 1753 | # every single object ever created. |
|
1759 | 1754 | sys.modules[main_mod_name] = main_mod |
|
1760 | 1755 | |
|
1761 | 1756 | try: |
|
1762 | 1757 | stats = None |
|
1763 | 1758 | with self.readline_no_record: |
|
1764 | 1759 | if 'p' in opts: |
|
1765 | 1760 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) |
|
1766 | 1761 | else: |
|
1767 | 1762 | if 'd' in opts: |
|
1768 | 1763 | deb = debugger.Pdb(self.shell.colors) |
|
1769 | 1764 | # reset Breakpoint state, which is moronically kept |
|
1770 | 1765 | # in a class |
|
1771 | 1766 | bdb.Breakpoint.next = 1 |
|
1772 | 1767 | bdb.Breakpoint.bplist = {} |
|
1773 | 1768 | bdb.Breakpoint.bpbynumber = [None] |
|
1774 | 1769 | # Set an initial breakpoint to stop execution |
|
1775 | 1770 | maxtries = 10 |
|
1776 | 1771 | bp = int(opts.get('b', [1])[0]) |
|
1777 | 1772 | checkline = deb.checkline(filename, bp) |
|
1778 | 1773 | if not checkline: |
|
1779 | 1774 | for bp in range(bp + 1, bp + maxtries + 1): |
|
1780 | 1775 | if deb.checkline(filename, bp): |
|
1781 | 1776 | break |
|
1782 | 1777 | else: |
|
1783 | 1778 | msg = ("\nI failed to find a valid line to set " |
|
1784 | 1779 | "a breakpoint\n" |
|
1785 | 1780 | "after trying up to line: %s.\n" |
|
1786 | 1781 | "Please set a valid breakpoint manually " |
|
1787 | 1782 | "with the -b option." % bp) |
|
1788 | 1783 | error(msg) |
|
1789 | 1784 | return |
|
1790 | 1785 | # if we find a good linenumber, set the breakpoint |
|
1791 | 1786 | deb.do_break('%s:%s' % (filename, bp)) |
|
1792 | 1787 | # Start file run |
|
1793 | 1788 | print "NOTE: Enter 'c' at the", |
|
1794 | 1789 | print "%s prompt to start your script." % deb.prompt |
|
1795 | 1790 | try: |
|
1796 | 1791 | deb.run('execfile("%s")' % filename, prog_ns) |
|
1797 | 1792 | |
|
1798 | 1793 | except: |
|
1799 | 1794 | etype, value, tb = sys.exc_info() |
|
1800 | 1795 | # Skip three frames in the traceback: the %run one, |
|
1801 | 1796 | # one inside bdb.py, and the command-line typed by the |
|
1802 | 1797 | # user (run by exec in pdb itself). |
|
1803 | 1798 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
1804 | 1799 | else: |
|
1805 | 1800 | if runner is None: |
|
1806 | 1801 | runner = self.shell.safe_execfile |
|
1807 | 1802 | if 't' in opts: |
|
1808 | 1803 | # timed execution |
|
1809 | 1804 | try: |
|
1810 | 1805 | nruns = int(opts['N'][0]) |
|
1811 | 1806 | if nruns < 1: |
|
1812 | 1807 | error('Number of runs must be >=1') |
|
1813 | 1808 | return |
|
1814 | 1809 | except (KeyError): |
|
1815 | 1810 | nruns = 1 |
|
1816 | 1811 | twall0 = time.time() |
|
1817 | 1812 | if nruns == 1: |
|
1818 | 1813 | t0 = clock2() |
|
1819 | 1814 | runner(filename, prog_ns, prog_ns, |
|
1820 | 1815 | exit_ignore=exit_ignore) |
|
1821 | 1816 | t1 = clock2() |
|
1822 | 1817 | t_usr = t1[0] - t0[0] |
|
1823 | 1818 | t_sys = t1[1] - t0[1] |
|
1824 | 1819 | print "\nIPython CPU timings (estimated):" |
|
1825 | 1820 | print " User : %10.2f s." % t_usr |
|
1826 | 1821 | print " System : %10.2f s." % t_sys |
|
1827 | 1822 | else: |
|
1828 | 1823 | runs = range(nruns) |
|
1829 | 1824 | t0 = clock2() |
|
1830 | 1825 | for nr in runs: |
|
1831 | 1826 | runner(filename, prog_ns, prog_ns, |
|
1832 | 1827 | exit_ignore=exit_ignore) |
|
1833 | 1828 | t1 = clock2() |
|
1834 | 1829 | t_usr = t1[0] - t0[0] |
|
1835 | 1830 | t_sys = t1[1] - t0[1] |
|
1836 | 1831 | print "\nIPython CPU timings (estimated):" |
|
1837 | 1832 | print "Total runs performed:", nruns |
|
1838 | 1833 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') |
|
1839 | 1834 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
1840 | 1835 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
1841 | 1836 | twall1 = time.time() |
|
1842 | 1837 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
1843 | 1838 | |
|
1844 | 1839 | else: |
|
1845 | 1840 | # regular execution |
|
1846 | 1841 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) |
|
1847 | 1842 | |
|
1848 | 1843 | if 'i' in opts: |
|
1849 | 1844 | self.shell.user_ns['__name__'] = __name__save |
|
1850 | 1845 | else: |
|
1851 | 1846 | # The shell MUST hold a reference to prog_ns so after %run |
|
1852 | 1847 | # exits, the python deletion mechanism doesn't zero it out |
|
1853 | 1848 | # (leaving dangling references). |
|
1854 | 1849 | self.shell.cache_main_mod(prog_ns, filename) |
|
1855 | 1850 | # update IPython interactive namespace |
|
1856 | 1851 | |
|
1857 | 1852 | # Some forms of read errors on the file may mean the |
|
1858 | 1853 | # __name__ key was never set; using pop we don't have to |
|
1859 | 1854 | # worry about a possible KeyError. |
|
1860 | 1855 | prog_ns.pop('__name__', None) |
|
1861 | 1856 | |
|
1862 | 1857 | self.shell.user_ns.update(prog_ns) |
|
1863 | 1858 | finally: |
|
1864 | 1859 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1865 | 1860 | # being a module to becoming a dict missing some key data after |
|
1866 | 1861 | # %run. As best I can see, this is NOT something IPython is doing |
|
1867 | 1862 | # at all, and similar problems have been reported before: |
|
1868 | 1863 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1869 | 1864 | # Since this seems to be done by the interpreter itself, the best |
|
1870 | 1865 | # we can do is to at least restore __builtins__ for the user on |
|
1871 | 1866 | # exit. |
|
1872 | 1867 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
1873 | 1868 | |
|
1874 | 1869 | # Ensure key global structures are restored |
|
1875 | 1870 | sys.argv = save_argv |
|
1876 | 1871 | if restore_main: |
|
1877 | 1872 | sys.modules['__main__'] = restore_main |
|
1878 | 1873 | else: |
|
1879 | 1874 | # Remove from sys.modules the reference to main_mod we'd |
|
1880 | 1875 | # added. Otherwise it will trap references to objects |
|
1881 | 1876 | # contained therein. |
|
1882 | 1877 | del sys.modules[main_mod_name] |
|
1883 | 1878 | |
|
1884 | 1879 | return stats |
|
1885 | 1880 | |
|
1886 | 1881 | @skip_doctest |
|
1887 | 1882 | def magic_timeit(self, parameter_s =''): |
|
1888 | 1883 | """Time execution of a Python statement or expression |
|
1889 | 1884 | |
|
1890 | 1885 | Usage:\\ |
|
1891 | 1886 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1892 | 1887 | |
|
1893 | 1888 | Time execution of a Python statement or expression using the timeit |
|
1894 | 1889 | module. |
|
1895 | 1890 | |
|
1896 | 1891 | Options: |
|
1897 | 1892 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1898 | 1893 | is not given, a fitting value is chosen. |
|
1899 | 1894 | |
|
1900 | 1895 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1901 | 1896 | Default: 3 |
|
1902 | 1897 | |
|
1903 | 1898 | -t: use time.time to measure the time, which is the default on Unix. |
|
1904 | 1899 | This function measures wall time. |
|
1905 | 1900 | |
|
1906 | 1901 | -c: use time.clock to measure the time, which is the default on |
|
1907 | 1902 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1908 | 1903 | instead and returns the CPU user time. |
|
1909 | 1904 | |
|
1910 | 1905 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1911 | 1906 | Default: 3 |
|
1912 | 1907 | |
|
1913 | 1908 | |
|
1914 | 1909 | Examples |
|
1915 | 1910 | -------- |
|
1916 | 1911 | :: |
|
1917 | 1912 | |
|
1918 | 1913 | In [1]: %timeit pass |
|
1919 | 1914 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1920 | 1915 | |
|
1921 | 1916 | In [2]: u = None |
|
1922 | 1917 | |
|
1923 | 1918 | In [3]: %timeit u is None |
|
1924 | 1919 | 10000000 loops, best of 3: 184 ns per loop |
|
1925 | 1920 | |
|
1926 | 1921 | In [4]: %timeit -r 4 u == None |
|
1927 | 1922 | 1000000 loops, best of 4: 242 ns per loop |
|
1928 | 1923 | |
|
1929 | 1924 | In [5]: import time |
|
1930 | 1925 | |
|
1931 | 1926 | In [6]: %timeit -n1 time.sleep(2) |
|
1932 | 1927 | 1 loops, best of 3: 2 s per loop |
|
1933 | 1928 | |
|
1934 | 1929 | |
|
1935 | 1930 | The times reported by %timeit will be slightly higher than those |
|
1936 | 1931 | reported by the timeit.py script when variables are accessed. This is |
|
1937 | 1932 | due to the fact that %timeit executes the statement in the namespace |
|
1938 | 1933 | of the shell, compared with timeit.py, which uses a single setup |
|
1939 | 1934 | statement to import function or create variables. Generally, the bias |
|
1940 | 1935 | does not matter as long as results from timeit.py are not mixed with |
|
1941 | 1936 | those from %timeit.""" |
|
1942 | 1937 | |
|
1943 | 1938 | import timeit |
|
1944 | 1939 | import math |
|
1945 | 1940 | |
|
1946 | 1941 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1947 | 1942 | # certain terminals. Until we figure out a robust way of |
|
1948 | 1943 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1949 | 1944 | # microseconds. I am really NOT happy about disabling the proper |
|
1950 | 1945 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1951 | 1946 | # right solution for this is, I'm all ears... |
|
1952 | 1947 | # |
|
1953 | 1948 | # Note: using |
|
1954 | 1949 | # |
|
1955 | 1950 | # s = u'\xb5' |
|
1956 | 1951 | # s.encode(sys.getdefaultencoding()) |
|
1957 | 1952 | # |
|
1958 | 1953 | # is not sufficient, as I've seen terminals where that fails but |
|
1959 | 1954 | # print s |
|
1960 | 1955 | # |
|
1961 | 1956 | # succeeds |
|
1962 | 1957 | # |
|
1963 | 1958 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1964 | 1959 | |
|
1965 | 1960 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1966 | 1961 | units = [u"s", u"ms",u'us',"ns"] |
|
1967 | 1962 | |
|
1968 | 1963 | scaling = [1, 1e3, 1e6, 1e9] |
|
1969 | 1964 | |
|
1970 | 1965 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1971 | 1966 | posix=False, strict=False) |
|
1972 | 1967 | if stmt == "": |
|
1973 | 1968 | return |
|
1974 | 1969 | timefunc = timeit.default_timer |
|
1975 | 1970 | number = int(getattr(opts, "n", 0)) |
|
1976 | 1971 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1977 | 1972 | precision = int(getattr(opts, "p", 3)) |
|
1978 | 1973 | if hasattr(opts, "t"): |
|
1979 | 1974 | timefunc = time.time |
|
1980 | 1975 | if hasattr(opts, "c"): |
|
1981 | 1976 | timefunc = clock |
|
1982 | 1977 | |
|
1983 | 1978 | timer = timeit.Timer(timer=timefunc) |
|
1984 | 1979 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1985 | 1980 | # but is there a better way to achieve that the code stmt has access |
|
1986 | 1981 | # to the shell namespace? |
|
1987 | 1982 | |
|
1988 | 1983 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1989 | 1984 | 'setup': "pass"} |
|
1990 | 1985 | # Track compilation time so it can be reported if too long |
|
1991 | 1986 | # Minimum time above which compilation time will be reported |
|
1992 | 1987 | tc_min = 0.1 |
|
1993 | 1988 | |
|
1994 | 1989 | t0 = clock() |
|
1995 | 1990 | code = compile(src, "<magic-timeit>", "exec") |
|
1996 | 1991 | tc = clock()-t0 |
|
1997 | 1992 | |
|
1998 | 1993 | ns = {} |
|
1999 | 1994 | exec code in self.shell.user_ns, ns |
|
2000 | 1995 | timer.inner = ns["inner"] |
|
2001 | 1996 | |
|
2002 | 1997 | if number == 0: |
|
2003 | 1998 | # determine number so that 0.2 <= total time < 2.0 |
|
2004 | 1999 | number = 1 |
|
2005 | 2000 | for i in range(1, 10): |
|
2006 | 2001 | if timer.timeit(number) >= 0.2: |
|
2007 | 2002 | break |
|
2008 | 2003 | number *= 10 |
|
2009 | 2004 | |
|
2010 | 2005 | best = min(timer.repeat(repeat, number)) / number |
|
2011 | 2006 | |
|
2012 | 2007 | if best > 0.0 and best < 1000.0: |
|
2013 | 2008 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
2014 | 2009 | elif best >= 1000.0: |
|
2015 | 2010 | order = 0 |
|
2016 | 2011 | else: |
|
2017 | 2012 | order = 3 |
|
2018 | 2013 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
2019 | 2014 | precision, |
|
2020 | 2015 | best * scaling[order], |
|
2021 | 2016 | units[order]) |
|
2022 | 2017 | if tc > tc_min: |
|
2023 | 2018 | print "Compiler time: %.2f s" % tc |
|
2024 | 2019 | |
|
2025 | 2020 | @skip_doctest |
|
2026 | 2021 | @needs_local_scope |
|
2027 | 2022 | def magic_time(self,parameter_s = ''): |
|
2028 | 2023 | """Time execution of a Python statement or expression. |
|
2029 | 2024 | |
|
2030 | 2025 | The CPU and wall clock times are printed, and the value of the |
|
2031 | 2026 | expression (if any) is returned. Note that under Win32, system time |
|
2032 | 2027 | is always reported as 0, since it can not be measured. |
|
2033 | 2028 | |
|
2034 | 2029 | This function provides very basic timing functionality. In Python |
|
2035 | 2030 | 2.3, the timeit module offers more control and sophistication, so this |
|
2036 | 2031 | could be rewritten to use it (patches welcome). |
|
2037 | 2032 | |
|
2038 | 2033 | Examples |
|
2039 | 2034 | -------- |
|
2040 | 2035 | :: |
|
2041 | 2036 | |
|
2042 | 2037 | In [1]: time 2**128 |
|
2043 | 2038 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2044 | 2039 | Wall time: 0.00 |
|
2045 | 2040 | Out[1]: 340282366920938463463374607431768211456L |
|
2046 | 2041 | |
|
2047 | 2042 | In [2]: n = 1000000 |
|
2048 | 2043 | |
|
2049 | 2044 | In [3]: time sum(range(n)) |
|
2050 | 2045 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
2051 | 2046 | Wall time: 1.37 |
|
2052 | 2047 | Out[3]: 499999500000L |
|
2053 | 2048 | |
|
2054 | 2049 | In [4]: time print 'hello world' |
|
2055 | 2050 | hello world |
|
2056 | 2051 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2057 | 2052 | Wall time: 0.00 |
|
2058 | 2053 | |
|
2059 | 2054 | Note that the time needed by Python to compile the given expression |
|
2060 | 2055 | will be reported if it is more than 0.1s. In this example, the |
|
2061 | 2056 | actual exponentiation is done by Python at compilation time, so while |
|
2062 | 2057 | the expression can take a noticeable amount of time to compute, that |
|
2063 | 2058 | time is purely due to the compilation: |
|
2064 | 2059 | |
|
2065 | 2060 | In [5]: time 3**9999; |
|
2066 | 2061 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2067 | 2062 | Wall time: 0.00 s |
|
2068 | 2063 | |
|
2069 | 2064 | In [6]: time 3**999999; |
|
2070 | 2065 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2071 | 2066 | Wall time: 0.00 s |
|
2072 | 2067 | Compiler : 0.78 s |
|
2073 | 2068 | """ |
|
2074 | 2069 | |
|
2075 | 2070 | # fail immediately if the given expression can't be compiled |
|
2076 | 2071 | |
|
2077 | 2072 | expr = self.shell.prefilter(parameter_s,False) |
|
2078 | 2073 | |
|
2079 | 2074 | # Minimum time above which compilation time will be reported |
|
2080 | 2075 | tc_min = 0.1 |
|
2081 | 2076 | |
|
2082 | 2077 | try: |
|
2083 | 2078 | mode = 'eval' |
|
2084 | 2079 | t0 = clock() |
|
2085 | 2080 | code = compile(expr,'<timed eval>',mode) |
|
2086 | 2081 | tc = clock()-t0 |
|
2087 | 2082 | except SyntaxError: |
|
2088 | 2083 | mode = 'exec' |
|
2089 | 2084 | t0 = clock() |
|
2090 | 2085 | code = compile(expr,'<timed exec>',mode) |
|
2091 | 2086 | tc = clock()-t0 |
|
2092 | 2087 | # skew measurement as little as possible |
|
2093 | 2088 | glob = self.shell.user_ns |
|
2094 | 2089 | locs = self._magic_locals |
|
2095 | 2090 | clk = clock2 |
|
2096 | 2091 | wtime = time.time |
|
2097 | 2092 | # time execution |
|
2098 | 2093 | wall_st = wtime() |
|
2099 | 2094 | if mode=='eval': |
|
2100 | 2095 | st = clk() |
|
2101 | 2096 | out = eval(code, glob, locs) |
|
2102 | 2097 | end = clk() |
|
2103 | 2098 | else: |
|
2104 | 2099 | st = clk() |
|
2105 | 2100 | exec code in glob, locs |
|
2106 | 2101 | end = clk() |
|
2107 | 2102 | out = None |
|
2108 | 2103 | wall_end = wtime() |
|
2109 | 2104 | # Compute actual times and report |
|
2110 | 2105 | wall_time = wall_end-wall_st |
|
2111 | 2106 | cpu_user = end[0]-st[0] |
|
2112 | 2107 | cpu_sys = end[1]-st[1] |
|
2113 | 2108 | cpu_tot = cpu_user+cpu_sys |
|
2114 | 2109 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
2115 | 2110 | (cpu_user,cpu_sys,cpu_tot) |
|
2116 | 2111 | print "Wall time: %.2f s" % wall_time |
|
2117 | 2112 | if tc > tc_min: |
|
2118 | 2113 | print "Compiler : %.2f s" % tc |
|
2119 | 2114 | return out |
|
2120 | 2115 | |
|
2121 | 2116 | @skip_doctest |
|
2122 | 2117 | def magic_macro(self,parameter_s = ''): |
|
2123 | 2118 | """Define a macro for future re-execution. It accepts ranges of history, |
|
2124 | 2119 | filenames or string objects. |
|
2125 | 2120 | |
|
2126 | 2121 | Usage:\\ |
|
2127 | 2122 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
2128 | 2123 | |
|
2129 | 2124 | Options: |
|
2130 | 2125 | |
|
2131 | 2126 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2132 | 2127 | so that magics are loaded in their transformed version to valid |
|
2133 | 2128 | Python. If this option is given, the raw input as typed as the |
|
2134 | 2129 | command line is used instead. |
|
2135 | 2130 | |
|
2136 | 2131 | This will define a global variable called `name` which is a string |
|
2137 | 2132 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2138 | 2133 | above) from your input history into a single string. This variable |
|
2139 | 2134 | acts like an automatic function which re-executes those lines as if |
|
2140 | 2135 | you had typed them. You just type 'name' at the prompt and the code |
|
2141 | 2136 | executes. |
|
2142 | 2137 | |
|
2143 | 2138 | The syntax for indicating input ranges is described in %history. |
|
2144 | 2139 | |
|
2145 | 2140 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2146 | 2141 | notation, where N:M means numbers N through M-1. |
|
2147 | 2142 | |
|
2148 | 2143 | For example, if your history contains (%hist prints it):: |
|
2149 | 2144 | |
|
2150 | 2145 | 44: x=1 |
|
2151 | 2146 | 45: y=3 |
|
2152 | 2147 | 46: z=x+y |
|
2153 | 2148 | 47: print x |
|
2154 | 2149 | 48: a=5 |
|
2155 | 2150 | 49: print 'x',x,'y',y |
|
2156 | 2151 | |
|
2157 | 2152 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2158 | 2153 | called my_macro with:: |
|
2159 | 2154 | |
|
2160 | 2155 | In [55]: %macro my_macro 44-47 49 |
|
2161 | 2156 | |
|
2162 | 2157 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2163 | 2158 | in one pass. |
|
2164 | 2159 | |
|
2165 | 2160 | You don't need to give the line-numbers in order, and any given line |
|
2166 | 2161 | number can appear multiple times. You can assemble macros with any |
|
2167 | 2162 | lines from your input history in any order. |
|
2168 | 2163 | |
|
2169 | 2164 | The macro is a simple object which holds its value in an attribute, |
|
2170 | 2165 | but IPython's display system checks for macros and executes them as |
|
2171 | 2166 | code instead of printing them when you type their name. |
|
2172 | 2167 | |
|
2173 | 2168 | You can view a macro's contents by explicitly printing it with:: |
|
2174 | 2169 | |
|
2175 | 2170 | print macro_name |
|
2176 | 2171 | |
|
2177 | 2172 | """ |
|
2178 | 2173 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2179 | 2174 | if not args: # List existing macros |
|
2180 | 2175 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2181 | 2176 | isinstance(v, Macro)) |
|
2182 | 2177 | if len(args) == 1: |
|
2183 | 2178 | raise UsageError( |
|
2184 | 2179 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2185 | 2180 | name, codefrom = args[0], " ".join(args[1:]) |
|
2186 | 2181 | |
|
2187 | 2182 | #print 'rng',ranges # dbg |
|
2188 | 2183 | try: |
|
2189 | 2184 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2190 | 2185 | except (ValueError, TypeError) as e: |
|
2191 | 2186 | print e.args[0] |
|
2192 | 2187 | return |
|
2193 | 2188 | macro = Macro(lines) |
|
2194 | 2189 | self.shell.define_macro(name, macro) |
|
2195 | 2190 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2196 | 2191 | print '=== Macro contents: ===' |
|
2197 | 2192 | print macro, |
|
2198 | 2193 | |
|
2199 | 2194 | def magic_save(self,parameter_s = ''): |
|
2200 | 2195 | """Save a set of lines or a macro to a given filename. |
|
2201 | 2196 | |
|
2202 | 2197 | Usage:\\ |
|
2203 | 2198 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2204 | 2199 | |
|
2205 | 2200 | Options: |
|
2206 | 2201 | |
|
2207 | 2202 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2208 | 2203 | so that magics are loaded in their transformed version to valid |
|
2209 | 2204 | Python. If this option is given, the raw input as typed as the |
|
2210 | 2205 | command line is used instead. |
|
2211 | 2206 | |
|
2212 | 2207 | This function uses the same syntax as %history for input ranges, |
|
2213 | 2208 | then saves the lines to the filename you specify. |
|
2214 | 2209 | |
|
2215 | 2210 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2216 | 2211 | it asks for confirmation before overwriting existing files.""" |
|
2217 | 2212 | |
|
2218 | 2213 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2219 | 2214 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
2220 | 2215 | if not fname.endswith('.py'): |
|
2221 | 2216 | fname += '.py' |
|
2222 | 2217 | if os.path.isfile(fname): |
|
2223 | 2218 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2224 | 2219 | if ans.lower() not in ['y','yes']: |
|
2225 | 2220 | print 'Operation cancelled.' |
|
2226 | 2221 | return |
|
2227 | 2222 | try: |
|
2228 | 2223 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2229 | 2224 | except (TypeError, ValueError) as e: |
|
2230 | 2225 | print e.args[0] |
|
2231 | 2226 | return |
|
2232 | 2227 | with py3compat.open(fname,'w', encoding="utf-8") as f: |
|
2233 | 2228 | f.write(u"# coding: utf-8\n") |
|
2234 | 2229 | f.write(py3compat.cast_unicode(cmds)) |
|
2235 | 2230 | print 'The following commands were written to file `%s`:' % fname |
|
2236 | 2231 | print cmds |
|
2237 | 2232 | |
|
2238 | 2233 | def magic_pastebin(self, parameter_s = ''): |
|
2239 | 2234 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2240 | 2235 | try: |
|
2241 | 2236 | code = self.shell.find_user_code(parameter_s) |
|
2242 | 2237 | except (ValueError, TypeError) as e: |
|
2243 | 2238 | print e.args[0] |
|
2244 | 2239 | return |
|
2245 | 2240 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2246 | 2241 | id = pbserver.pastes.newPaste("python", code) |
|
2247 | 2242 | return "http://paste.pocoo.org/show/" + id |
|
2248 | 2243 | |
|
2249 | 2244 | def magic_loadpy(self, arg_s): |
|
2250 | 2245 | """Load a .py python script into the GUI console. |
|
2251 | 2246 | |
|
2252 | 2247 | This magic command can either take a local filename or a url:: |
|
2253 | 2248 | |
|
2254 | 2249 | %loadpy myscript.py |
|
2255 | 2250 | %loadpy http://www.example.com/myscript.py |
|
2256 | 2251 | """ |
|
2257 | 2252 | arg_s = unquote_filename(arg_s) |
|
2258 | 2253 | remote_url = arg_s.startswith(('http://', 'https://')) |
|
2259 | 2254 | local_url = not remote_url |
|
2260 | 2255 | if local_url and not arg_s.endswith('.py'): |
|
2261 | 2256 | # Local files must be .py; for remote URLs it's possible that the |
|
2262 | 2257 | # fetch URL doesn't have a .py in it (many servers have an opaque |
|
2263 | 2258 | # URL, such as scipy-central.org). |
|
2264 | 2259 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
2265 | 2260 | if remote_url: |
|
2266 | 2261 | import urllib2 |
|
2267 | 2262 | fileobj = urllib2.urlopen(arg_s) |
|
2268 | 2263 | # While responses have a .info().getencoding() way of asking for |
|
2269 | 2264 | # their encoding, in *many* cases the return value is bogus. In |
|
2270 | 2265 | # the wild, servers serving utf-8 but declaring latin-1 are |
|
2271 | 2266 | # extremely common, as the old HTTP standards specify latin-1 as |
|
2272 | 2267 | # the default but many modern filesystems use utf-8. So we can NOT |
|
2273 | 2268 | # rely on the headers. Short of building complex encoding-guessing |
|
2274 | 2269 | # logic, going with utf-8 is a simple solution likely to be right |
|
2275 | 2270 | # in most real-world cases. |
|
2276 | 2271 | linesource = fileobj.read().decode('utf-8', 'replace').splitlines() |
|
2277 | 2272 | fileobj.close() |
|
2278 | 2273 | else: |
|
2279 | 2274 | with open(arg_s) as fileobj: |
|
2280 | 2275 | linesource = fileobj.read().splitlines() |
|
2281 | 2276 | |
|
2282 | 2277 | # Strip out encoding declarations |
|
2283 | 2278 | lines = [l for l in linesource if not _encoding_declaration_re.match(l)] |
|
2284 | 2279 | |
|
2285 | 2280 | self.set_next_input(os.linesep.join(lines)) |
|
2286 | 2281 | |
|
2287 | 2282 | def _find_edit_target(self, args, opts, last_call): |
|
2288 | 2283 | """Utility method used by magic_edit to find what to edit.""" |
|
2289 | 2284 | |
|
2290 | 2285 | def make_filename(arg): |
|
2291 | 2286 | "Make a filename from the given args" |
|
2292 | 2287 | arg = unquote_filename(arg) |
|
2293 | 2288 | try: |
|
2294 | 2289 | filename = get_py_filename(arg) |
|
2295 | 2290 | except IOError: |
|
2296 | 2291 | # If it ends with .py but doesn't already exist, assume we want |
|
2297 | 2292 | # a new file. |
|
2298 | 2293 | if arg.endswith('.py'): |
|
2299 | 2294 | filename = arg |
|
2300 | 2295 | else: |
|
2301 | 2296 | filename = None |
|
2302 | 2297 | return filename |
|
2303 | 2298 | |
|
2304 | 2299 | # Set a few locals from the options for convenience: |
|
2305 | 2300 | opts_prev = 'p' in opts |
|
2306 | 2301 | opts_raw = 'r' in opts |
|
2307 | 2302 | |
|
2308 | 2303 | # custom exceptions |
|
2309 | 2304 | class DataIsObject(Exception): pass |
|
2310 | 2305 | |
|
2311 | 2306 | # Default line number value |
|
2312 | 2307 | lineno = opts.get('n',None) |
|
2313 | 2308 | |
|
2314 | 2309 | if opts_prev: |
|
2315 | 2310 | args = '_%s' % last_call[0] |
|
2316 | 2311 | if not self.shell.user_ns.has_key(args): |
|
2317 | 2312 | args = last_call[1] |
|
2318 | 2313 | |
|
2319 | 2314 | # use last_call to remember the state of the previous call, but don't |
|
2320 | 2315 | # let it be clobbered by successive '-p' calls. |
|
2321 | 2316 | try: |
|
2322 | 2317 | last_call[0] = self.shell.displayhook.prompt_count |
|
2323 | 2318 | if not opts_prev: |
|
2324 |
last_call[1] = |
|
|
2319 | last_call[1] = args | |
|
2325 | 2320 | except: |
|
2326 | 2321 | pass |
|
2327 | 2322 | |
|
2328 | 2323 | # by default this is done with temp files, except when the given |
|
2329 | 2324 | # arg is a filename |
|
2330 | 2325 | use_temp = True |
|
2331 | 2326 | |
|
2332 | 2327 | data = '' |
|
2333 | 2328 | |
|
2334 | 2329 | # First, see if the arguments should be a filename. |
|
2335 | 2330 | filename = make_filename(args) |
|
2336 | 2331 | if filename: |
|
2337 | 2332 | use_temp = False |
|
2338 | 2333 | elif args: |
|
2339 | 2334 | # Mode where user specifies ranges of lines, like in %macro. |
|
2340 | 2335 | data = self.extract_input_lines(args, opts_raw) |
|
2341 | 2336 | if not data: |
|
2342 | 2337 | try: |
|
2343 | 2338 | # Load the parameter given as a variable. If not a string, |
|
2344 | 2339 | # process it as an object instead (below) |
|
2345 | 2340 | |
|
2346 | 2341 | #print '*** args',args,'type',type(args) # dbg |
|
2347 | 2342 | data = eval(args, self.shell.user_ns) |
|
2348 | 2343 | if not isinstance(data, basestring): |
|
2349 | 2344 | raise DataIsObject |
|
2350 | 2345 | |
|
2351 | 2346 | except (NameError,SyntaxError): |
|
2352 | 2347 | # given argument is not a variable, try as a filename |
|
2353 | 2348 | filename = make_filename(args) |
|
2354 | 2349 | if filename is None: |
|
2355 | 2350 | warn("Argument given (%s) can't be found as a variable " |
|
2356 | 2351 | "or as a filename." % args) |
|
2357 | 2352 | return |
|
2358 | 2353 | use_temp = False |
|
2359 | 2354 | |
|
2360 | 2355 | except DataIsObject: |
|
2361 | 2356 | # macros have a special edit function |
|
2362 | 2357 | if isinstance(data, Macro): |
|
2363 | 2358 | raise MacroToEdit(data) |
|
2364 | 2359 | |
|
2365 | 2360 | # For objects, try to edit the file where they are defined |
|
2366 | 2361 | try: |
|
2367 | 2362 | filename = inspect.getabsfile(data) |
|
2368 | 2363 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2369 | 2364 | # class created by %edit? Try to find source |
|
2370 | 2365 | # by looking for method definitions instead, the |
|
2371 | 2366 | # __module__ in those classes is FakeModule. |
|
2372 | 2367 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2373 | 2368 | for attr in attrs: |
|
2374 | 2369 | if not inspect.ismethod(attr): |
|
2375 | 2370 | continue |
|
2376 | 2371 | filename = inspect.getabsfile(attr) |
|
2377 | 2372 | if filename and 'fakemodule' not in filename.lower(): |
|
2378 | 2373 | # change the attribute to be the edit target instead |
|
2379 | 2374 | data = attr |
|
2380 | 2375 | break |
|
2381 | 2376 | |
|
2382 | 2377 | datafile = 1 |
|
2383 | 2378 | except TypeError: |
|
2384 | 2379 | filename = make_filename(args) |
|
2385 | 2380 | datafile = 1 |
|
2386 | 2381 | warn('Could not find file where `%s` is defined.\n' |
|
2387 | 2382 | 'Opening a file named `%s`' % (args,filename)) |
|
2388 | 2383 | # Now, make sure we can actually read the source (if it was in |
|
2389 | 2384 | # a temp file it's gone by now). |
|
2390 | 2385 | if datafile: |
|
2391 | 2386 | try: |
|
2392 | 2387 | if lineno is None: |
|
2393 | 2388 | lineno = inspect.getsourcelines(data)[1] |
|
2394 | 2389 | except IOError: |
|
2395 | 2390 | filename = make_filename(args) |
|
2396 | 2391 | if filename is None: |
|
2397 | 2392 | warn('The file `%s` where `%s` was defined cannot ' |
|
2398 | 2393 | 'be read.' % (filename,data)) |
|
2399 | 2394 | return |
|
2400 | 2395 | use_temp = False |
|
2401 | 2396 | |
|
2402 | 2397 | if use_temp: |
|
2403 | 2398 | filename = self.shell.mktempfile(data) |
|
2404 | 2399 | print 'IPython will make a temporary file named:',filename |
|
2405 | 2400 | |
|
2406 | 2401 | return filename, lineno, use_temp |
|
2407 | 2402 | |
|
2408 | 2403 | def _edit_macro(self,mname,macro): |
|
2409 | 2404 | """open an editor with the macro data in a file""" |
|
2410 | 2405 | filename = self.shell.mktempfile(macro.value) |
|
2411 | 2406 | self.shell.hooks.editor(filename) |
|
2412 | 2407 | |
|
2413 | 2408 | # and make a new macro object, to replace the old one |
|
2414 | 2409 | mfile = open(filename) |
|
2415 | 2410 | mvalue = mfile.read() |
|
2416 | 2411 | mfile.close() |
|
2417 | 2412 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2418 | 2413 | |
|
2419 | 2414 | def magic_ed(self,parameter_s=''): |
|
2420 | 2415 | """Alias to %edit.""" |
|
2421 | 2416 | return self.magic_edit(parameter_s) |
|
2422 | 2417 | |
|
2423 | 2418 | @skip_doctest |
|
2424 | 2419 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2425 | 2420 | """Bring up an editor and execute the resulting code. |
|
2426 | 2421 | |
|
2427 | 2422 | Usage: |
|
2428 | 2423 | %edit [options] [args] |
|
2429 | 2424 | |
|
2430 | 2425 | %edit runs IPython's editor hook. The default version of this hook is |
|
2431 | 2426 | set to call the editor specified by your $EDITOR environment variable. |
|
2432 | 2427 | If this isn't found, it will default to vi under Linux/Unix and to |
|
2433 | 2428 | notepad under Windows. See the end of this docstring for how to change |
|
2434 | 2429 | the editor hook. |
|
2435 | 2430 | |
|
2436 | 2431 | You can also set the value of this editor via the |
|
2437 | 2432 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
2438 | 2433 | This is useful if you wish to use a different editor from your typical |
|
2439 | 2434 | default with IPython (and for Windows users who typically don't set |
|
2440 | 2435 | environment variables). |
|
2441 | 2436 | |
|
2442 | 2437 | This command allows you to conveniently edit multi-line code right in |
|
2443 | 2438 | your IPython session. |
|
2444 | 2439 | |
|
2445 | 2440 | If called without arguments, %edit opens up an empty editor with a |
|
2446 | 2441 | temporary file and will execute the contents of this file when you |
|
2447 | 2442 | close it (don't forget to save it!). |
|
2448 | 2443 | |
|
2449 | 2444 | |
|
2450 | 2445 | Options: |
|
2451 | 2446 | |
|
2452 | 2447 | -n <number>: open the editor at a specified line number. By default, |
|
2453 | 2448 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2454 | 2449 | you can configure this by providing your own modified hook if your |
|
2455 | 2450 | favorite editor supports line-number specifications with a different |
|
2456 | 2451 | syntax. |
|
2457 | 2452 | |
|
2458 | 2453 | -p: this will call the editor with the same data as the previous time |
|
2459 | 2454 | it was used, regardless of how long ago (in your current session) it |
|
2460 | 2455 | was. |
|
2461 | 2456 | |
|
2462 | 2457 | -r: use 'raw' input. This option only applies to input taken from the |
|
2463 | 2458 | user's history. By default, the 'processed' history is used, so that |
|
2464 | 2459 | magics are loaded in their transformed version to valid Python. If |
|
2465 | 2460 | this option is given, the raw input as typed as the command line is |
|
2466 | 2461 | used instead. When you exit the editor, it will be executed by |
|
2467 | 2462 | IPython's own processor. |
|
2468 | 2463 | |
|
2469 | 2464 | -x: do not execute the edited code immediately upon exit. This is |
|
2470 | 2465 | mainly useful if you are editing programs which need to be called with |
|
2471 | 2466 | command line arguments, which you can then do using %run. |
|
2472 | 2467 | |
|
2473 | 2468 | |
|
2474 | 2469 | Arguments: |
|
2475 | 2470 | |
|
2476 | 2471 | If arguments are given, the following possibilities exist: |
|
2477 | 2472 | |
|
2478 | 2473 | - If the argument is a filename, IPython will load that into the |
|
2479 | 2474 | editor. It will execute its contents with execfile() when you exit, |
|
2480 | 2475 | loading any code in the file into your interactive namespace. |
|
2481 | 2476 | |
|
2482 | 2477 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2483 | 2478 | The syntax is the same as in the %history magic. |
|
2484 | 2479 | |
|
2485 | 2480 | - If the argument is a string variable, its contents are loaded |
|
2486 | 2481 | into the editor. You can thus edit any string which contains |
|
2487 | 2482 | python code (including the result of previous edits). |
|
2488 | 2483 | |
|
2489 | 2484 | - If the argument is the name of an object (other than a string), |
|
2490 | 2485 | IPython will try to locate the file where it was defined and open the |
|
2491 | 2486 | editor at the point where it is defined. You can use `%edit function` |
|
2492 | 2487 | to load an editor exactly at the point where 'function' is defined, |
|
2493 | 2488 | edit it and have the file be executed automatically. |
|
2494 | 2489 | |
|
2495 | 2490 | - If the object is a macro (see %macro for details), this opens up your |
|
2496 | 2491 | specified editor with a temporary file containing the macro's data. |
|
2497 | 2492 | Upon exit, the macro is reloaded with the contents of the file. |
|
2498 | 2493 | |
|
2499 | 2494 | Note: opening at an exact line is only supported under Unix, and some |
|
2500 | 2495 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2501 | 2496 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2502 | 2497 | (X)Emacs, vi, jed, pico and joe all do. |
|
2503 | 2498 | |
|
2504 | 2499 | After executing your code, %edit will return as output the code you |
|
2505 | 2500 | typed in the editor (except when it was an existing file). This way |
|
2506 | 2501 | you can reload the code in further invocations of %edit as a variable, |
|
2507 | 2502 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2508 | 2503 | the output. |
|
2509 | 2504 | |
|
2510 | 2505 | Note that %edit is also available through the alias %ed. |
|
2511 | 2506 | |
|
2512 | 2507 | This is an example of creating a simple function inside the editor and |
|
2513 | 2508 | then modifying it. First, start up the editor:: |
|
2514 | 2509 | |
|
2515 | 2510 | In [1]: ed |
|
2516 | 2511 | Editing... done. Executing edited code... |
|
2517 | 2512 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
2518 | 2513 | session"\\n' |
|
2519 | 2514 | |
|
2520 | 2515 | We can then call the function foo():: |
|
2521 | 2516 | |
|
2522 | 2517 | In [2]: foo() |
|
2523 | 2518 | foo() was defined in an editing session |
|
2524 | 2519 | |
|
2525 | 2520 | Now we edit foo. IPython automatically loads the editor with the |
|
2526 | 2521 | (temporary) file where foo() was previously defined:: |
|
2527 | 2522 | |
|
2528 | 2523 | In [3]: ed foo |
|
2529 | 2524 | Editing... done. Executing edited code... |
|
2530 | 2525 | |
|
2531 | 2526 | And if we call foo() again we get the modified version:: |
|
2532 | 2527 | |
|
2533 | 2528 | In [4]: foo() |
|
2534 | 2529 | foo() has now been changed! |
|
2535 | 2530 | |
|
2536 | 2531 | Here is an example of how to edit a code snippet successive |
|
2537 | 2532 | times. First we call the editor:: |
|
2538 | 2533 | |
|
2539 | 2534 | In [5]: ed |
|
2540 | 2535 | Editing... done. Executing edited code... |
|
2541 | 2536 | hello |
|
2542 | 2537 | Out[5]: "print 'hello'\\n" |
|
2543 | 2538 | |
|
2544 | 2539 | Now we call it again with the previous output (stored in _):: |
|
2545 | 2540 | |
|
2546 | 2541 | In [6]: ed _ |
|
2547 | 2542 | Editing... done. Executing edited code... |
|
2548 | 2543 | hello world |
|
2549 | 2544 | Out[6]: "print 'hello world'\\n" |
|
2550 | 2545 | |
|
2551 | 2546 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
2552 | 2547 | |
|
2553 | 2548 | In [7]: ed _8 |
|
2554 | 2549 | Editing... done. Executing edited code... |
|
2555 | 2550 | hello again |
|
2556 | 2551 | Out[7]: "print 'hello again'\\n" |
|
2557 | 2552 | |
|
2558 | 2553 | |
|
2559 | 2554 | Changing the default editor hook: |
|
2560 | 2555 | |
|
2561 | 2556 | If you wish to write your own editor hook, you can put it in a |
|
2562 | 2557 | configuration file which you load at startup time. The default hook |
|
2563 | 2558 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2564 | 2559 | starting example for further modifications. That file also has |
|
2565 | 2560 | general instructions on how to set a new hook for use once you've |
|
2566 | 2561 | defined it.""" |
|
2567 | 2562 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2568 | 2563 | |
|
2569 | 2564 | try: |
|
2570 | 2565 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
2571 | 2566 | except MacroToEdit as e: |
|
2572 | 2567 | self._edit_macro(args, e.args[0]) |
|
2573 | 2568 | return |
|
2574 | 2569 | |
|
2575 | 2570 | # do actual editing here |
|
2576 | 2571 | print 'Editing...', |
|
2577 | 2572 | sys.stdout.flush() |
|
2578 | 2573 | try: |
|
2579 | 2574 | # Quote filenames that may have spaces in them |
|
2580 | 2575 | if ' ' in filename: |
|
2581 | 2576 | filename = "'%s'" % filename |
|
2582 | 2577 | self.shell.hooks.editor(filename,lineno) |
|
2583 | 2578 | except TryNext: |
|
2584 | 2579 | warn('Could not open editor') |
|
2585 | 2580 | return |
|
2586 | 2581 | |
|
2587 | 2582 | # XXX TODO: should this be generalized for all string vars? |
|
2588 | 2583 | # For now, this is special-cased to blocks created by cpaste |
|
2589 | 2584 | if args.strip() == 'pasted_block': |
|
2590 | 2585 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2591 | 2586 | |
|
2592 | 2587 | if 'x' in opts: # -x prevents actual execution |
|
2593 | 2588 | |
|
2594 | 2589 | else: |
|
2595 | 2590 | print 'done. Executing edited code...' |
|
2596 | 2591 | if 'r' in opts: # Untranslated IPython code |
|
2597 | 2592 | self.shell.run_cell(file_read(filename), |
|
2598 | 2593 | store_history=False) |
|
2599 | 2594 | else: |
|
2600 | 2595 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2601 | 2596 | self.shell.user_ns) |
|
2602 | 2597 | |
|
2603 | 2598 | if is_temp: |
|
2604 | 2599 | try: |
|
2605 | 2600 | return open(filename).read() |
|
2606 | 2601 | except IOError,msg: |
|
2607 | 2602 | if msg.filename == filename: |
|
2608 | 2603 | warn('File not found. Did you forget to save?') |
|
2609 | 2604 | return |
|
2610 | 2605 | else: |
|
2611 | 2606 | self.shell.showtraceback() |
|
2612 | 2607 | |
|
2613 | 2608 | def magic_xmode(self,parameter_s = ''): |
|
2614 | 2609 | """Switch modes for the exception handlers. |
|
2615 | 2610 | |
|
2616 | 2611 | Valid modes: Plain, Context and Verbose. |
|
2617 | 2612 | |
|
2618 | 2613 | If called without arguments, acts as a toggle.""" |
|
2619 | 2614 | |
|
2620 | 2615 | def xmode_switch_err(name): |
|
2621 | 2616 | warn('Error changing %s exception modes.\n%s' % |
|
2622 | 2617 | (name,sys.exc_info()[1])) |
|
2623 | 2618 | |
|
2624 | 2619 | shell = self.shell |
|
2625 | 2620 | new_mode = parameter_s.strip().capitalize() |
|
2626 | 2621 | try: |
|
2627 | 2622 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2628 | 2623 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2629 | 2624 | except: |
|
2630 | 2625 | xmode_switch_err('user') |
|
2631 | 2626 | |
|
2632 | 2627 | def magic_colors(self,parameter_s = ''): |
|
2633 | 2628 | """Switch color scheme for prompts, info system and exception handlers. |
|
2634 | 2629 | |
|
2635 | 2630 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2636 | 2631 | |
|
2637 | 2632 | Color scheme names are not case-sensitive. |
|
2638 | 2633 | |
|
2639 | 2634 | Examples |
|
2640 | 2635 | -------- |
|
2641 | 2636 | To get a plain black and white terminal:: |
|
2642 | 2637 | |
|
2643 | 2638 | %colors nocolor |
|
2644 | 2639 | """ |
|
2645 | 2640 | |
|
2646 | 2641 | def color_switch_err(name): |
|
2647 | 2642 | warn('Error changing %s color schemes.\n%s' % |
|
2648 | 2643 | (name,sys.exc_info()[1])) |
|
2649 | 2644 | |
|
2650 | 2645 | |
|
2651 | 2646 | new_scheme = parameter_s.strip() |
|
2652 | 2647 | if not new_scheme: |
|
2653 | 2648 | raise UsageError( |
|
2654 | 2649 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2655 | 2650 | return |
|
2656 | 2651 | # local shortcut |
|
2657 | 2652 | shell = self.shell |
|
2658 | 2653 | |
|
2659 | 2654 | import IPython.utils.rlineimpl as readline |
|
2660 | 2655 | |
|
2661 | 2656 | if not shell.colors_force and \ |
|
2662 | 2657 | not readline.have_readline and sys.platform == "win32": |
|
2663 | 2658 | msg = """\ |
|
2664 | 2659 | Proper color support under MS Windows requires the pyreadline library. |
|
2665 | 2660 | You can find it at: |
|
2666 | 2661 | http://ipython.org/pyreadline.html |
|
2667 | 2662 | Gary's readline needs the ctypes module, from: |
|
2668 | 2663 | http://starship.python.net/crew/theller/ctypes |
|
2669 | 2664 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2670 | 2665 | |
|
2671 | 2666 | Defaulting color scheme to 'NoColor'""" |
|
2672 | 2667 | new_scheme = 'NoColor' |
|
2673 | 2668 | warn(msg) |
|
2674 | 2669 | |
|
2675 | 2670 | # readline option is 0 |
|
2676 | 2671 | if not shell.colors_force and not shell.has_readline: |
|
2677 | 2672 | new_scheme = 'NoColor' |
|
2678 | 2673 | |
|
2679 | 2674 | # Set prompt colors |
|
2680 | 2675 | try: |
|
2681 | 2676 | shell.prompt_manager.color_scheme = new_scheme |
|
2682 | 2677 | except: |
|
2683 | 2678 | color_switch_err('prompt') |
|
2684 | 2679 | else: |
|
2685 | 2680 | shell.colors = \ |
|
2686 | 2681 | shell.prompt_manager.color_scheme_table.active_scheme_name |
|
2687 | 2682 | # Set exception colors |
|
2688 | 2683 | try: |
|
2689 | 2684 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2690 | 2685 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2691 | 2686 | except: |
|
2692 | 2687 | color_switch_err('exception') |
|
2693 | 2688 | |
|
2694 | 2689 | # Set info (for 'object?') colors |
|
2695 | 2690 | if shell.color_info: |
|
2696 | 2691 | try: |
|
2697 | 2692 | shell.inspector.set_active_scheme(new_scheme) |
|
2698 | 2693 | except: |
|
2699 | 2694 | color_switch_err('object inspector') |
|
2700 | 2695 | else: |
|
2701 | 2696 | shell.inspector.set_active_scheme('NoColor') |
|
2702 | 2697 | |
|
2703 | 2698 | def magic_pprint(self, parameter_s=''): |
|
2704 | 2699 | """Toggle pretty printing on/off.""" |
|
2705 | 2700 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2706 | 2701 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2707 | 2702 | print 'Pretty printing has been turned', \ |
|
2708 | 2703 | ['OFF','ON'][ptformatter.pprint] |
|
2709 | 2704 | |
|
2710 | 2705 | #...................................................................... |
|
2711 | 2706 | # Functions to implement unix shell-type things |
|
2712 | 2707 | |
|
2713 | 2708 | @skip_doctest |
|
2714 | 2709 | def magic_alias(self, parameter_s = ''): |
|
2715 | 2710 | """Define an alias for a system command. |
|
2716 | 2711 | |
|
2717 | 2712 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2718 | 2713 | |
|
2719 | 2714 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2720 | 2715 | params' (from your underlying operating system). |
|
2721 | 2716 | |
|
2722 | 2717 | Aliases have lower precedence than magic functions and Python normal |
|
2723 | 2718 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2724 | 2719 | alias can not be executed until 'del foo' removes the Python variable. |
|
2725 | 2720 | |
|
2726 | 2721 | You can use the %l specifier in an alias definition to represent the |
|
2727 | 2722 | whole line when the alias is called. For example:: |
|
2728 | 2723 | |
|
2729 | 2724 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2730 | 2725 | In [3]: bracket hello world |
|
2731 | 2726 | Input in brackets: <hello world> |
|
2732 | 2727 | |
|
2733 | 2728 | You can also define aliases with parameters using %s specifiers (one |
|
2734 | 2729 | per parameter):: |
|
2735 | 2730 | |
|
2736 | 2731 | In [1]: alias parts echo first %s second %s |
|
2737 | 2732 | In [2]: %parts A B |
|
2738 | 2733 | first A second B |
|
2739 | 2734 | In [3]: %parts A |
|
2740 | 2735 | Incorrect number of arguments: 2 expected. |
|
2741 | 2736 | parts is an alias to: 'echo first %s second %s' |
|
2742 | 2737 | |
|
2743 | 2738 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2744 | 2739 | the other in your aliases. |
|
2745 | 2740 | |
|
2746 | 2741 | Aliases expand Python variables just like system calls using ! or !! |
|
2747 | 2742 | do: all expressions prefixed with '$' get expanded. For details of |
|
2748 | 2743 | the semantic rules, see PEP-215: |
|
2749 | 2744 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2750 | 2745 | IPython for variable expansion. If you want to access a true shell |
|
2751 | 2746 | variable, an extra $ is necessary to prevent its expansion by |
|
2752 | 2747 | IPython:: |
|
2753 | 2748 | |
|
2754 | 2749 | In [6]: alias show echo |
|
2755 | 2750 | In [7]: PATH='A Python string' |
|
2756 | 2751 | In [8]: show $PATH |
|
2757 | 2752 | A Python string |
|
2758 | 2753 | In [9]: show $$PATH |
|
2759 | 2754 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2760 | 2755 | |
|
2761 | 2756 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2762 | 2757 | and %rehashx functions, which automatically create aliases for the |
|
2763 | 2758 | contents of your $PATH. |
|
2764 | 2759 | |
|
2765 | 2760 | If called with no parameters, %alias prints the current alias table.""" |
|
2766 | 2761 | |
|
2767 | 2762 | par = parameter_s.strip() |
|
2768 | 2763 | if not par: |
|
2769 | 2764 | stored = self.db.get('stored_aliases', {} ) |
|
2770 | 2765 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2771 | 2766 | # for k, v in stored: |
|
2772 | 2767 | # atab.append(k, v[0]) |
|
2773 | 2768 | |
|
2774 | 2769 | print "Total number of aliases:", len(aliases) |
|
2775 | 2770 | sys.stdout.flush() |
|
2776 | 2771 | return aliases |
|
2777 | 2772 | |
|
2778 | 2773 | # Now try to define a new one |
|
2779 | 2774 | try: |
|
2780 | 2775 | alias,cmd = par.split(None, 1) |
|
2781 | 2776 | except: |
|
2782 | 2777 | print oinspect.getdoc(self.magic_alias) |
|
2783 | 2778 | else: |
|
2784 | 2779 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2785 | 2780 | # end magic_alias |
|
2786 | 2781 | |
|
2787 | 2782 | def magic_unalias(self, parameter_s = ''): |
|
2788 | 2783 | """Remove an alias""" |
|
2789 | 2784 | |
|
2790 | 2785 | aname = parameter_s.strip() |
|
2791 | 2786 | self.shell.alias_manager.undefine_alias(aname) |
|
2792 | 2787 | stored = self.db.get('stored_aliases', {} ) |
|
2793 | 2788 | if aname in stored: |
|
2794 | 2789 | print "Removing %stored alias",aname |
|
2795 | 2790 | del stored[aname] |
|
2796 | 2791 | self.db['stored_aliases'] = stored |
|
2797 | 2792 | |
|
2798 | 2793 | def magic_rehashx(self, parameter_s = ''): |
|
2799 | 2794 | """Update the alias table with all executable files in $PATH. |
|
2800 | 2795 | |
|
2801 | 2796 | This version explicitly checks that every entry in $PATH is a file |
|
2802 | 2797 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2803 | 2798 | |
|
2804 | 2799 | Under Windows, it checks executability as a match against a |
|
2805 | 2800 | '|'-separated string of extensions, stored in the IPython config |
|
2806 | 2801 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2807 | 2802 | |
|
2808 | 2803 | This function also resets the root module cache of module completer, |
|
2809 | 2804 | used on slow filesystems. |
|
2810 | 2805 | """ |
|
2811 | 2806 | from IPython.core.alias import InvalidAliasError |
|
2812 | 2807 | |
|
2813 | 2808 | # for the benefit of module completer in ipy_completers.py |
|
2814 | 2809 | del self.shell.db['rootmodules'] |
|
2815 | 2810 | |
|
2816 | 2811 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2817 | 2812 | os.environ.get('PATH','').split(os.pathsep)] |
|
2818 | 2813 | path = filter(os.path.isdir,path) |
|
2819 | 2814 | |
|
2820 | 2815 | syscmdlist = [] |
|
2821 | 2816 | # Now define isexec in a cross platform manner. |
|
2822 | 2817 | if os.name == 'posix': |
|
2823 | 2818 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2824 | 2819 | os.access(fname,os.X_OK) |
|
2825 | 2820 | else: |
|
2826 | 2821 | try: |
|
2827 | 2822 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2828 | 2823 | except KeyError: |
|
2829 | 2824 | winext = 'exe|com|bat|py' |
|
2830 | 2825 | if 'py' not in winext: |
|
2831 | 2826 | winext += '|py' |
|
2832 | 2827 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2833 | 2828 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2834 | 2829 | savedir = os.getcwdu() |
|
2835 | 2830 | |
|
2836 | 2831 | # Now walk the paths looking for executables to alias. |
|
2837 | 2832 | try: |
|
2838 | 2833 | # write the whole loop for posix/Windows so we don't have an if in |
|
2839 | 2834 | # the innermost part |
|
2840 | 2835 | if os.name == 'posix': |
|
2841 | 2836 | for pdir in path: |
|
2842 | 2837 | os.chdir(pdir) |
|
2843 | 2838 | for ff in os.listdir(pdir): |
|
2844 | 2839 | if isexec(ff): |
|
2845 | 2840 | try: |
|
2846 | 2841 | # Removes dots from the name since ipython |
|
2847 | 2842 | # will assume names with dots to be python. |
|
2848 | 2843 | self.shell.alias_manager.define_alias( |
|
2849 | 2844 | ff.replace('.',''), ff) |
|
2850 | 2845 | except InvalidAliasError: |
|
2851 | 2846 | pass |
|
2852 | 2847 | else: |
|
2853 | 2848 | syscmdlist.append(ff) |
|
2854 | 2849 | else: |
|
2855 | 2850 | no_alias = self.shell.alias_manager.no_alias |
|
2856 | 2851 | for pdir in path: |
|
2857 | 2852 | os.chdir(pdir) |
|
2858 | 2853 | for ff in os.listdir(pdir): |
|
2859 | 2854 | base, ext = os.path.splitext(ff) |
|
2860 | 2855 | if isexec(ff) and base.lower() not in no_alias: |
|
2861 | 2856 | if ext.lower() == '.exe': |
|
2862 | 2857 | ff = base |
|
2863 | 2858 | try: |
|
2864 | 2859 | # Removes dots from the name since ipython |
|
2865 | 2860 | # will assume names with dots to be python. |
|
2866 | 2861 | self.shell.alias_manager.define_alias( |
|
2867 | 2862 | base.lower().replace('.',''), ff) |
|
2868 | 2863 | except InvalidAliasError: |
|
2869 | 2864 | pass |
|
2870 | 2865 | syscmdlist.append(ff) |
|
2871 | 2866 | self.shell.db['syscmdlist'] = syscmdlist |
|
2872 | 2867 | finally: |
|
2873 | 2868 | os.chdir(savedir) |
|
2874 | 2869 | |
|
2875 | 2870 | @skip_doctest |
|
2876 | 2871 | def magic_pwd(self, parameter_s = ''): |
|
2877 | 2872 | """Return the current working directory path. |
|
2878 | 2873 | |
|
2879 | 2874 | Examples |
|
2880 | 2875 | -------- |
|
2881 | 2876 | :: |
|
2882 | 2877 | |
|
2883 | 2878 | In [9]: pwd |
|
2884 | 2879 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2885 | 2880 | """ |
|
2886 | 2881 | return os.getcwdu() |
|
2887 | 2882 | |
|
2888 | 2883 | @skip_doctest |
|
2889 | 2884 | def magic_cd(self, parameter_s=''): |
|
2890 | 2885 | """Change the current working directory. |
|
2891 | 2886 | |
|
2892 | 2887 | This command automatically maintains an internal list of directories |
|
2893 | 2888 | you visit during your IPython session, in the variable _dh. The |
|
2894 | 2889 | command %dhist shows this history nicely formatted. You can also |
|
2895 | 2890 | do 'cd -<tab>' to see directory history conveniently. |
|
2896 | 2891 | |
|
2897 | 2892 | Usage: |
|
2898 | 2893 | |
|
2899 | 2894 | cd 'dir': changes to directory 'dir'. |
|
2900 | 2895 | |
|
2901 | 2896 | cd -: changes to the last visited directory. |
|
2902 | 2897 | |
|
2903 | 2898 | cd -<n>: changes to the n-th directory in the directory history. |
|
2904 | 2899 | |
|
2905 | 2900 | cd --foo: change to directory that matches 'foo' in history |
|
2906 | 2901 | |
|
2907 | 2902 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2908 | 2903 | (note: cd <bookmark_name> is enough if there is no |
|
2909 | 2904 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2910 | 2905 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2911 | 2906 | |
|
2912 | 2907 | Options: |
|
2913 | 2908 | |
|
2914 | 2909 | -q: quiet. Do not print the working directory after the cd command is |
|
2915 | 2910 | executed. By default IPython's cd command does print this directory, |
|
2916 | 2911 | since the default prompts do not display path information. |
|
2917 | 2912 | |
|
2918 | 2913 | Note that !cd doesn't work for this purpose because the shell where |
|
2919 | 2914 | !command runs is immediately discarded after executing 'command'. |
|
2920 | 2915 | |
|
2921 | 2916 | Examples |
|
2922 | 2917 | -------- |
|
2923 | 2918 | :: |
|
2924 | 2919 | |
|
2925 | 2920 | In [10]: cd parent/child |
|
2926 | 2921 | /home/tsuser/parent/child |
|
2927 | 2922 | """ |
|
2928 | 2923 | |
|
2929 | 2924 | parameter_s = parameter_s.strip() |
|
2930 | 2925 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2931 | 2926 | |
|
2932 | 2927 | oldcwd = os.getcwdu() |
|
2933 | 2928 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2934 | 2929 | # jump in directory history by number |
|
2935 | 2930 | if numcd: |
|
2936 | 2931 | nn = int(numcd.group(2)) |
|
2937 | 2932 | try: |
|
2938 | 2933 | ps = self.shell.user_ns['_dh'][nn] |
|
2939 | 2934 | except IndexError: |
|
2940 | 2935 | print 'The requested directory does not exist in history.' |
|
2941 | 2936 | return |
|
2942 | 2937 | else: |
|
2943 | 2938 | opts = {} |
|
2944 | 2939 | elif parameter_s.startswith('--'): |
|
2945 | 2940 | ps = None |
|
2946 | 2941 | fallback = None |
|
2947 | 2942 | pat = parameter_s[2:] |
|
2948 | 2943 | dh = self.shell.user_ns['_dh'] |
|
2949 | 2944 | # first search only by basename (last component) |
|
2950 | 2945 | for ent in reversed(dh): |
|
2951 | 2946 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2952 | 2947 | ps = ent |
|
2953 | 2948 | break |
|
2954 | 2949 | |
|
2955 | 2950 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2956 | 2951 | fallback = ent |
|
2957 | 2952 | |
|
2958 | 2953 | # if we have no last part match, pick the first full path match |
|
2959 | 2954 | if ps is None: |
|
2960 | 2955 | ps = fallback |
|
2961 | 2956 | |
|
2962 | 2957 | if ps is None: |
|
2963 | 2958 | print "No matching entry in directory history" |
|
2964 | 2959 | return |
|
2965 | 2960 | else: |
|
2966 | 2961 | opts = {} |
|
2967 | 2962 | |
|
2968 | 2963 | |
|
2969 | 2964 | else: |
|
2970 | 2965 | #turn all non-space-escaping backslashes to slashes, |
|
2971 | 2966 | # for c:\windows\directory\names\ |
|
2972 | 2967 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2973 | 2968 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2974 | 2969 | # jump to previous |
|
2975 | 2970 | if ps == '-': |
|
2976 | 2971 | try: |
|
2977 | 2972 | ps = self.shell.user_ns['_dh'][-2] |
|
2978 | 2973 | except IndexError: |
|
2979 | 2974 | raise UsageError('%cd -: No previous directory to change to.') |
|
2980 | 2975 | # jump to bookmark if needed |
|
2981 | 2976 | else: |
|
2982 | 2977 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2983 | 2978 | bkms = self.db.get('bookmarks', {}) |
|
2984 | 2979 | |
|
2985 | 2980 | if bkms.has_key(ps): |
|
2986 | 2981 | target = bkms[ps] |
|
2987 | 2982 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2988 | 2983 | ps = target |
|
2989 | 2984 | else: |
|
2990 | 2985 | if opts.has_key('b'): |
|
2991 | 2986 | raise UsageError("Bookmark '%s' not found. " |
|
2992 | 2987 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2993 | 2988 | |
|
2994 | 2989 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
2995 | 2990 | ps = unquote_filename(ps) |
|
2996 | 2991 | # at this point ps should point to the target dir |
|
2997 | 2992 | if ps: |
|
2998 | 2993 | try: |
|
2999 | 2994 | os.chdir(os.path.expanduser(ps)) |
|
3000 | 2995 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
3001 | 2996 | set_term_title('IPython: ' + abbrev_cwd()) |
|
3002 | 2997 | except OSError: |
|
3003 | 2998 | print sys.exc_info()[1] |
|
3004 | 2999 | else: |
|
3005 | 3000 | cwd = os.getcwdu() |
|
3006 | 3001 | dhist = self.shell.user_ns['_dh'] |
|
3007 | 3002 | if oldcwd != cwd: |
|
3008 | 3003 | dhist.append(cwd) |
|
3009 | 3004 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3010 | 3005 | |
|
3011 | 3006 | else: |
|
3012 | 3007 | os.chdir(self.shell.home_dir) |
|
3013 | 3008 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
3014 | 3009 | set_term_title('IPython: ' + '~') |
|
3015 | 3010 | cwd = os.getcwdu() |
|
3016 | 3011 | dhist = self.shell.user_ns['_dh'] |
|
3017 | 3012 | |
|
3018 | 3013 | if oldcwd != cwd: |
|
3019 | 3014 | dhist.append(cwd) |
|
3020 | 3015 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3021 | 3016 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
3022 | 3017 | print self.shell.user_ns['_dh'][-1] |
|
3023 | 3018 | |
|
3024 | 3019 | |
|
3025 | 3020 | def magic_env(self, parameter_s=''): |
|
3026 | 3021 | """List environment variables.""" |
|
3027 | 3022 | |
|
3028 | 3023 | return os.environ.data |
|
3029 | 3024 | |
|
3030 | 3025 | def magic_pushd(self, parameter_s=''): |
|
3031 | 3026 | """Place the current dir on stack and change directory. |
|
3032 | 3027 | |
|
3033 | 3028 | Usage:\\ |
|
3034 | 3029 | %pushd ['dirname'] |
|
3035 | 3030 | """ |
|
3036 | 3031 | |
|
3037 | 3032 | dir_s = self.shell.dir_stack |
|
3038 | 3033 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
3039 | 3034 | cwd = os.getcwdu().replace(self.home_dir,'~') |
|
3040 | 3035 | if tgt: |
|
3041 | 3036 | self.magic_cd(parameter_s) |
|
3042 | 3037 | dir_s.insert(0,cwd) |
|
3043 | 3038 | return self.magic_dirs() |
|
3044 | 3039 | |
|
3045 | 3040 | def magic_popd(self, parameter_s=''): |
|
3046 | 3041 | """Change to directory popped off the top of the stack. |
|
3047 | 3042 | """ |
|
3048 | 3043 | if not self.shell.dir_stack: |
|
3049 | 3044 | raise UsageError("%popd on empty stack") |
|
3050 | 3045 | top = self.shell.dir_stack.pop(0) |
|
3051 | 3046 | self.magic_cd(top) |
|
3052 | 3047 | print "popd ->",top |
|
3053 | 3048 | |
|
3054 | 3049 | def magic_dirs(self, parameter_s=''): |
|
3055 | 3050 | """Return the current directory stack.""" |
|
3056 | 3051 | |
|
3057 | 3052 | return self.shell.dir_stack |
|
3058 | 3053 | |
|
3059 | 3054 | def magic_dhist(self, parameter_s=''): |
|
3060 | 3055 | """Print your history of visited directories. |
|
3061 | 3056 | |
|
3062 | 3057 | %dhist -> print full history\\ |
|
3063 | 3058 | %dhist n -> print last n entries only\\ |
|
3064 | 3059 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
3065 | 3060 | |
|
3066 | 3061 | This history is automatically maintained by the %cd command, and |
|
3067 | 3062 | always available as the global list variable _dh. You can use %cd -<n> |
|
3068 | 3063 | to go to directory number <n>. |
|
3069 | 3064 | |
|
3070 | 3065 | Note that most of time, you should view directory history by entering |
|
3071 | 3066 | cd -<TAB>. |
|
3072 | 3067 | |
|
3073 | 3068 | """ |
|
3074 | 3069 | |
|
3075 | 3070 | dh = self.shell.user_ns['_dh'] |
|
3076 | 3071 | if parameter_s: |
|
3077 | 3072 | try: |
|
3078 | 3073 | args = map(int,parameter_s.split()) |
|
3079 | 3074 | except: |
|
3080 | 3075 | self.arg_err(Magic.magic_dhist) |
|
3081 | 3076 | return |
|
3082 | 3077 | if len(args) == 1: |
|
3083 | 3078 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
3084 | 3079 | elif len(args) == 2: |
|
3085 | 3080 | ini,fin = args |
|
3086 | 3081 | else: |
|
3087 | 3082 | self.arg_err(Magic.magic_dhist) |
|
3088 | 3083 | return |
|
3089 | 3084 | else: |
|
3090 | 3085 | ini,fin = 0,len(dh) |
|
3091 | 3086 | nlprint(dh, |
|
3092 | 3087 | header = 'Directory history (kept in _dh)', |
|
3093 | 3088 | start=ini,stop=fin) |
|
3094 | 3089 | |
|
3095 | 3090 | @skip_doctest |
|
3096 | 3091 | def magic_sc(self, parameter_s=''): |
|
3097 | 3092 | """Shell capture - execute a shell command and capture its output. |
|
3098 | 3093 | |
|
3099 | 3094 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
3100 | 3095 | |
|
3101 | 3096 | You should use the form 'var = !command' instead. Example: |
|
3102 | 3097 | |
|
3103 | 3098 | "%sc -l myfiles = ls ~" should now be written as |
|
3104 | 3099 | |
|
3105 | 3100 | "myfiles = !ls ~" |
|
3106 | 3101 | |
|
3107 | 3102 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
3108 | 3103 | below. |
|
3109 | 3104 | |
|
3110 | 3105 | -- |
|
3111 | 3106 | %sc [options] varname=command |
|
3112 | 3107 | |
|
3113 | 3108 | IPython will run the given command using commands.getoutput(), and |
|
3114 | 3109 | will then update the user's interactive namespace with a variable |
|
3115 | 3110 | called varname, containing the value of the call. Your command can |
|
3116 | 3111 | contain shell wildcards, pipes, etc. |
|
3117 | 3112 | |
|
3118 | 3113 | The '=' sign in the syntax is mandatory, and the variable name you |
|
3119 | 3114 | supply must follow Python's standard conventions for valid names. |
|
3120 | 3115 | |
|
3121 | 3116 | (A special format without variable name exists for internal use) |
|
3122 | 3117 | |
|
3123 | 3118 | Options: |
|
3124 | 3119 | |
|
3125 | 3120 | -l: list output. Split the output on newlines into a list before |
|
3126 | 3121 | assigning it to the given variable. By default the output is stored |
|
3127 | 3122 | as a single string. |
|
3128 | 3123 | |
|
3129 | 3124 | -v: verbose. Print the contents of the variable. |
|
3130 | 3125 | |
|
3131 | 3126 | In most cases you should not need to split as a list, because the |
|
3132 | 3127 | returned value is a special type of string which can automatically |
|
3133 | 3128 | provide its contents either as a list (split on newlines) or as a |
|
3134 | 3129 | space-separated string. These are convenient, respectively, either |
|
3135 | 3130 | for sequential processing or to be passed to a shell command. |
|
3136 | 3131 | |
|
3137 | 3132 | For example:: |
|
3138 | 3133 | |
|
3139 | 3134 | # Capture into variable a |
|
3140 | 3135 | In [1]: sc a=ls *py |
|
3141 | 3136 | |
|
3142 | 3137 | # a is a string with embedded newlines |
|
3143 | 3138 | In [2]: a |
|
3144 | 3139 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3145 | 3140 | |
|
3146 | 3141 | # which can be seen as a list: |
|
3147 | 3142 | In [3]: a.l |
|
3148 | 3143 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3149 | 3144 | |
|
3150 | 3145 | # or as a whitespace-separated string: |
|
3151 | 3146 | In [4]: a.s |
|
3152 | 3147 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3153 | 3148 | |
|
3154 | 3149 | # a.s is useful to pass as a single command line: |
|
3155 | 3150 | In [5]: !wc -l $a.s |
|
3156 | 3151 | 146 setup.py |
|
3157 | 3152 | 130 win32_manual_post_install.py |
|
3158 | 3153 | 276 total |
|
3159 | 3154 | |
|
3160 | 3155 | # while the list form is useful to loop over: |
|
3161 | 3156 | In [6]: for f in a.l: |
|
3162 | 3157 | ...: !wc -l $f |
|
3163 | 3158 | ...: |
|
3164 | 3159 | 146 setup.py |
|
3165 | 3160 | 130 win32_manual_post_install.py |
|
3166 | 3161 | |
|
3167 | 3162 | Similarly, the lists returned by the -l option are also special, in |
|
3168 | 3163 | the sense that you can equally invoke the .s attribute on them to |
|
3169 | 3164 | automatically get a whitespace-separated string from their contents:: |
|
3170 | 3165 | |
|
3171 | 3166 | In [7]: sc -l b=ls *py |
|
3172 | 3167 | |
|
3173 | 3168 | In [8]: b |
|
3174 | 3169 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3175 | 3170 | |
|
3176 | 3171 | In [9]: b.s |
|
3177 | 3172 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3178 | 3173 | |
|
3179 | 3174 | In summary, both the lists and strings used for output capture have |
|
3180 | 3175 | the following special attributes:: |
|
3181 | 3176 | |
|
3182 | 3177 | .l (or .list) : value as list. |
|
3183 | 3178 | .n (or .nlstr): value as newline-separated string. |
|
3184 | 3179 | .s (or .spstr): value as space-separated string. |
|
3185 | 3180 | """ |
|
3186 | 3181 | |
|
3187 | 3182 | opts,args = self.parse_options(parameter_s,'lv') |
|
3188 | 3183 | # Try to get a variable name and command to run |
|
3189 | 3184 | try: |
|
3190 | 3185 | # the variable name must be obtained from the parse_options |
|
3191 | 3186 | # output, which uses shlex.split to strip options out. |
|
3192 | 3187 | var,_ = args.split('=',1) |
|
3193 | 3188 | var = var.strip() |
|
3194 | 3189 | # But the command has to be extracted from the original input |
|
3195 | 3190 | # parameter_s, not on what parse_options returns, to avoid the |
|
3196 | 3191 | # quote stripping which shlex.split performs on it. |
|
3197 | 3192 | _,cmd = parameter_s.split('=',1) |
|
3198 | 3193 | except ValueError: |
|
3199 | 3194 | var,cmd = '','' |
|
3200 | 3195 | # If all looks ok, proceed |
|
3201 | 3196 | split = 'l' in opts |
|
3202 | 3197 | out = self.shell.getoutput(cmd, split=split) |
|
3203 | 3198 | if opts.has_key('v'): |
|
3204 | 3199 | print '%s ==\n%s' % (var,pformat(out)) |
|
3205 | 3200 | if var: |
|
3206 | 3201 | self.shell.user_ns.update({var:out}) |
|
3207 | 3202 | else: |
|
3208 | 3203 | return out |
|
3209 | 3204 | |
|
3210 | 3205 | def magic_sx(self, parameter_s=''): |
|
3211 | 3206 | """Shell execute - run a shell command and capture its output. |
|
3212 | 3207 | |
|
3213 | 3208 | %sx command |
|
3214 | 3209 | |
|
3215 | 3210 | IPython will run the given command using commands.getoutput(), and |
|
3216 | 3211 | return the result formatted as a list (split on '\\n'). Since the |
|
3217 | 3212 | output is _returned_, it will be stored in ipython's regular output |
|
3218 | 3213 | cache Out[N] and in the '_N' automatic variables. |
|
3219 | 3214 | |
|
3220 | 3215 | Notes: |
|
3221 | 3216 | |
|
3222 | 3217 | 1) If an input line begins with '!!', then %sx is automatically |
|
3223 | 3218 | invoked. That is, while:: |
|
3224 | 3219 | |
|
3225 | 3220 | !ls |
|
3226 | 3221 | |
|
3227 | 3222 | causes ipython to simply issue system('ls'), typing:: |
|
3228 | 3223 | |
|
3229 | 3224 | !!ls |
|
3230 | 3225 | |
|
3231 | 3226 | is a shorthand equivalent to:: |
|
3232 | 3227 | |
|
3233 | 3228 | %sx ls |
|
3234 | 3229 | |
|
3235 | 3230 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3236 | 3231 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3237 | 3232 | to process line-oriented shell output via further python commands. |
|
3238 | 3233 | %sc is meant to provide much finer control, but requires more |
|
3239 | 3234 | typing. |
|
3240 | 3235 | |
|
3241 | 3236 | 3) Just like %sc -l, this is a list with special attributes: |
|
3242 | 3237 | :: |
|
3243 | 3238 | |
|
3244 | 3239 | .l (or .list) : value as list. |
|
3245 | 3240 | .n (or .nlstr): value as newline-separated string. |
|
3246 | 3241 | .s (or .spstr): value as whitespace-separated string. |
|
3247 | 3242 | |
|
3248 | 3243 | This is very useful when trying to use such lists as arguments to |
|
3249 | 3244 | system commands.""" |
|
3250 | 3245 | |
|
3251 | 3246 | if parameter_s: |
|
3252 | 3247 | return self.shell.getoutput(parameter_s) |
|
3253 | 3248 | |
|
3254 | 3249 | |
|
3255 | 3250 | def magic_bookmark(self, parameter_s=''): |
|
3256 | 3251 | """Manage IPython's bookmark system. |
|
3257 | 3252 | |
|
3258 | 3253 | %bookmark <name> - set bookmark to current dir |
|
3259 | 3254 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3260 | 3255 | %bookmark -l - list all bookmarks |
|
3261 | 3256 | %bookmark -d <name> - remove bookmark |
|
3262 | 3257 | %bookmark -r - remove all bookmarks |
|
3263 | 3258 | |
|
3264 | 3259 | You can later on access a bookmarked folder with:: |
|
3265 | 3260 | |
|
3266 | 3261 | %cd -b <name> |
|
3267 | 3262 | |
|
3268 | 3263 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3269 | 3264 | there is such a bookmark defined. |
|
3270 | 3265 | |
|
3271 | 3266 | Your bookmarks persist through IPython sessions, but they are |
|
3272 | 3267 | associated with each profile.""" |
|
3273 | 3268 | |
|
3274 | 3269 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3275 | 3270 | if len(args) > 2: |
|
3276 | 3271 | raise UsageError("%bookmark: too many arguments") |
|
3277 | 3272 | |
|
3278 | 3273 | bkms = self.db.get('bookmarks',{}) |
|
3279 | 3274 | |
|
3280 | 3275 | if opts.has_key('d'): |
|
3281 | 3276 | try: |
|
3282 | 3277 | todel = args[0] |
|
3283 | 3278 | except IndexError: |
|
3284 | 3279 | raise UsageError( |
|
3285 | 3280 | "%bookmark -d: must provide a bookmark to delete") |
|
3286 | 3281 | else: |
|
3287 | 3282 | try: |
|
3288 | 3283 | del bkms[todel] |
|
3289 | 3284 | except KeyError: |
|
3290 | 3285 | raise UsageError( |
|
3291 | 3286 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3292 | 3287 | |
|
3293 | 3288 | elif opts.has_key('r'): |
|
3294 | 3289 | bkms = {} |
|
3295 | 3290 | elif opts.has_key('l'): |
|
3296 | 3291 | bks = bkms.keys() |
|
3297 | 3292 | bks.sort() |
|
3298 | 3293 | if bks: |
|
3299 | 3294 | size = max(map(len,bks)) |
|
3300 | 3295 | else: |
|
3301 | 3296 | size = 0 |
|
3302 | 3297 | fmt = '%-'+str(size)+'s -> %s' |
|
3303 | 3298 | print 'Current bookmarks:' |
|
3304 | 3299 | for bk in bks: |
|
3305 | 3300 | print fmt % (bk,bkms[bk]) |
|
3306 | 3301 | else: |
|
3307 | 3302 | if not args: |
|
3308 | 3303 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3309 | 3304 | elif len(args)==1: |
|
3310 | 3305 | bkms[args[0]] = os.getcwdu() |
|
3311 | 3306 | elif len(args)==2: |
|
3312 | 3307 | bkms[args[0]] = args[1] |
|
3313 | 3308 | self.db['bookmarks'] = bkms |
|
3314 | 3309 | |
|
3315 | 3310 | def magic_pycat(self, parameter_s=''): |
|
3316 | 3311 | """Show a syntax-highlighted file through a pager. |
|
3317 | 3312 | |
|
3318 | 3313 | This magic is similar to the cat utility, but it will assume the file |
|
3319 | 3314 | to be Python source and will show it with syntax highlighting. """ |
|
3320 | 3315 | |
|
3321 | 3316 | try: |
|
3322 | 3317 | filename = get_py_filename(parameter_s) |
|
3323 | 3318 | cont = file_read(filename) |
|
3324 | 3319 | except IOError: |
|
3325 | 3320 | try: |
|
3326 | 3321 | cont = eval(parameter_s,self.user_ns) |
|
3327 | 3322 | except NameError: |
|
3328 | 3323 | cont = None |
|
3329 | 3324 | if cont is None: |
|
3330 | 3325 | print "Error: no such file or variable" |
|
3331 | 3326 | return |
|
3332 | 3327 | |
|
3333 | 3328 | page.page(self.shell.pycolorize(cont)) |
|
3334 | 3329 | |
|
3335 | 3330 | def magic_quickref(self,arg): |
|
3336 | 3331 | """ Show a quick reference sheet """ |
|
3337 | 3332 | import IPython.core.usage |
|
3338 | 3333 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3339 | 3334 | |
|
3340 | 3335 | page.page(qr) |
|
3341 | 3336 | |
|
3342 | 3337 | def magic_doctest_mode(self,parameter_s=''): |
|
3343 | 3338 | """Toggle doctest mode on and off. |
|
3344 | 3339 | |
|
3345 | 3340 | This mode is intended to make IPython behave as much as possible like a |
|
3346 | 3341 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3347 | 3342 | and output look. This makes it easy to copy and paste parts of a |
|
3348 | 3343 | session into doctests. It does so by: |
|
3349 | 3344 | |
|
3350 | 3345 | - Changing the prompts to the classic ``>>>`` ones. |
|
3351 | 3346 | - Changing the exception reporting mode to 'Plain'. |
|
3352 | 3347 | - Disabling pretty-printing of output. |
|
3353 | 3348 | |
|
3354 | 3349 | Note that IPython also supports the pasting of code snippets that have |
|
3355 | 3350 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3356 | 3351 | doctests from files or docstrings (even if they have leading |
|
3357 | 3352 | whitespace), and the code will execute correctly. You can then use |
|
3358 | 3353 | '%history -t' to see the translated history; this will give you the |
|
3359 | 3354 | input after removal of all the leading prompts and whitespace, which |
|
3360 | 3355 | can be pasted back into an editor. |
|
3361 | 3356 | |
|
3362 | 3357 | With these features, you can switch into this mode easily whenever you |
|
3363 | 3358 | need to do testing and changes to doctests, without having to leave |
|
3364 | 3359 | your existing IPython session. |
|
3365 | 3360 | """ |
|
3366 | 3361 | |
|
3367 | 3362 | from IPython.utils.ipstruct import Struct |
|
3368 | 3363 | |
|
3369 | 3364 | # Shorthands |
|
3370 | 3365 | shell = self.shell |
|
3371 | 3366 | pm = shell.prompt_manager |
|
3372 | 3367 | meta = shell.meta |
|
3373 | 3368 | disp_formatter = self.shell.display_formatter |
|
3374 | 3369 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3375 | 3370 | # dstore is a data store kept in the instance metadata bag to track any |
|
3376 | 3371 | # changes we make, so we can undo them later. |
|
3377 | 3372 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3378 | 3373 | save_dstore = dstore.setdefault |
|
3379 | 3374 | |
|
3380 | 3375 | # save a few values we'll need to recover later |
|
3381 | 3376 | mode = save_dstore('mode',False) |
|
3382 | 3377 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3383 | 3378 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3384 | 3379 | save_dstore('rc_separate_out',shell.separate_out) |
|
3385 | 3380 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3386 | 3381 | save_dstore('rc_prompts_pad_left',pm.justify) |
|
3387 | 3382 | save_dstore('rc_separate_in',shell.separate_in) |
|
3388 | 3383 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3389 | 3384 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) |
|
3390 | 3385 | |
|
3391 | 3386 | if mode == False: |
|
3392 | 3387 | # turn on |
|
3393 | 3388 | pm.in_template = '>>> ' |
|
3394 | 3389 | pm.in2_template = '... ' |
|
3395 | 3390 | pm.out_template = '' |
|
3396 | 3391 | |
|
3397 | 3392 | # Prompt separators like plain python |
|
3398 | 3393 | shell.separate_in = '' |
|
3399 | 3394 | shell.separate_out = '' |
|
3400 | 3395 | shell.separate_out2 = '' |
|
3401 | 3396 | |
|
3402 | 3397 | pm.justify = False |
|
3403 | 3398 | |
|
3404 | 3399 | ptformatter.pprint = False |
|
3405 | 3400 | disp_formatter.plain_text_only = True |
|
3406 | 3401 | |
|
3407 | 3402 | shell.magic_xmode('Plain') |
|
3408 | 3403 | else: |
|
3409 | 3404 | # turn off |
|
3410 | 3405 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates |
|
3411 | 3406 | |
|
3412 | 3407 | shell.separate_in = dstore.rc_separate_in |
|
3413 | 3408 | |
|
3414 | 3409 | shell.separate_out = dstore.rc_separate_out |
|
3415 | 3410 | shell.separate_out2 = dstore.rc_separate_out2 |
|
3416 | 3411 | |
|
3417 | 3412 | pm.justify = dstore.rc_prompts_pad_left |
|
3418 | 3413 | |
|
3419 | 3414 | ptformatter.pprint = dstore.rc_pprint |
|
3420 | 3415 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3421 | 3416 | |
|
3422 | 3417 | shell.magic_xmode(dstore.xmode) |
|
3423 | 3418 | |
|
3424 | 3419 | # Store new mode and inform |
|
3425 | 3420 | dstore.mode = bool(1-int(mode)) |
|
3426 | 3421 | mode_label = ['OFF','ON'][dstore.mode] |
|
3427 | 3422 | print 'Doctest mode is:', mode_label |
|
3428 | 3423 | |
|
3429 | 3424 | def magic_gui(self, parameter_s=''): |
|
3430 | 3425 | """Enable or disable IPython GUI event loop integration. |
|
3431 | 3426 | |
|
3432 | 3427 | %gui [GUINAME] |
|
3433 | 3428 | |
|
3434 | 3429 | This magic replaces IPython's threaded shells that were activated |
|
3435 | 3430 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3436 | 3431 | can now be enabled at runtime and keyboard |
|
3437 | 3432 | interrupts should work without any problems. The following toolkits |
|
3438 | 3433 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
3439 | 3434 | |
|
3440 | 3435 | %gui wx # enable wxPython event loop integration |
|
3441 | 3436 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3442 | 3437 | %gui gtk # enable PyGTK event loop integration |
|
3443 | 3438 | %gui tk # enable Tk event loop integration |
|
3444 | 3439 | %gui OSX # enable Cocoa event loop integration |
|
3445 | 3440 | # (requires %matplotlib 1.1) |
|
3446 | 3441 | %gui # disable all event loop integration |
|
3447 | 3442 | |
|
3448 | 3443 | WARNING: after any of these has been called you can simply create |
|
3449 | 3444 | an application object, but DO NOT start the event loop yourself, as |
|
3450 | 3445 | we have already handled that. |
|
3451 | 3446 | """ |
|
3452 | 3447 | opts, arg = self.parse_options(parameter_s, '') |
|
3453 | 3448 | if arg=='': arg = None |
|
3454 | 3449 | try: |
|
3455 | 3450 | return self.enable_gui(arg) |
|
3456 | 3451 | except Exception as e: |
|
3457 | 3452 | # print simple error message, rather than traceback if we can't |
|
3458 | 3453 | # hook up the GUI |
|
3459 | 3454 | error(str(e)) |
|
3460 | 3455 | |
|
3461 | 3456 | def magic_install_ext(self, parameter_s): |
|
3462 | 3457 | """Download and install an extension from a URL, e.g.:: |
|
3463 | 3458 | |
|
3464 | 3459 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py |
|
3465 | 3460 | |
|
3466 | 3461 | The URL should point to an importable Python module - either a .py file |
|
3467 | 3462 | or a .zip file. |
|
3468 | 3463 | |
|
3469 | 3464 | Parameters: |
|
3470 | 3465 | |
|
3471 | 3466 | -n filename : Specify a name for the file, rather than taking it from |
|
3472 | 3467 | the URL. |
|
3473 | 3468 | """ |
|
3474 | 3469 | opts, args = self.parse_options(parameter_s, 'n:') |
|
3475 | 3470 | try: |
|
3476 | 3471 | filename, headers = self.extension_manager.install_extension(args, opts.get('n')) |
|
3477 | 3472 | except ValueError as e: |
|
3478 | 3473 | print e |
|
3479 | 3474 | return |
|
3480 | 3475 | |
|
3481 | 3476 | filename = os.path.basename(filename) |
|
3482 | 3477 | print "Installed %s. To use it, type:" % filename |
|
3483 | 3478 | print " %%load_ext %s" % os.path.splitext(filename)[0] |
|
3484 | 3479 | |
|
3485 | 3480 | |
|
3486 | 3481 | def magic_load_ext(self, module_str): |
|
3487 | 3482 | """Load an IPython extension by its module name.""" |
|
3488 | 3483 | return self.extension_manager.load_extension(module_str) |
|
3489 | 3484 | |
|
3490 | 3485 | def magic_unload_ext(self, module_str): |
|
3491 | 3486 | """Unload an IPython extension by its module name.""" |
|
3492 | 3487 | self.extension_manager.unload_extension(module_str) |
|
3493 | 3488 | |
|
3494 | 3489 | def magic_reload_ext(self, module_str): |
|
3495 | 3490 | """Reload an IPython extension by its module name.""" |
|
3496 | 3491 | self.extension_manager.reload_extension(module_str) |
|
3497 | 3492 | |
|
3498 | 3493 | def magic_install_profiles(self, s): |
|
3499 | 3494 | """%install_profiles has been deprecated.""" |
|
3500 | 3495 | print '\n'.join([ |
|
3501 | 3496 | "%install_profiles has been deprecated.", |
|
3502 | 3497 | "Use `ipython profile list` to view available profiles.", |
|
3503 | 3498 | "Requesting a profile with `ipython profile create <name>`", |
|
3504 | 3499 | "or `ipython --profile=<name>` will start with the bundled", |
|
3505 | 3500 | "profile of that name if it exists." |
|
3506 | 3501 | ]) |
|
3507 | 3502 | |
|
3508 | 3503 | def magic_install_default_config(self, s): |
|
3509 | 3504 | """%install_default_config has been deprecated.""" |
|
3510 | 3505 | print '\n'.join([ |
|
3511 | 3506 | "%install_default_config has been deprecated.", |
|
3512 | 3507 | "Use `ipython profile create <name>` to initialize a profile", |
|
3513 | 3508 | "with the default config files.", |
|
3514 | 3509 | "Add `--reset` to overwrite already existing config files with defaults." |
|
3515 | 3510 | ]) |
|
3516 | 3511 | |
|
3517 | 3512 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3518 | 3513 | # handling and modify slightly %run |
|
3519 | 3514 | |
|
3520 | 3515 | @skip_doctest |
|
3521 | 3516 | def _pylab_magic_run(self, parameter_s=''): |
|
3522 | 3517 | Magic.magic_run(self, parameter_s, |
|
3523 | 3518 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3524 | 3519 | |
|
3525 | 3520 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3526 | 3521 | |
|
3527 | 3522 | @skip_doctest |
|
3528 | 3523 | def magic_pylab(self, s): |
|
3529 | 3524 | """Load numpy and matplotlib to work interactively. |
|
3530 | 3525 | |
|
3531 | 3526 | %pylab [GUINAME] |
|
3532 | 3527 | |
|
3533 | 3528 | This function lets you activate pylab (matplotlib, numpy and |
|
3534 | 3529 | interactive support) at any point during an IPython session. |
|
3535 | 3530 | |
|
3536 | 3531 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3537 | 3532 | pylab and mlab, as well as all names from numpy and pylab. |
|
3538 | 3533 | |
|
3539 | 3534 | If you are using the inline matplotlib backend for embedded figures, |
|
3540 | 3535 | you can adjust its behavior via the %config magic:: |
|
3541 | 3536 | |
|
3542 | 3537 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole |
|
3543 | 3538 | In [1]: %config InlineBackend.figure_format = 'svg' |
|
3544 | 3539 | |
|
3545 | 3540 | # change the behavior of closing all figures at the end of each |
|
3546 | 3541 | # execution (cell), or allowing reuse of active figures across |
|
3547 | 3542 | # cells: |
|
3548 | 3543 | In [2]: %config InlineBackend.close_figures = False |
|
3549 | 3544 | |
|
3550 | 3545 | Parameters |
|
3551 | 3546 | ---------- |
|
3552 | 3547 | guiname : optional |
|
3553 | 3548 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', |
|
3554 | 3549 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is |
|
3555 | 3550 | used, otherwise matplotlib's default (which you can override in your |
|
3556 | 3551 | matplotlib config file) is used. |
|
3557 | 3552 | |
|
3558 | 3553 | Examples |
|
3559 | 3554 | -------- |
|
3560 | 3555 | In this case, where the MPL default is TkAgg:: |
|
3561 | 3556 | |
|
3562 | 3557 | In [2]: %pylab |
|
3563 | 3558 | |
|
3564 | 3559 | Welcome to pylab, a matplotlib-based Python environment. |
|
3565 | 3560 | Backend in use: TkAgg |
|
3566 | 3561 | For more information, type 'help(pylab)'. |
|
3567 | 3562 | |
|
3568 | 3563 | But you can explicitly request a different backend:: |
|
3569 | 3564 | |
|
3570 | 3565 | In [3]: %pylab qt |
|
3571 | 3566 | |
|
3572 | 3567 | Welcome to pylab, a matplotlib-based Python environment. |
|
3573 | 3568 | Backend in use: Qt4Agg |
|
3574 | 3569 | For more information, type 'help(pylab)'. |
|
3575 | 3570 | """ |
|
3576 | 3571 | |
|
3577 | 3572 | if Application.initialized(): |
|
3578 | 3573 | app = Application.instance() |
|
3579 | 3574 | try: |
|
3580 | 3575 | import_all_status = app.pylab_import_all |
|
3581 | 3576 | except AttributeError: |
|
3582 | 3577 | import_all_status = True |
|
3583 | 3578 | else: |
|
3584 | 3579 | import_all_status = True |
|
3585 | 3580 | |
|
3586 | 3581 | self.shell.enable_pylab(s, import_all=import_all_status) |
|
3587 | 3582 | |
|
3588 | 3583 | def magic_tb(self, s): |
|
3589 | 3584 | """Print the last traceback with the currently active exception mode. |
|
3590 | 3585 | |
|
3591 | 3586 | See %xmode for changing exception reporting modes.""" |
|
3592 | 3587 | self.shell.showtraceback() |
|
3593 | 3588 | |
|
3594 | 3589 | @skip_doctest |
|
3595 | 3590 | def magic_precision(self, s=''): |
|
3596 | 3591 | """Set floating point precision for pretty printing. |
|
3597 | 3592 | |
|
3598 | 3593 | Can set either integer precision or a format string. |
|
3599 | 3594 | |
|
3600 | 3595 | If numpy has been imported and precision is an int, |
|
3601 | 3596 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3602 | 3597 | |
|
3603 | 3598 | If no argument is given, defaults will be restored. |
|
3604 | 3599 | |
|
3605 | 3600 | Examples |
|
3606 | 3601 | -------- |
|
3607 | 3602 | :: |
|
3608 | 3603 | |
|
3609 | 3604 | In [1]: from math import pi |
|
3610 | 3605 | |
|
3611 | 3606 | In [2]: %precision 3 |
|
3612 | 3607 | Out[2]: u'%.3f' |
|
3613 | 3608 | |
|
3614 | 3609 | In [3]: pi |
|
3615 | 3610 | Out[3]: 3.142 |
|
3616 | 3611 | |
|
3617 | 3612 | In [4]: %precision %i |
|
3618 | 3613 | Out[4]: u'%i' |
|
3619 | 3614 | |
|
3620 | 3615 | In [5]: pi |
|
3621 | 3616 | Out[5]: 3 |
|
3622 | 3617 | |
|
3623 | 3618 | In [6]: %precision %e |
|
3624 | 3619 | Out[6]: u'%e' |
|
3625 | 3620 | |
|
3626 | 3621 | In [7]: pi**10 |
|
3627 | 3622 | Out[7]: 9.364805e+04 |
|
3628 | 3623 | |
|
3629 | 3624 | In [8]: %precision |
|
3630 | 3625 | Out[8]: u'%r' |
|
3631 | 3626 | |
|
3632 | 3627 | In [9]: pi**10 |
|
3633 | 3628 | Out[9]: 93648.047476082982 |
|
3634 | 3629 | |
|
3635 | 3630 | """ |
|
3636 | 3631 | |
|
3637 | 3632 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3638 | 3633 | ptformatter.float_precision = s |
|
3639 | 3634 | return ptformatter.float_format |
|
3640 | 3635 | |
|
3641 | 3636 | |
|
3642 | 3637 | @magic_arguments.magic_arguments() |
|
3643 | 3638 | @magic_arguments.argument( |
|
3644 | 3639 | '-e', '--export', action='store_true', default=False, |
|
3645 | 3640 | help='Export IPython history as a notebook. The filename argument ' |
|
3646 | 3641 | 'is used to specify the notebook name and format. For example ' |
|
3647 | 3642 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
3648 | 3643 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
3649 | 3644 | 'or ".py" file extension will write the notebook in the json ' |
|
3650 | 3645 | 'or py formats.' |
|
3651 | 3646 | ) |
|
3652 | 3647 | @magic_arguments.argument( |
|
3653 | 3648 | '-f', '--format', |
|
3654 | 3649 | help='Convert an existing IPython notebook to a new format. This option ' |
|
3655 | 3650 | 'specifies the new format and can have the values: xml, json, py. ' |
|
3656 | 3651 | 'The target filename is chosen automatically based on the new ' |
|
3657 | 3652 | 'format. The filename argument gives the name of the source file.' |
|
3658 | 3653 | ) |
|
3659 | 3654 | @magic_arguments.argument( |
|
3660 | 3655 | 'filename', type=unicode, |
|
3661 | 3656 | help='Notebook name or filename' |
|
3662 | 3657 | ) |
|
3663 | 3658 | def magic_notebook(self, s): |
|
3664 | 3659 | """Export and convert IPython notebooks. |
|
3665 | 3660 | |
|
3666 | 3661 | This function can export the current IPython history to a notebook file |
|
3667 | 3662 | or can convert an existing notebook file into a different format. For |
|
3668 | 3663 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
3669 | 3664 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
3670 | 3665 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
3671 | 3666 | formats include (json/ipynb, py). |
|
3672 | 3667 | """ |
|
3673 | 3668 | args = magic_arguments.parse_argstring(self.magic_notebook, s) |
|
3674 | 3669 | |
|
3675 | 3670 | from IPython.nbformat import current |
|
3676 | 3671 | args.filename = unquote_filename(args.filename) |
|
3677 | 3672 | if args.export: |
|
3678 | 3673 | fname, name, format = current.parse_filename(args.filename) |
|
3679 | 3674 | cells = [] |
|
3680 | 3675 | hist = list(self.history_manager.get_range()) |
|
3681 | 3676 | for session, prompt_number, input in hist[:-1]: |
|
3682 | 3677 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) |
|
3683 | 3678 | worksheet = current.new_worksheet(cells=cells) |
|
3684 | 3679 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
3685 | 3680 | with open(fname, 'w') as f: |
|
3686 | 3681 | current.write(nb, f, format); |
|
3687 | 3682 | elif args.format is not None: |
|
3688 | 3683 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
3689 | 3684 | new_format = args.format |
|
3690 | 3685 | if new_format == u'xml': |
|
3691 | 3686 | raise ValueError('Notebooks cannot be written as xml.') |
|
3692 | 3687 | elif new_format == u'ipynb' or new_format == u'json': |
|
3693 | 3688 | new_fname = old_name + u'.ipynb' |
|
3694 | 3689 | new_format = u'json' |
|
3695 | 3690 | elif new_format == u'py': |
|
3696 | 3691 | new_fname = old_name + u'.py' |
|
3697 | 3692 | else: |
|
3698 | 3693 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
3699 | 3694 | with open(old_fname, 'r') as f: |
|
3700 | 3695 | s = f.read() |
|
3701 | 3696 | try: |
|
3702 | 3697 | nb = current.reads(s, old_format) |
|
3703 | 3698 | except: |
|
3704 | 3699 | nb = current.reads(s, u'xml') |
|
3705 | 3700 | with open(new_fname, 'w') as f: |
|
3706 | 3701 | current.write(nb, f, new_format) |
|
3707 | 3702 | |
|
3708 | 3703 | def magic_config(self, s): |
|
3709 | 3704 | """configure IPython |
|
3710 | 3705 | |
|
3711 | 3706 | %config Class[.trait=value] |
|
3712 | 3707 | |
|
3713 | 3708 | This magic exposes most of the IPython config system. Any |
|
3714 | 3709 | Configurable class should be able to be configured with the simple |
|
3715 | 3710 | line:: |
|
3716 | 3711 | |
|
3717 | 3712 | %config Class.trait=value |
|
3718 | 3713 | |
|
3719 | 3714 | Where `value` will be resolved in the user's namespace, if it is an |
|
3720 | 3715 | expression or variable name. |
|
3721 | 3716 | |
|
3722 | 3717 | Examples |
|
3723 | 3718 | -------- |
|
3724 | 3719 | |
|
3725 | 3720 | To see what classes are available for config, pass no arguments:: |
|
3726 | 3721 | |
|
3727 | 3722 | In [1]: %config |
|
3728 | 3723 | Available objects for config: |
|
3729 | 3724 | TerminalInteractiveShell |
|
3730 | 3725 | HistoryManager |
|
3731 | 3726 | PrefilterManager |
|
3732 | 3727 | AliasManager |
|
3733 | 3728 | IPCompleter |
|
3734 | 3729 | PromptManager |
|
3735 | 3730 | DisplayFormatter |
|
3736 | 3731 | |
|
3737 | 3732 | To view what is configurable on a given class, just pass the class |
|
3738 | 3733 | name:: |
|
3739 | 3734 | |
|
3740 | 3735 | In [2]: %config IPCompleter |
|
3741 | 3736 | IPCompleter options |
|
3742 | 3737 | ----------------- |
|
3743 | 3738 | IPCompleter.omit__names=<Enum> |
|
3744 | 3739 | Current: 2 |
|
3745 | 3740 | Choices: (0, 1, 2) |
|
3746 | 3741 | Instruct the completer to omit private method names |
|
3747 | 3742 | Specifically, when completing on ``object.<tab>``. |
|
3748 | 3743 | When 2 [default]: all names that start with '_' will be excluded. |
|
3749 | 3744 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
3750 | 3745 | When 0: nothing will be excluded. |
|
3751 | 3746 | IPCompleter.merge_completions=<CBool> |
|
3752 | 3747 | Current: True |
|
3753 | 3748 | Whether to merge completion results into a single list |
|
3754 | 3749 | If False, only the completion results from the first non-empty completer |
|
3755 | 3750 | will be returned. |
|
3756 | 3751 | IPCompleter.greedy=<CBool> |
|
3757 | 3752 | Current: False |
|
3758 | 3753 | Activate greedy completion |
|
3759 | 3754 | This will enable completion on elements of lists, results of function calls, |
|
3760 | 3755 | etc., but can be unsafe because the code is actually evaluated on TAB. |
|
3761 | 3756 | |
|
3762 | 3757 | but the real use is in setting values:: |
|
3763 | 3758 | |
|
3764 | 3759 | In [3]: %config IPCompleter.greedy = True |
|
3765 | 3760 | |
|
3766 | 3761 | and these values are read from the user_ns if they are variables:: |
|
3767 | 3762 | |
|
3768 | 3763 | In [4]: feeling_greedy=False |
|
3769 | 3764 | |
|
3770 | 3765 | In [5]: %config IPCompleter.greedy = feeling_greedy |
|
3771 | 3766 | |
|
3772 | 3767 | """ |
|
3773 | 3768 | from IPython.config.loader import Config |
|
3774 | 3769 | # some IPython objects are Configurable, but do not yet have |
|
3775 | 3770 | # any configurable traits. Exclude them from the effects of |
|
3776 | 3771 | # this magic, as their presence is just noise: |
|
3777 | 3772 | configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ] |
|
3778 | 3773 | classnames = [ c.__class__.__name__ for c in configurables ] |
|
3779 | 3774 | |
|
3780 | 3775 | line = s.strip() |
|
3781 | 3776 | if not line: |
|
3782 | 3777 | # print available configurable names |
|
3783 | 3778 | print "Available objects for config:" |
|
3784 | 3779 | for name in classnames: |
|
3785 | 3780 | print " ", name |
|
3786 | 3781 | return |
|
3787 | 3782 | elif line in classnames: |
|
3788 | 3783 | # `%config TerminalInteractiveShell` will print trait info for |
|
3789 | 3784 | # TerminalInteractiveShell |
|
3790 | 3785 | c = configurables[classnames.index(line)] |
|
3791 | 3786 | cls = c.__class__ |
|
3792 | 3787 | help = cls.class_get_help(c) |
|
3793 | 3788 | # strip leading '--' from cl-args: |
|
3794 | 3789 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
3795 | 3790 | print help |
|
3796 | 3791 | return |
|
3797 | 3792 | elif '=' not in line: |
|
3798 | 3793 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) |
|
3799 | 3794 | |
|
3800 | 3795 | |
|
3801 | 3796 | # otherwise, assume we are setting configurables. |
|
3802 | 3797 | # leave quotes on args when splitting, because we want |
|
3803 | 3798 | # unquoted args to eval in user_ns |
|
3804 | 3799 | cfg = Config() |
|
3805 | 3800 | exec "cfg."+line in locals(), self.user_ns |
|
3806 | 3801 | |
|
3807 | 3802 | for configurable in configurables: |
|
3808 | 3803 | try: |
|
3809 | 3804 | configurable.update_config(cfg) |
|
3810 | 3805 | except Exception as e: |
|
3811 | 3806 | error(e) |
|
3812 | 3807 | |
|
3813 | 3808 | # end Magic |
@@ -1,174 +1,174 b'' | |||
|
1 | 1 | """Manage IPython.parallel clusters in the notebook. |
|
2 | 2 | |
|
3 | 3 | Authors: |
|
4 | 4 | |
|
5 | 5 | * Brian Granger |
|
6 | 6 | """ |
|
7 | 7 | |
|
8 | 8 | #----------------------------------------------------------------------------- |
|
9 | 9 | # Copyright (C) 2008-2011 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | import os |
|
20 | 20 | |
|
21 | 21 | from tornado import web |
|
22 | 22 | from zmq.eventloop import ioloop |
|
23 | 23 | |
|
24 | 24 | from IPython.config.configurable import LoggingConfigurable |
|
25 | 25 | from IPython.config.loader import load_pyconfig_files |
|
26 | 26 | from IPython.utils.traitlets import Dict, Instance, CFloat |
|
27 | 27 | from IPython.parallel.apps.ipclusterapp import IPClusterStart |
|
28 | 28 | from IPython.core.profileapp import list_profiles_in |
|
29 | 29 | from IPython.core.profiledir import ProfileDir |
|
30 | 30 | from IPython.utils.path import get_ipython_dir |
|
31 | 31 | from IPython.utils.sysinfo import num_cpus |
|
32 | 32 | |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Classes |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | class DummyIPClusterStart(IPClusterStart): |
|
40 | 40 | """Dummy subclass to skip init steps that conflict with global app. |
|
41 | 41 | |
|
42 | 42 | Instantiating and initializing this class should result in fully configured |
|
43 | 43 | launchers, but no other side effects or state. |
|
44 | 44 | """ |
|
45 | 45 | |
|
46 | 46 | def init_signal(self): |
|
47 | 47 | pass |
|
48 | 48 | def init_logging(self): |
|
49 | 49 | pass |
|
50 | 50 | def reinit_logging(self): |
|
51 | 51 | pass |
|
52 | 52 | |
|
53 | 53 | |
|
54 | 54 | class ClusterManager(LoggingConfigurable): |
|
55 | 55 | |
|
56 | 56 | profiles = Dict() |
|
57 | 57 | |
|
58 | 58 | delay = CFloat(1., config=True, |
|
59 | 59 | help="delay (in s) between starting the controller and the engines") |
|
60 | 60 | |
|
61 | 61 | loop = Instance('zmq.eventloop.ioloop.IOLoop') |
|
62 | 62 | def _loop_default(self): |
|
63 | 63 | from zmq.eventloop.ioloop import IOLoop |
|
64 | 64 | return IOLoop.instance() |
|
65 | 65 | |
|
66 | 66 | def build_launchers(self, profile_dir): |
|
67 | 67 | starter = DummyIPClusterStart(log=self.log) |
|
68 | 68 | starter.initialize(['--profile-dir', profile_dir]) |
|
69 | 69 | cl = starter.controller_launcher |
|
70 | 70 | esl = starter.engine_launcher |
|
71 | 71 | n = starter.n |
|
72 | 72 | return cl, esl, n |
|
73 | 73 | |
|
74 | 74 | def get_profile_dir(self, name, path): |
|
75 | 75 | p = ProfileDir.find_profile_dir_by_name(path,name=name) |
|
76 | 76 | return p.location |
|
77 | 77 | |
|
78 | 78 | def update_profiles(self): |
|
79 | 79 | """List all profiles in the ipython_dir and cwd. |
|
80 | 80 | """ |
|
81 | 81 | for path in [get_ipython_dir(), os.getcwdu()]: |
|
82 | 82 | for profile in list_profiles_in(path): |
|
83 | 83 | pd = self.get_profile_dir(profile, path) |
|
84 | 84 | if profile not in self.profiles: |
|
85 | 85 | self.log.debug("Overwriting profile %s" % profile) |
|
86 | 86 | self.profiles[profile] = { |
|
87 | 87 | 'profile': profile, |
|
88 | 88 | 'profile_dir': pd, |
|
89 | 89 | 'status': 'stopped' |
|
90 | 90 | } |
|
91 | 91 | |
|
92 | 92 | def list_profiles(self): |
|
93 | 93 | self.update_profiles() |
|
94 | 94 | result = [self.profile_info(p) for p in sorted(self.profiles.keys())] |
|
95 | 95 | return result |
|
96 | 96 | |
|
97 | 97 | def check_profile(self, profile): |
|
98 | 98 | if profile not in self.profiles: |
|
99 | 99 | raise web.HTTPError(404, u'profile not found') |
|
100 | 100 | |
|
101 | 101 | def profile_info(self, profile): |
|
102 | 102 | self.check_profile(profile) |
|
103 | 103 | result = {} |
|
104 | 104 | data = self.profiles.get(profile) |
|
105 | 105 | result['profile'] = profile |
|
106 | 106 | result['profile_dir'] = data['profile_dir'] |
|
107 | 107 | result['status'] = data['status'] |
|
108 | 108 | if 'n' in data: |
|
109 | 109 | result['n'] = data['n'] |
|
110 | 110 | return result |
|
111 | 111 | |
|
112 | 112 | def start_cluster(self, profile, n=None): |
|
113 | 113 | """Start a cluster for a given profile.""" |
|
114 | 114 | self.check_profile(profile) |
|
115 | 115 | data = self.profiles[profile] |
|
116 | 116 | if data['status'] == 'running': |
|
117 | 117 | raise web.HTTPError(409, u'cluster already running') |
|
118 | 118 | cl, esl, default_n = self.build_launchers(data['profile_dir']) |
|
119 | 119 | n = n if n is not None else default_n |
|
120 | 120 | def clean_data(): |
|
121 | 121 | data.pop('controller_launcher',None) |
|
122 | 122 | data.pop('engine_set_launcher',None) |
|
123 | 123 | data.pop('n',None) |
|
124 | 124 | data['status'] = 'stopped' |
|
125 | 125 | def engines_stopped(r): |
|
126 | 126 | self.log.debug('Engines stopped') |
|
127 | 127 | if cl.running: |
|
128 | 128 | cl.stop() |
|
129 | 129 | clean_data() |
|
130 | 130 | esl.on_stop(engines_stopped) |
|
131 | 131 | def controller_stopped(r): |
|
132 | 132 | self.log.debug('Controller stopped') |
|
133 | 133 | if esl.running: |
|
134 | 134 | esl.stop() |
|
135 | 135 | clean_data() |
|
136 | 136 | cl.on_stop(controller_stopped) |
|
137 | 137 | |
|
138 | 138 | dc = ioloop.DelayedCallback(lambda: cl.start(), 0, self.loop) |
|
139 | 139 | dc.start() |
|
140 | 140 | dc = ioloop.DelayedCallback(lambda: esl.start(n), 1000*self.delay, self.loop) |
|
141 | 141 | dc.start() |
|
142 | 142 | |
|
143 | 143 | self.log.debug('Cluster started') |
|
144 | 144 | data['controller_launcher'] = cl |
|
145 | 145 | data['engine_set_launcher'] = esl |
|
146 | 146 | data['n'] = n |
|
147 | 147 | data['status'] = 'running' |
|
148 | 148 | return self.profile_info(profile) |
|
149 | 149 | |
|
150 | 150 | def stop_cluster(self, profile): |
|
151 | 151 | """Stop a cluster for a given profile.""" |
|
152 | 152 | self.check_profile(profile) |
|
153 | 153 | data = self.profiles[profile] |
|
154 | 154 | if data['status'] == 'stopped': |
|
155 | 155 | raise web.HTTPError(409, u'cluster not running') |
|
156 | 156 | data = self.profiles[profile] |
|
157 | 157 | cl = data['controller_launcher'] |
|
158 | 158 | esl = data['engine_set_launcher'] |
|
159 | 159 | if cl.running: |
|
160 | 160 | cl.stop() |
|
161 | 161 | if esl.running: |
|
162 | 162 | esl.stop() |
|
163 | 163 | # Return a temp info dict, the real one is updated in the on_stop |
|
164 | 164 | # logic above. |
|
165 | 165 | result = { |
|
166 | 166 | 'profile': data['profile'], |
|
167 | 167 | 'profile_dir': data['profile_dir'], |
|
168 | 168 | 'status': 'stopped' |
|
169 | 169 | } |
|
170 | 170 | return result |
|
171 | 171 | |
|
172 | 172 | def stop_all_clusters(self): |
|
173 | 173 | for p in self.profiles.keys(): |
|
174 |
self.stop_cluster(p |
|
|
174 | self.stop_cluster(p) |
@@ -1,668 +1,668 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Subclass of InteractiveShell for terminal based frontends.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import __builtin__ |
|
18 | 18 | import bdb |
|
19 | 19 | import os |
|
20 | 20 | import re |
|
21 | 21 | import sys |
|
22 | 22 | import textwrap |
|
23 | 23 | |
|
24 | 24 | try: |
|
25 | 25 | from contextlib import nested |
|
26 | 26 | except: |
|
27 | 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 | 30 | from IPython.core.usage import interactive_usage, default_banner |
|
31 | 31 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
32 | 32 | from IPython.core.pylabtools import pylab_activate |
|
33 | 33 | from IPython.testing.skipdoctest import skip_doctest |
|
34 | 34 | from IPython.utils import py3compat |
|
35 | 35 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
36 | 36 | from IPython.utils.process import abbrev_cwd |
|
37 | 37 | from IPython.utils.warn import warn, error |
|
38 | 38 | from IPython.utils.text import num_ini_spaces, SList |
|
39 | 39 | from IPython.utils.traitlets import Integer, CBool, Unicode |
|
40 | 40 | |
|
41 | 41 | #----------------------------------------------------------------------------- |
|
42 | 42 | # Utilities |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | |
|
45 | 45 | def get_default_editor(): |
|
46 | 46 | try: |
|
47 | 47 | ed = os.environ['EDITOR'] |
|
48 | 48 | except KeyError: |
|
49 | 49 | if os.name == 'posix': |
|
50 | 50 | ed = 'vi' # the only one guaranteed to be there! |
|
51 | 51 | else: |
|
52 | 52 | ed = 'notepad' # same in Windows! |
|
53 | 53 | return ed |
|
54 | 54 | |
|
55 | 55 | |
|
56 | 56 | def get_pasted_lines(sentinel, l_input=py3compat.input): |
|
57 | 57 | """ Yield pasted lines until the user enters the given sentinel value. |
|
58 | 58 | """ |
|
59 | 59 | print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ |
|
60 | 60 | % sentinel |
|
61 | 61 | while True: |
|
62 | 62 | try: |
|
63 | 63 | l = l_input(':') |
|
64 | 64 | if l == sentinel: |
|
65 | 65 | return |
|
66 | 66 | else: |
|
67 | 67 | yield l |
|
68 | 68 | except EOFError: |
|
69 | 69 | print '<EOF>' |
|
70 | 70 | return |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | def strip_email_quotes(raw_lines): |
|
74 | 74 | """ Strip email quotation marks at the beginning of each line. |
|
75 | 75 | |
|
76 | 76 | We don't do any more input transofrmations here because the main shell's |
|
77 | 77 | prefiltering handles other cases. |
|
78 | 78 | """ |
|
79 | 79 | lines = [re.sub(r'^\s*(\s?>)+', '', l) for l in raw_lines] |
|
80 | 80 | return '\n'.join(lines) + '\n' |
|
81 | 81 | |
|
82 | 82 | |
|
83 | 83 | # These two functions are needed by the %paste/%cpaste magics. In practice |
|
84 | 84 | # they are basically methods (they take the shell as their first argument), but |
|
85 | 85 | # we leave them as standalone functions because eventually the magics |
|
86 | 86 | # themselves will become separate objects altogether. At that point, the |
|
87 | 87 | # magics will have access to the shell object, and these functions can be made |
|
88 | 88 | # methods of the magic object, but not of the shell. |
|
89 | 89 | |
|
90 | 90 | def store_or_execute(shell, block, name): |
|
91 | 91 | """ Execute a block, or store it in a variable, per the user's request. |
|
92 | 92 | """ |
|
93 | 93 | # Dedent and prefilter so what we store matches what is executed by |
|
94 | 94 | # run_cell. |
|
95 | 95 | b = shell.prefilter(textwrap.dedent(block)) |
|
96 | 96 | |
|
97 | 97 | if name: |
|
98 | 98 | # If storing it for further editing, run the prefilter on it |
|
99 | 99 | shell.user_ns[name] = SList(b.splitlines()) |
|
100 | 100 | print "Block assigned to '%s'" % name |
|
101 | 101 | else: |
|
102 | 102 | shell.user_ns['pasted_block'] = b |
|
103 | 103 | shell.run_cell(b) |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | def rerun_pasted(shell, name='pasted_block'): |
|
107 | 107 | """ Rerun a previously pasted command. |
|
108 | 108 | """ |
|
109 | 109 | b = shell.user_ns.get(name) |
|
110 | 110 | |
|
111 | 111 | # Sanity checks |
|
112 | 112 | if b is None: |
|
113 | 113 | raise UsageError('No previous pasted block available') |
|
114 | 114 | if not isinstance(b, basestring): |
|
115 | 115 | raise UsageError( |
|
116 | 116 | "Variable 'pasted_block' is not a string, can't execute") |
|
117 | 117 | |
|
118 | 118 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
119 | 119 | shell.run_cell(b) |
|
120 | 120 | |
|
121 | 121 | |
|
122 | 122 | #----------------------------------------------------------------------------- |
|
123 | 123 | # Main class |
|
124 | 124 | #----------------------------------------------------------------------------- |
|
125 | 125 | |
|
126 | 126 | class TerminalInteractiveShell(InteractiveShell): |
|
127 | 127 | |
|
128 | 128 | autoedit_syntax = CBool(False, config=True, |
|
129 | 129 | help="auto editing of files with syntax errors.") |
|
130 | 130 | banner = Unicode('') |
|
131 | 131 | banner1 = Unicode(default_banner, config=True, |
|
132 | 132 | help="""The part of the banner to be printed before the profile""" |
|
133 | 133 | ) |
|
134 | 134 | banner2 = Unicode('', config=True, |
|
135 | 135 | help="""The part of the banner to be printed after the profile""" |
|
136 | 136 | ) |
|
137 | 137 | confirm_exit = CBool(True, config=True, |
|
138 | 138 | help=""" |
|
139 | 139 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
140 | 140 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
141 | 141 | you can force a direct exit without any confirmation.""", |
|
142 | 142 | ) |
|
143 | 143 | # This display_banner only controls whether or not self.show_banner() |
|
144 | 144 | # is called when mainloop/interact are called. The default is False |
|
145 | 145 | # because for the terminal based application, the banner behavior |
|
146 | 146 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
147 | 147 | # to determine if *it* should call show_banner() by hand or not. |
|
148 | 148 | display_banner = CBool(False) # This isn't configurable! |
|
149 | 149 | embedded = CBool(False) |
|
150 | 150 | embedded_active = CBool(False) |
|
151 | 151 | editor = Unicode(get_default_editor(), config=True, |
|
152 | 152 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
153 | 153 | ) |
|
154 | 154 | pager = Unicode('less', config=True, |
|
155 | 155 | help="The shell program to be used for paging.") |
|
156 | 156 | |
|
157 | 157 | screen_length = Integer(0, config=True, |
|
158 | 158 | help= |
|
159 | 159 | """Number of lines of your screen, used to control printing of very |
|
160 | 160 | long strings. Strings longer than this number of lines will be sent |
|
161 | 161 | through a pager instead of directly printed. The default value for |
|
162 | 162 | this is 0, which means IPython will auto-detect your screen size every |
|
163 | 163 | time it needs to print certain potentially long strings (this doesn't |
|
164 | 164 | change the behavior of the 'print' keyword, it's only triggered |
|
165 | 165 | internally). If for some reason this isn't working well (it needs |
|
166 | 166 | curses support), specify it yourself. Otherwise don't change the |
|
167 | 167 | default.""", |
|
168 | 168 | ) |
|
169 | 169 | term_title = CBool(False, config=True, |
|
170 | 170 | help="Enable auto setting the terminal title." |
|
171 | 171 | ) |
|
172 | 172 | |
|
173 | 173 | # In the terminal, GUI control is done via PyOS_InputHook |
|
174 | 174 | from IPython.lib.inputhook import enable_gui |
|
175 | 175 | enable_gui = staticmethod(enable_gui) |
|
176 | 176 | |
|
177 | 177 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, |
|
178 | 178 | user_ns=None, user_module=None, custom_exceptions=((),None), |
|
179 | 179 | usage=None, banner1=None, banner2=None, display_banner=None): |
|
180 | 180 | |
|
181 | 181 | super(TerminalInteractiveShell, self).__init__( |
|
182 | 182 | config=config, profile_dir=profile_dir, user_ns=user_ns, |
|
183 | 183 | user_module=user_module, custom_exceptions=custom_exceptions |
|
184 | 184 | ) |
|
185 | 185 | # use os.system instead of utils.process.system by default, |
|
186 | 186 | # because piped system doesn't make sense in the Terminal: |
|
187 | 187 | self.system = self.system_raw |
|
188 | 188 | |
|
189 | 189 | self.init_term_title() |
|
190 | 190 | self.init_usage(usage) |
|
191 | 191 | self.init_banner(banner1, banner2, display_banner) |
|
192 | 192 | |
|
193 | 193 | #------------------------------------------------------------------------- |
|
194 | 194 | # Things related to the terminal |
|
195 | 195 | #------------------------------------------------------------------------- |
|
196 | 196 | |
|
197 | 197 | @property |
|
198 | 198 | def usable_screen_length(self): |
|
199 | 199 | if self.screen_length == 0: |
|
200 | 200 | return 0 |
|
201 | 201 | else: |
|
202 | 202 | num_lines_bot = self.separate_in.count('\n')+1 |
|
203 | 203 | return self.screen_length - num_lines_bot |
|
204 | 204 | |
|
205 | 205 | def init_term_title(self): |
|
206 | 206 | # Enable or disable the terminal title. |
|
207 | 207 | if self.term_title: |
|
208 | 208 | toggle_set_term_title(True) |
|
209 | 209 | set_term_title('IPython: ' + abbrev_cwd()) |
|
210 | 210 | else: |
|
211 | 211 | toggle_set_term_title(False) |
|
212 | 212 | |
|
213 | 213 | #------------------------------------------------------------------------- |
|
214 | 214 | # Things related to aliases |
|
215 | 215 | #------------------------------------------------------------------------- |
|
216 | 216 | |
|
217 | 217 | def init_alias(self): |
|
218 | 218 | # The parent class defines aliases that can be safely used with any |
|
219 | 219 | # frontend. |
|
220 | 220 | super(TerminalInteractiveShell, self).init_alias() |
|
221 | 221 | |
|
222 | 222 | # Now define aliases that only make sense on the terminal, because they |
|
223 | 223 | # need direct access to the console in a way that we can't emulate in |
|
224 | 224 | # GUI or web frontend |
|
225 | 225 | if os.name == 'posix': |
|
226 | 226 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), |
|
227 | 227 | ('man', 'man')] |
|
228 | 228 | elif os.name == 'nt': |
|
229 | 229 | aliases = [('cls', 'cls')] |
|
230 | 230 | |
|
231 | 231 | |
|
232 | 232 | for name, cmd in aliases: |
|
233 | 233 | self.alias_manager.define_alias(name, cmd) |
|
234 | 234 | |
|
235 | 235 | #------------------------------------------------------------------------- |
|
236 | 236 | # Things related to the banner and usage |
|
237 | 237 | #------------------------------------------------------------------------- |
|
238 | 238 | |
|
239 | 239 | def _banner1_changed(self): |
|
240 | 240 | self.compute_banner() |
|
241 | 241 | |
|
242 | 242 | def _banner2_changed(self): |
|
243 | 243 | self.compute_banner() |
|
244 | 244 | |
|
245 | 245 | def _term_title_changed(self, name, new_value): |
|
246 | 246 | self.init_term_title() |
|
247 | 247 | |
|
248 | 248 | def init_banner(self, banner1, banner2, display_banner): |
|
249 | 249 | if banner1 is not None: |
|
250 | 250 | self.banner1 = banner1 |
|
251 | 251 | if banner2 is not None: |
|
252 | 252 | self.banner2 = banner2 |
|
253 | 253 | if display_banner is not None: |
|
254 | 254 | self.display_banner = display_banner |
|
255 | 255 | self.compute_banner() |
|
256 | 256 | |
|
257 | 257 | def show_banner(self, banner=None): |
|
258 | 258 | if banner is None: |
|
259 | 259 | banner = self.banner |
|
260 | 260 | self.write(banner) |
|
261 | 261 | |
|
262 | 262 | def compute_banner(self): |
|
263 | 263 | self.banner = self.banner1 |
|
264 | 264 | if self.profile and self.profile != 'default': |
|
265 | 265 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
266 | 266 | if self.banner2: |
|
267 | 267 | self.banner += '\n' + self.banner2 |
|
268 | 268 | |
|
269 | 269 | def init_usage(self, usage=None): |
|
270 | 270 | if usage is None: |
|
271 | 271 | self.usage = interactive_usage |
|
272 | 272 | else: |
|
273 | 273 | self.usage = usage |
|
274 | 274 | |
|
275 | 275 | #------------------------------------------------------------------------- |
|
276 | 276 | # Mainloop and code execution logic |
|
277 | 277 | #------------------------------------------------------------------------- |
|
278 | 278 | |
|
279 | 279 | def mainloop(self, display_banner=None): |
|
280 | 280 | """Start the mainloop. |
|
281 | 281 | |
|
282 | 282 | If an optional banner argument is given, it will override the |
|
283 | 283 | internally created default banner. |
|
284 | 284 | """ |
|
285 | 285 | |
|
286 | 286 | with nested(self.builtin_trap, self.display_trap): |
|
287 | 287 | |
|
288 | 288 | while 1: |
|
289 | 289 | try: |
|
290 | 290 | self.interact(display_banner=display_banner) |
|
291 | 291 | #self.interact_with_readline() |
|
292 | 292 | # XXX for testing of a readline-decoupled repl loop, call |
|
293 | 293 | # interact_with_readline above |
|
294 | 294 | break |
|
295 | 295 | except KeyboardInterrupt: |
|
296 | 296 | # this should not be necessary, but KeyboardInterrupt |
|
297 | 297 | # handling seems rather unpredictable... |
|
298 | 298 | self.write("\nKeyboardInterrupt in interact()\n") |
|
299 | 299 | |
|
300 | 300 | def _replace_rlhist_multiline(self, source_raw, hlen_before_cell): |
|
301 | 301 | """Store multiple lines as a single entry in history""" |
|
302 | 302 | |
|
303 | 303 | # do nothing without readline or disabled multiline |
|
304 | 304 | if not self.has_readline or not self.multiline_history: |
|
305 | 305 | return hlen_before_cell |
|
306 | 306 | |
|
307 | 307 | # windows rl has no remove_history_item |
|
308 | 308 | if not hasattr(self.readline, "remove_history_item"): |
|
309 | 309 | return hlen_before_cell |
|
310 | 310 | |
|
311 | 311 | # skip empty cells |
|
312 | 312 | if not source_raw.rstrip(): |
|
313 | 313 | return hlen_before_cell |
|
314 | 314 | |
|
315 | 315 | # nothing changed do nothing, e.g. when rl removes consecutive dups |
|
316 | 316 | hlen = self.readline.get_current_history_length() |
|
317 | 317 | if hlen == hlen_before_cell: |
|
318 | 318 | return hlen_before_cell |
|
319 | 319 | |
|
320 | 320 | for i in range(hlen - hlen_before_cell): |
|
321 | 321 | self.readline.remove_history_item(hlen - i - 1) |
|
322 | 322 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
323 | 323 | self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(), |
|
324 | 324 | stdin_encoding)) |
|
325 | 325 | return self.readline.get_current_history_length() |
|
326 | 326 | |
|
327 | 327 | def interact(self, display_banner=None): |
|
328 | 328 | """Closely emulate the interactive Python console.""" |
|
329 | 329 | |
|
330 | 330 | # batch run -> do not interact |
|
331 | 331 | if self.exit_now: |
|
332 | 332 | return |
|
333 | 333 | |
|
334 | 334 | if display_banner is None: |
|
335 | 335 | display_banner = self.display_banner |
|
336 | 336 | |
|
337 | 337 | if isinstance(display_banner, basestring): |
|
338 | 338 | self.show_banner(display_banner) |
|
339 | 339 | elif display_banner: |
|
340 | 340 | self.show_banner() |
|
341 | 341 | |
|
342 | 342 | more = False |
|
343 | 343 | |
|
344 | 344 | if self.has_readline: |
|
345 | 345 | self.readline_startup_hook(self.pre_readline) |
|
346 | 346 | hlen_b4_cell = self.readline.get_current_history_length() |
|
347 | 347 | else: |
|
348 | 348 | hlen_b4_cell = 0 |
|
349 | 349 | # exit_now is set by a call to %Exit or %Quit, through the |
|
350 | 350 | # ask_exit callback. |
|
351 | 351 | |
|
352 | 352 | while not self.exit_now: |
|
353 | 353 | self.hooks.pre_prompt_hook() |
|
354 | 354 | if more: |
|
355 | 355 | try: |
|
356 | 356 | prompt = self.prompt_manager.render('in2') |
|
357 | 357 | except: |
|
358 | 358 | self.showtraceback() |
|
359 | 359 | if self.autoindent: |
|
360 | 360 | self.rl_do_indent = True |
|
361 | 361 | |
|
362 | 362 | else: |
|
363 | 363 | try: |
|
364 | 364 | prompt = self.separate_in + self.prompt_manager.render('in') |
|
365 | 365 | except: |
|
366 | 366 | self.showtraceback() |
|
367 | 367 | try: |
|
368 | 368 | line = self.raw_input(prompt) |
|
369 | 369 | if self.exit_now: |
|
370 | 370 | # quick exit on sys.std[in|out] close |
|
371 | 371 | break |
|
372 | 372 | if self.autoindent: |
|
373 | 373 | self.rl_do_indent = False |
|
374 | 374 | |
|
375 | 375 | except KeyboardInterrupt: |
|
376 | 376 | #double-guard against keyboardinterrupts during kbdint handling |
|
377 | 377 | try: |
|
378 | 378 | self.write('\nKeyboardInterrupt\n') |
|
379 | 379 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
380 | 380 | hlen_b4_cell = \ |
|
381 | 381 | self._replace_rlhist_multiline(source_raw, hlen_b4_cell) |
|
382 | 382 | more = False |
|
383 | 383 | except KeyboardInterrupt: |
|
384 | 384 | pass |
|
385 | 385 | except EOFError: |
|
386 | 386 | if self.autoindent: |
|
387 | 387 | self.rl_do_indent = False |
|
388 | 388 | if self.has_readline: |
|
389 | 389 | self.readline_startup_hook(None) |
|
390 | 390 | self.write('\n') |
|
391 | 391 | self.exit() |
|
392 | 392 | except bdb.BdbQuit: |
|
393 | 393 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
394 | 394 | 'Because of how pdb handles the stack, it is impossible\n' |
|
395 | 395 | 'for IPython to properly format this particular exception.\n' |
|
396 | 396 | 'IPython will resume normal operation.') |
|
397 | 397 | except: |
|
398 | 398 | # exceptions here are VERY RARE, but they can be triggered |
|
399 | 399 | # asynchronously by signal handlers, for example. |
|
400 | 400 | self.showtraceback() |
|
401 | 401 | else: |
|
402 | 402 | self.input_splitter.push(line) |
|
403 | 403 | more = self.input_splitter.push_accepts_more() |
|
404 | 404 | if (self.SyntaxTB.last_syntax_error and |
|
405 | 405 | self.autoedit_syntax): |
|
406 | 406 | self.edit_syntax_error() |
|
407 | 407 | if not more: |
|
408 | 408 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
409 | 409 | self.run_cell(source_raw, store_history=True) |
|
410 | 410 | hlen_b4_cell = \ |
|
411 | 411 | self._replace_rlhist_multiline(source_raw, hlen_b4_cell) |
|
412 | 412 | |
|
413 | 413 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
414 | 414 | self.exit_now = False |
|
415 | 415 | |
|
416 | 416 | def raw_input(self, prompt=''): |
|
417 | 417 | """Write a prompt and read a line. |
|
418 | 418 | |
|
419 | 419 | The returned line does not include the trailing newline. |
|
420 | 420 | When the user enters the EOF key sequence, EOFError is raised. |
|
421 | 421 | |
|
422 | 422 | Optional inputs: |
|
423 | 423 | |
|
424 | 424 | - prompt(''): a string to be printed to prompt the user. |
|
425 | 425 | |
|
426 | 426 | - continue_prompt(False): whether this line is the first one or a |
|
427 | 427 | continuation in a sequence of inputs. |
|
428 | 428 | """ |
|
429 | 429 | # Code run by the user may have modified the readline completer state. |
|
430 | 430 | # We must ensure that our completer is back in place. |
|
431 | 431 | |
|
432 | 432 | if self.has_readline: |
|
433 | 433 | self.set_readline_completer() |
|
434 | 434 | |
|
435 | 435 | try: |
|
436 | 436 | line = py3compat.str_to_unicode(self.raw_input_original(prompt)) |
|
437 | 437 | except ValueError: |
|
438 | 438 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
439 | 439 | " or sys.stdout.close()!\nExiting IPython!") |
|
440 | 440 | self.ask_exit() |
|
441 | 441 | return "" |
|
442 | 442 | |
|
443 | 443 | # Try to be reasonably smart about not re-indenting pasted input more |
|
444 | 444 | # than necessary. We do this by trimming out the auto-indent initial |
|
445 | 445 | # spaces, if the user's actual input started itself with whitespace. |
|
446 | 446 | if self.autoindent: |
|
447 | 447 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
448 | 448 | line = line[self.indent_current_nsp:] |
|
449 | 449 | self.indent_current_nsp = 0 |
|
450 | 450 | |
|
451 | 451 | return line |
|
452 | 452 | |
|
453 | 453 | #------------------------------------------------------------------------- |
|
454 | 454 | # Methods to support auto-editing of SyntaxErrors. |
|
455 | 455 | #------------------------------------------------------------------------- |
|
456 | 456 | |
|
457 | 457 | def edit_syntax_error(self): |
|
458 | 458 | """The bottom half of the syntax error handler called in the main loop. |
|
459 | 459 | |
|
460 | 460 | Loop until syntax error is fixed or user cancels. |
|
461 | 461 | """ |
|
462 | 462 | |
|
463 | 463 | while self.SyntaxTB.last_syntax_error: |
|
464 | 464 | # copy and clear last_syntax_error |
|
465 | 465 | err = self.SyntaxTB.clear_err_state() |
|
466 | 466 | if not self._should_recompile(err): |
|
467 | 467 | return |
|
468 | 468 | try: |
|
469 | 469 | # may set last_syntax_error again if a SyntaxError is raised |
|
470 | 470 | self.safe_execfile(err.filename,self.user_ns) |
|
471 | 471 | except: |
|
472 | 472 | self.showtraceback() |
|
473 | 473 | else: |
|
474 | 474 | try: |
|
475 | 475 | f = file(err.filename) |
|
476 | 476 | try: |
|
477 | 477 | # This should be inside a display_trap block and I |
|
478 | 478 | # think it is. |
|
479 | 479 | sys.displayhook(f.read()) |
|
480 | 480 | finally: |
|
481 | 481 | f.close() |
|
482 | 482 | except: |
|
483 | 483 | self.showtraceback() |
|
484 | 484 | |
|
485 | 485 | def _should_recompile(self,e): |
|
486 | 486 | """Utility routine for edit_syntax_error""" |
|
487 | 487 | |
|
488 | 488 | if e.filename in ('<ipython console>','<input>','<string>', |
|
489 | 489 | '<console>','<BackgroundJob compilation>', |
|
490 | 490 | None): |
|
491 | 491 | |
|
492 | 492 | return False |
|
493 | 493 | try: |
|
494 | 494 | if (self.autoedit_syntax and |
|
495 | 495 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
496 | 496 | '[Y/n] ','y')): |
|
497 | 497 | return False |
|
498 | 498 | except EOFError: |
|
499 | 499 | return False |
|
500 | 500 | |
|
501 | 501 | def int0(x): |
|
502 | 502 | try: |
|
503 | 503 | return int(x) |
|
504 | 504 | except TypeError: |
|
505 | 505 | return 0 |
|
506 | 506 | # always pass integer line and offset values to editor hook |
|
507 | 507 | try: |
|
508 | 508 | self.hooks.fix_error_editor(e.filename, |
|
509 | 509 | int0(e.lineno),int0(e.offset),e.msg) |
|
510 | 510 | except TryNext: |
|
511 | 511 | warn('Could not open editor') |
|
512 | 512 | return False |
|
513 | 513 | return True |
|
514 | 514 | |
|
515 | 515 | #------------------------------------------------------------------------- |
|
516 | 516 | # Things related to exiting |
|
517 | 517 | #------------------------------------------------------------------------- |
|
518 | 518 | |
|
519 | 519 | def ask_exit(self): |
|
520 | 520 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
521 | 521 | self.exit_now = True |
|
522 | 522 | |
|
523 | 523 | def exit(self): |
|
524 | 524 | """Handle interactive exit. |
|
525 | 525 | |
|
526 | 526 | This method calls the ask_exit callback.""" |
|
527 | 527 | if self.confirm_exit: |
|
528 | 528 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
529 | 529 | self.ask_exit() |
|
530 | 530 | else: |
|
531 | 531 | self.ask_exit() |
|
532 | 532 | |
|
533 | 533 | #------------------------------------------------------------------------ |
|
534 | 534 | # Magic overrides |
|
535 | 535 | #------------------------------------------------------------------------ |
|
536 | 536 | # Once the base class stops inheriting from magic, this code needs to be |
|
537 | 537 | # moved into a separate machinery as well. For now, at least isolate here |
|
538 | 538 | # the magics which this class needs to implement differently from the base |
|
539 | 539 | # class, or that are unique to it. |
|
540 | 540 | |
|
541 | 541 | def magic_autoindent(self, parameter_s = ''): |
|
542 | 542 | """Toggle autoindent on/off (if available).""" |
|
543 | 543 | |
|
544 | 544 | self.shell.set_autoindent() |
|
545 | 545 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
546 | 546 | |
|
547 | 547 | @skip_doctest |
|
548 | 548 | def magic_cpaste(self, parameter_s=''): |
|
549 | 549 | """Paste & execute a pre-formatted code block from clipboard. |
|
550 | 550 | |
|
551 | 551 | You must terminate the block with '--' (two minus-signs) or Ctrl-D |
|
552 | 552 | alone on the line. You can also provide your own sentinel with '%paste |
|
553 | 553 | -s %%' ('%%' is the new sentinel for this operation) |
|
554 | 554 | |
|
555 | 555 | The block is dedented prior to execution to enable execution of method |
|
556 | 556 | definitions. '>' and '+' characters at the beginning of a line are |
|
557 | 557 | ignored, to allow pasting directly from e-mails, diff files and |
|
558 | 558 | doctests (the '...' continuation prompt is also stripped). The |
|
559 | 559 | executed block is also assigned to variable named 'pasted_block' for |
|
560 | 560 | later editing with '%edit pasted_block'. |
|
561 | 561 | |
|
562 | 562 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
563 | 563 | This assigns the pasted block to variable 'foo' as string, without |
|
564 | 564 | dedenting or executing it (preceding >>> and + is still stripped) |
|
565 | 565 | |
|
566 | 566 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
567 | 567 | |
|
568 | 568 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
569 | 569 | Just press enter and type -- (and press enter again) and the block |
|
570 | 570 | will be what was just pasted. |
|
571 | 571 | |
|
572 | 572 | IPython statements (magics, shell escapes) are not supported (yet). |
|
573 | 573 | |
|
574 | 574 | See also |
|
575 | 575 | -------- |
|
576 | 576 | paste: automatically pull code from clipboard. |
|
577 | 577 | |
|
578 | 578 | Examples |
|
579 | 579 | -------- |
|
580 | 580 | :: |
|
581 | 581 | |
|
582 | 582 | In [8]: %cpaste |
|
583 | 583 | Pasting code; enter '--' alone on the line to stop. |
|
584 | 584 | :>>> a = ["world!", "Hello"] |
|
585 | 585 | :>>> print " ".join(sorted(a)) |
|
586 | 586 | :-- |
|
587 | 587 | Hello world! |
|
588 | 588 | """ |
|
589 | 589 | |
|
590 | 590 | opts, name = self.parse_options(parameter_s, 'rs:', mode='string') |
|
591 | 591 | if 'r' in opts: |
|
592 | 592 | rerun_pasted(self.shell) |
|
593 | 593 | return |
|
594 | 594 | |
|
595 | 595 | sentinel = opts.get('s', '--') |
|
596 | 596 | block = strip_email_quotes(get_pasted_lines(sentinel)) |
|
597 | 597 | store_or_execute(self.shell, block, name) |
|
598 | 598 | |
|
599 | 599 | def magic_paste(self, parameter_s=''): |
|
600 | 600 | """Paste & execute a pre-formatted code block from clipboard. |
|
601 | 601 | |
|
602 | 602 | The text is pulled directly from the clipboard without user |
|
603 | 603 | intervention and printed back on the screen before execution (unless |
|
604 | 604 | the -q flag is given to force quiet mode). |
|
605 | 605 | |
|
606 | 606 | The block is dedented prior to execution to enable execution of method |
|
607 | 607 | definitions. '>' and '+' characters at the beginning of a line are |
|
608 | 608 | ignored, to allow pasting directly from e-mails, diff files and |
|
609 | 609 | doctests (the '...' continuation prompt is also stripped). The |
|
610 | 610 | executed block is also assigned to variable named 'pasted_block' for |
|
611 | 611 | later editing with '%edit pasted_block'. |
|
612 | 612 | |
|
613 | 613 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
614 | 614 | This assigns the pasted block to variable 'foo' as string, without |
|
615 | 615 | dedenting or executing it (preceding >>> and + is still stripped) |
|
616 | 616 | |
|
617 | 617 | Options |
|
618 | 618 | ------- |
|
619 | 619 | |
|
620 | 620 | -r: re-executes the block previously entered by cpaste. |
|
621 | 621 | |
|
622 | 622 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
623 | 623 | |
|
624 | 624 | IPython statements (magics, shell escapes) are not supported (yet). |
|
625 | 625 | |
|
626 | 626 | See also |
|
627 | 627 | -------- |
|
628 | 628 | cpaste: manually paste code into terminal until you mark its end. |
|
629 | 629 | """ |
|
630 | 630 | opts, name = self.parse_options(parameter_s, 'rq', mode='string') |
|
631 | 631 | if 'r' in opts: |
|
632 | 632 | rerun_pasted(self.shell) |
|
633 | 633 | return |
|
634 | 634 | try: |
|
635 | 635 | text = self.shell.hooks.clipboard_get() |
|
636 | 636 | block = strip_email_quotes(text.splitlines()) |
|
637 | 637 | except TryNext as clipboard_exc: |
|
638 | 638 | message = getattr(clipboard_exc, 'args') |
|
639 | 639 | if message: |
|
640 | 640 | error(message[0]) |
|
641 | 641 | else: |
|
642 | 642 | error('Could not get text from the clipboard.') |
|
643 | 643 | return |
|
644 | 644 | |
|
645 | 645 | # By default, echo back to terminal unless quiet mode is requested |
|
646 | 646 | if 'q' not in opts: |
|
647 | 647 | write = self.shell.write |
|
648 | 648 | write(self.shell.pycolorize(block)) |
|
649 | 649 | if not block.endswith('\n'): |
|
650 | 650 | write('\n') |
|
651 | 651 | write("## -- End pasted text --\n") |
|
652 | 652 | |
|
653 | 653 | store_or_execute(self.shell, block, name) |
|
654 | 654 | |
|
655 | 655 | # Class-level: add a '%cls' magic only on Windows |
|
656 | 656 | if sys.platform == 'win32': |
|
657 | 657 | def magic_cls(self, s): |
|
658 | 658 | """Clear screen. |
|
659 | 659 | """ |
|
660 | 660 | os.system("cls") |
|
661 | 661 | |
|
662 | 662 | def showindentationerror(self): |
|
663 | 663 | super(TerminalInteractiveShell, self).showindentationerror() |
|
664 | 664 | print("If you want to paste code into IPython, try the " |
|
665 | 665 | "%paste and %cpaste magic functions.") |
|
666 | 666 | |
|
667 | 667 | |
|
668 | 668 | InteractiveShellABC.register(TerminalInteractiveShell) |
@@ -1,759 +1,759 b'' | |||
|
1 | 1 | """The Python scheduler for rich scheduling. |
|
2 | 2 | |
|
3 | 3 | The Pure ZMQ scheduler does not allow routing schemes other than LRU, |
|
4 | 4 | nor does it check msg_id DAG dependencies. For those, a slightly slower |
|
5 | 5 | Python Scheduler exists. |
|
6 | 6 | |
|
7 | 7 | Authors: |
|
8 | 8 | |
|
9 | 9 | * Min RK |
|
10 | 10 | """ |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2010-2011 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #---------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #---------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | from __future__ import print_function |
|
23 | 23 | |
|
24 | 24 | import logging |
|
25 | 25 | import sys |
|
26 | 26 | import time |
|
27 | 27 | |
|
28 | 28 | from datetime import datetime, timedelta |
|
29 | 29 | from random import randint, random |
|
30 | 30 | from types import FunctionType |
|
31 | 31 | |
|
32 | 32 | try: |
|
33 | 33 | import numpy |
|
34 | 34 | except ImportError: |
|
35 | 35 | numpy = None |
|
36 | 36 | |
|
37 | 37 | import zmq |
|
38 | 38 | from zmq.eventloop import ioloop, zmqstream |
|
39 | 39 | |
|
40 | 40 | # local imports |
|
41 | 41 | from IPython.external.decorator import decorator |
|
42 | 42 | from IPython.config.application import Application |
|
43 | 43 | from IPython.config.loader import Config |
|
44 | 44 | from IPython.utils.traitlets import Instance, Dict, List, Set, Integer, Enum, CBytes |
|
45 | 45 | |
|
46 | 46 | from IPython.parallel import error |
|
47 | 47 | from IPython.parallel.factory import SessionFactory |
|
48 | 48 | from IPython.parallel.util import connect_logger, local_logger, asbytes |
|
49 | 49 | |
|
50 | 50 | from .dependency import Dependency |
|
51 | 51 | |
|
52 | 52 | @decorator |
|
53 | 53 | def logged(f,self,*args,**kwargs): |
|
54 | 54 | # print ("#--------------------") |
|
55 | 55 | self.log.debug("scheduler::%s(*%s,**%s)", f.func_name, args, kwargs) |
|
56 | 56 | # print ("#--") |
|
57 | 57 | return f(self,*args, **kwargs) |
|
58 | 58 | |
|
59 | 59 | #---------------------------------------------------------------------- |
|
60 | 60 | # Chooser functions |
|
61 | 61 | #---------------------------------------------------------------------- |
|
62 | 62 | |
|
63 | 63 | def plainrandom(loads): |
|
64 | 64 | """Plain random pick.""" |
|
65 | 65 | n = len(loads) |
|
66 | 66 | return randint(0,n-1) |
|
67 | 67 | |
|
68 | 68 | def lru(loads): |
|
69 | 69 | """Always pick the front of the line. |
|
70 | 70 | |
|
71 | 71 | The content of `loads` is ignored. |
|
72 | 72 | |
|
73 | 73 | Assumes LRU ordering of loads, with oldest first. |
|
74 | 74 | """ |
|
75 | 75 | return 0 |
|
76 | 76 | |
|
77 | 77 | def twobin(loads): |
|
78 | 78 | """Pick two at random, use the LRU of the two. |
|
79 | 79 | |
|
80 | 80 | The content of loads is ignored. |
|
81 | 81 | |
|
82 | 82 | Assumes LRU ordering of loads, with oldest first. |
|
83 | 83 | """ |
|
84 | 84 | n = len(loads) |
|
85 | 85 | a = randint(0,n-1) |
|
86 | 86 | b = randint(0,n-1) |
|
87 | 87 | return min(a,b) |
|
88 | 88 | |
|
89 | 89 | def weighted(loads): |
|
90 | 90 | """Pick two at random using inverse load as weight. |
|
91 | 91 | |
|
92 | 92 | Return the less loaded of the two. |
|
93 | 93 | """ |
|
94 | 94 | # weight 0 a million times more than 1: |
|
95 | 95 | weights = 1./(1e-6+numpy.array(loads)) |
|
96 | 96 | sums = weights.cumsum() |
|
97 | 97 | t = sums[-1] |
|
98 | 98 | x = random()*t |
|
99 | 99 | y = random()*t |
|
100 | 100 | idx = 0 |
|
101 | 101 | idy = 0 |
|
102 | 102 | while sums[idx] < x: |
|
103 | 103 | idx += 1 |
|
104 | 104 | while sums[idy] < y: |
|
105 | 105 | idy += 1 |
|
106 | 106 | if weights[idy] > weights[idx]: |
|
107 | 107 | return idy |
|
108 | 108 | else: |
|
109 | 109 | return idx |
|
110 | 110 | |
|
111 | 111 | def leastload(loads): |
|
112 | 112 | """Always choose the lowest load. |
|
113 | 113 | |
|
114 | 114 | If the lowest load occurs more than once, the first |
|
115 | 115 | occurance will be used. If loads has LRU ordering, this means |
|
116 | 116 | the LRU of those with the lowest load is chosen. |
|
117 | 117 | """ |
|
118 | 118 | return loads.index(min(loads)) |
|
119 | 119 | |
|
120 | 120 | #--------------------------------------------------------------------- |
|
121 | 121 | # Classes |
|
122 | 122 | #--------------------------------------------------------------------- |
|
123 | 123 | |
|
124 | 124 | |
|
125 | 125 | # store empty default dependency: |
|
126 | 126 | MET = Dependency([]) |
|
127 | 127 | |
|
128 | 128 | |
|
129 | 129 | class Job(object): |
|
130 | 130 | """Simple container for a job""" |
|
131 | 131 | def __init__(self, msg_id, raw_msg, idents, msg, header, targets, after, follow, timeout): |
|
132 | 132 | self.msg_id = msg_id |
|
133 | 133 | self.raw_msg = raw_msg |
|
134 | 134 | self.idents = idents |
|
135 | 135 | self.msg = msg |
|
136 | 136 | self.header = header |
|
137 | 137 | self.targets = targets |
|
138 | 138 | self.after = after |
|
139 | 139 | self.follow = follow |
|
140 | 140 | self.timeout = timeout |
|
141 | 141 | |
|
142 | 142 | |
|
143 | 143 | self.timestamp = time.time() |
|
144 | 144 | self.blacklist = set() |
|
145 | 145 | |
|
146 | 146 | @property |
|
147 | 147 | def dependents(self): |
|
148 | 148 | return self.follow.union(self.after) |
|
149 | 149 | |
|
150 | 150 | class TaskScheduler(SessionFactory): |
|
151 | 151 | """Python TaskScheduler object. |
|
152 | 152 | |
|
153 | 153 | This is the simplest object that supports msg_id based |
|
154 | 154 | DAG dependencies. *Only* task msg_ids are checked, not |
|
155 | 155 | msg_ids of jobs submitted via the MUX queue. |
|
156 | 156 | |
|
157 | 157 | """ |
|
158 | 158 | |
|
159 | 159 | hwm = Integer(1, config=True, |
|
160 | 160 | help="""specify the High Water Mark (HWM) for the downstream |
|
161 | 161 | socket in the Task scheduler. This is the maximum number |
|
162 | 162 | of allowed outstanding tasks on each engine. |
|
163 | 163 | |
|
164 | 164 | The default (1) means that only one task can be outstanding on each |
|
165 | 165 | engine. Setting TaskScheduler.hwm=0 means there is no limit, and the |
|
166 | 166 | engines continue to be assigned tasks while they are working, |
|
167 | 167 | effectively hiding network latency behind computation, but can result |
|
168 | 168 | in an imbalance of work when submitting many heterogenous tasks all at |
|
169 | 169 | once. Any positive value greater than one is a compromise between the |
|
170 | 170 | two. |
|
171 | 171 | |
|
172 | 172 | """ |
|
173 | 173 | ) |
|
174 | 174 | scheme_name = Enum(('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin'), |
|
175 | 175 | 'leastload', config=True, allow_none=False, |
|
176 | 176 | help="""select the task scheduler scheme [default: Python LRU] |
|
177 | 177 | Options are: 'pure', 'lru', 'plainrandom', 'weighted', 'twobin','leastload'""" |
|
178 | 178 | ) |
|
179 | 179 | def _scheme_name_changed(self, old, new): |
|
180 | 180 | self.log.debug("Using scheme %r"%new) |
|
181 | 181 | self.scheme = globals()[new] |
|
182 | 182 | |
|
183 | 183 | # input arguments: |
|
184 | 184 | scheme = Instance(FunctionType) # function for determining the destination |
|
185 | 185 | def _scheme_default(self): |
|
186 | 186 | return leastload |
|
187 | 187 | client_stream = Instance(zmqstream.ZMQStream) # client-facing stream |
|
188 | 188 | engine_stream = Instance(zmqstream.ZMQStream) # engine-facing stream |
|
189 | 189 | notifier_stream = Instance(zmqstream.ZMQStream) # hub-facing sub stream |
|
190 | 190 | mon_stream = Instance(zmqstream.ZMQStream) # hub-facing pub stream |
|
191 | 191 | |
|
192 | 192 | # internals: |
|
193 | 193 | graph = Dict() # dict by msg_id of [ msg_ids that depend on key ] |
|
194 | 194 | retries = Dict() # dict by msg_id of retries remaining (non-neg ints) |
|
195 | 195 | # waiting = List() # list of msg_ids ready to run, but haven't due to HWM |
|
196 | 196 | depending = Dict() # dict by msg_id of Jobs |
|
197 | 197 | pending = Dict() # dict by engine_uuid of submitted tasks |
|
198 | 198 | completed = Dict() # dict by engine_uuid of completed tasks |
|
199 | 199 | failed = Dict() # dict by engine_uuid of failed tasks |
|
200 | 200 | destinations = Dict() # dict by msg_id of engine_uuids where jobs ran (reverse of completed+failed) |
|
201 | 201 | clients = Dict() # dict by msg_id for who submitted the task |
|
202 | 202 | targets = List() # list of target IDENTs |
|
203 | 203 | loads = List() # list of engine loads |
|
204 | 204 | # full = Set() # set of IDENTs that have HWM outstanding tasks |
|
205 | 205 | all_completed = Set() # set of all completed tasks |
|
206 | 206 | all_failed = Set() # set of all failed tasks |
|
207 | 207 | all_done = Set() # set of all finished tasks=union(completed,failed) |
|
208 | 208 | all_ids = Set() # set of all submitted task IDs |
|
209 | 209 | |
|
210 | 210 | auditor = Instance('zmq.eventloop.ioloop.PeriodicCallback') |
|
211 | 211 | |
|
212 | 212 | ident = CBytes() # ZMQ identity. This should just be self.session.session |
|
213 | 213 | # but ensure Bytes |
|
214 | 214 | def _ident_default(self): |
|
215 | 215 | return self.session.bsession |
|
216 | 216 | |
|
217 | 217 | def start(self): |
|
218 | 218 | self.engine_stream.on_recv(self.dispatch_result, copy=False) |
|
219 | 219 | self.client_stream.on_recv(self.dispatch_submission, copy=False) |
|
220 | 220 | |
|
221 | 221 | self._notification_handlers = dict( |
|
222 | 222 | registration_notification = self._register_engine, |
|
223 | 223 | unregistration_notification = self._unregister_engine |
|
224 | 224 | ) |
|
225 | 225 | self.notifier_stream.on_recv(self.dispatch_notification) |
|
226 | 226 | self.auditor = ioloop.PeriodicCallback(self.audit_timeouts, 2e3, self.loop) # 1 Hz |
|
227 | 227 | self.auditor.start() |
|
228 | 228 | self.log.info("Scheduler started [%s]"%self.scheme_name) |
|
229 | 229 | |
|
230 | 230 | def resume_receiving(self): |
|
231 | 231 | """Resume accepting jobs.""" |
|
232 | 232 | self.client_stream.on_recv(self.dispatch_submission, copy=False) |
|
233 | 233 | |
|
234 | 234 | def stop_receiving(self): |
|
235 | 235 | """Stop accepting jobs while there are no engines. |
|
236 | 236 | Leave them in the ZMQ queue.""" |
|
237 | 237 | self.client_stream.on_recv(None) |
|
238 | 238 | |
|
239 | 239 | #----------------------------------------------------------------------- |
|
240 | 240 | # [Un]Registration Handling |
|
241 | 241 | #----------------------------------------------------------------------- |
|
242 | 242 | |
|
243 | 243 | def dispatch_notification(self, msg): |
|
244 | 244 | """dispatch register/unregister events.""" |
|
245 | 245 | try: |
|
246 | 246 | idents,msg = self.session.feed_identities(msg) |
|
247 | 247 | except ValueError: |
|
248 | 248 | self.log.warn("task::Invalid Message: %r",msg) |
|
249 | 249 | return |
|
250 | 250 | try: |
|
251 | 251 | msg = self.session.unserialize(msg) |
|
252 | 252 | except ValueError: |
|
253 | 253 | self.log.warn("task::Unauthorized message from: %r"%idents) |
|
254 | 254 | return |
|
255 | 255 | |
|
256 | 256 | msg_type = msg['header']['msg_type'] |
|
257 | 257 | |
|
258 | 258 | handler = self._notification_handlers.get(msg_type, None) |
|
259 | 259 | if handler is None: |
|
260 | 260 | self.log.error("Unhandled message type: %r"%msg_type) |
|
261 | 261 | else: |
|
262 | 262 | try: |
|
263 | 263 | handler(asbytes(msg['content']['queue'])) |
|
264 | 264 | except Exception: |
|
265 | 265 | self.log.error("task::Invalid notification msg: %r", msg, exc_info=True) |
|
266 | 266 | |
|
267 | 267 | def _register_engine(self, uid): |
|
268 | 268 | """New engine with ident `uid` became available.""" |
|
269 | 269 | # head of the line: |
|
270 | 270 | self.targets.insert(0,uid) |
|
271 | 271 | self.loads.insert(0,0) |
|
272 | 272 | |
|
273 | 273 | # initialize sets |
|
274 | 274 | self.completed[uid] = set() |
|
275 | 275 | self.failed[uid] = set() |
|
276 | 276 | self.pending[uid] = {} |
|
277 | 277 | |
|
278 | 278 | # rescan the graph: |
|
279 | 279 | self.update_graph(None) |
|
280 | 280 | |
|
281 | 281 | def _unregister_engine(self, uid): |
|
282 | 282 | """Existing engine with ident `uid` became unavailable.""" |
|
283 | 283 | if len(self.targets) == 1: |
|
284 | 284 | # this was our only engine |
|
285 | 285 | pass |
|
286 | 286 | |
|
287 | 287 | # handle any potentially finished tasks: |
|
288 | 288 | self.engine_stream.flush() |
|
289 | 289 | |
|
290 | 290 | # don't pop destinations, because they might be used later |
|
291 | 291 | # map(self.destinations.pop, self.completed.pop(uid)) |
|
292 | 292 | # map(self.destinations.pop, self.failed.pop(uid)) |
|
293 | 293 | |
|
294 | 294 | # prevent this engine from receiving work |
|
295 | 295 | idx = self.targets.index(uid) |
|
296 | 296 | self.targets.pop(idx) |
|
297 | 297 | self.loads.pop(idx) |
|
298 | 298 | |
|
299 | 299 | # wait 5 seconds before cleaning up pending jobs, since the results might |
|
300 | 300 | # still be incoming |
|
301 | 301 | if self.pending[uid]: |
|
302 | 302 | dc = ioloop.DelayedCallback(lambda : self.handle_stranded_tasks(uid), 5000, self.loop) |
|
303 | 303 | dc.start() |
|
304 | 304 | else: |
|
305 | 305 | self.completed.pop(uid) |
|
306 | 306 | self.failed.pop(uid) |
|
307 | 307 | |
|
308 | 308 | |
|
309 | 309 | def handle_stranded_tasks(self, engine): |
|
310 | 310 | """Deal with jobs resident in an engine that died.""" |
|
311 | 311 | lost = self.pending[engine] |
|
312 | 312 | for msg_id in lost.keys(): |
|
313 | 313 | if msg_id not in self.pending[engine]: |
|
314 | 314 | # prevent double-handling of messages |
|
315 | 315 | continue |
|
316 | 316 | |
|
317 | 317 | raw_msg = lost[msg_id][0] |
|
318 | 318 | idents,msg = self.session.feed_identities(raw_msg, copy=False) |
|
319 | 319 | parent = self.session.unpack(msg[1].bytes) |
|
320 | 320 | idents = [engine, idents[0]] |
|
321 | 321 | |
|
322 | 322 | # build fake error reply |
|
323 | 323 | try: |
|
324 | 324 | raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id)) |
|
325 | 325 | except: |
|
326 | 326 | content = error.wrap_exception() |
|
327 | 327 | # build fake header |
|
328 | 328 | header = dict( |
|
329 | 329 | status='error', |
|
330 | 330 | engine=engine, |
|
331 | 331 | date=datetime.now(), |
|
332 | 332 | ) |
|
333 | 333 | msg = self.session.msg('apply_reply', content, parent=parent, subheader=header) |
|
334 | 334 | raw_reply = map(zmq.Message, self.session.serialize(msg, ident=idents)) |
|
335 | 335 | # and dispatch it |
|
336 | 336 | self.dispatch_result(raw_reply) |
|
337 | 337 | |
|
338 | 338 | # finally scrub completed/failed lists |
|
339 | 339 | self.completed.pop(engine) |
|
340 | 340 | self.failed.pop(engine) |
|
341 | 341 | |
|
342 | 342 | |
|
343 | 343 | #----------------------------------------------------------------------- |
|
344 | 344 | # Job Submission |
|
345 | 345 | #----------------------------------------------------------------------- |
|
346 | 346 | def dispatch_submission(self, raw_msg): |
|
347 | 347 | """Dispatch job submission to appropriate handlers.""" |
|
348 | 348 | # ensure targets up to date: |
|
349 | 349 | self.notifier_stream.flush() |
|
350 | 350 | try: |
|
351 | 351 | idents, msg = self.session.feed_identities(raw_msg, copy=False) |
|
352 | 352 | msg = self.session.unserialize(msg, content=False, copy=False) |
|
353 | 353 | except Exception: |
|
354 | 354 | self.log.error("task::Invaid task msg: %r"%raw_msg, exc_info=True) |
|
355 | 355 | return |
|
356 | 356 | |
|
357 | 357 | |
|
358 | 358 | # send to monitor |
|
359 | 359 | self.mon_stream.send_multipart([b'intask']+raw_msg, copy=False) |
|
360 | 360 | |
|
361 | 361 | header = msg['header'] |
|
362 | 362 | msg_id = header['msg_id'] |
|
363 | 363 | self.all_ids.add(msg_id) |
|
364 | 364 | |
|
365 | 365 | # get targets as a set of bytes objects |
|
366 | 366 | # from a list of unicode objects |
|
367 | 367 | targets = header.get('targets', []) |
|
368 | 368 | targets = map(asbytes, targets) |
|
369 | 369 | targets = set(targets) |
|
370 | 370 | |
|
371 | 371 | retries = header.get('retries', 0) |
|
372 | 372 | self.retries[msg_id] = retries |
|
373 | 373 | |
|
374 | 374 | # time dependencies |
|
375 | 375 | after = header.get('after', None) |
|
376 | 376 | if after: |
|
377 | 377 | after = Dependency(after) |
|
378 | 378 | if after.all: |
|
379 | 379 | if after.success: |
|
380 | 380 | after = Dependency(after.difference(self.all_completed), |
|
381 | 381 | success=after.success, |
|
382 | 382 | failure=after.failure, |
|
383 | 383 | all=after.all, |
|
384 | 384 | ) |
|
385 | 385 | if after.failure: |
|
386 | 386 | after = Dependency(after.difference(self.all_failed), |
|
387 | 387 | success=after.success, |
|
388 | 388 | failure=after.failure, |
|
389 | 389 | all=after.all, |
|
390 | 390 | ) |
|
391 | 391 | if after.check(self.all_completed, self.all_failed): |
|
392 | 392 | # recast as empty set, if `after` already met, |
|
393 | 393 | # to prevent unnecessary set comparisons |
|
394 | 394 | after = MET |
|
395 | 395 | else: |
|
396 | 396 | after = MET |
|
397 | 397 | |
|
398 | 398 | # location dependencies |
|
399 | 399 | follow = Dependency(header.get('follow', [])) |
|
400 | 400 | |
|
401 | 401 | # turn timeouts into datetime objects: |
|
402 | 402 | timeout = header.get('timeout', None) |
|
403 | 403 | if timeout: |
|
404 | 404 | # cast to float, because jsonlib returns floats as decimal.Decimal, |
|
405 | 405 | # which timedelta does not accept |
|
406 | 406 | timeout = datetime.now() + timedelta(0,float(timeout),0) |
|
407 | 407 | |
|
408 | 408 | job = Job(msg_id=msg_id, raw_msg=raw_msg, idents=idents, msg=msg, |
|
409 | 409 | header=header, targets=targets, after=after, follow=follow, |
|
410 | 410 | timeout=timeout, |
|
411 | 411 | ) |
|
412 | 412 | |
|
413 | 413 | # validate and reduce dependencies: |
|
414 | 414 | for dep in after,follow: |
|
415 | 415 | if not dep: # empty dependency |
|
416 | 416 | continue |
|
417 | 417 | # check valid: |
|
418 | 418 | if msg_id in dep or dep.difference(self.all_ids): |
|
419 | 419 | self.depending[msg_id] = job |
|
420 | 420 | return self.fail_unreachable(msg_id, error.InvalidDependency) |
|
421 | 421 | # check if unreachable: |
|
422 | 422 | if dep.unreachable(self.all_completed, self.all_failed): |
|
423 | 423 | self.depending[msg_id] = job |
|
424 | 424 | return self.fail_unreachable(msg_id) |
|
425 | 425 | |
|
426 | 426 | if after.check(self.all_completed, self.all_failed): |
|
427 | 427 | # time deps already met, try to run |
|
428 | 428 | if not self.maybe_run(job): |
|
429 | 429 | # can't run yet |
|
430 | 430 | if msg_id not in self.all_failed: |
|
431 | 431 | # could have failed as unreachable |
|
432 | 432 | self.save_unmet(job) |
|
433 | 433 | else: |
|
434 | 434 | self.save_unmet(job) |
|
435 | 435 | |
|
436 | 436 | def audit_timeouts(self): |
|
437 | 437 | """Audit all waiting tasks for expired timeouts.""" |
|
438 | 438 | now = datetime.now() |
|
439 | 439 | for msg_id in self.depending.keys(): |
|
440 | 440 | # must recheck, in case one failure cascaded to another: |
|
441 | 441 | if msg_id in self.depending: |
|
442 | 442 | job = self.depending[msg_id] |
|
443 | 443 | if job.timeout and job.timeout < now: |
|
444 | 444 | self.fail_unreachable(msg_id, error.TaskTimeout) |
|
445 | 445 | |
|
446 | 446 | def fail_unreachable(self, msg_id, why=error.ImpossibleDependency): |
|
447 | 447 | """a task has become unreachable, send a reply with an ImpossibleDependency |
|
448 | 448 | error.""" |
|
449 | 449 | if msg_id not in self.depending: |
|
450 | 450 | self.log.error("msg %r already failed!", msg_id) |
|
451 | 451 | return |
|
452 | 452 | job = self.depending.pop(msg_id) |
|
453 | 453 | for mid in job.dependents: |
|
454 | 454 | if mid in self.graph: |
|
455 | 455 | self.graph[mid].remove(msg_id) |
|
456 | 456 | |
|
457 | 457 | try: |
|
458 | 458 | raise why() |
|
459 | 459 | except: |
|
460 | 460 | content = error.wrap_exception() |
|
461 | 461 | |
|
462 | 462 | self.all_done.add(msg_id) |
|
463 | 463 | self.all_failed.add(msg_id) |
|
464 | 464 | |
|
465 | 465 | msg = self.session.send(self.client_stream, 'apply_reply', content, |
|
466 | 466 | parent=job.header, ident=job.idents) |
|
467 | 467 | self.session.send(self.mon_stream, msg, ident=[b'outtask']+job.idents) |
|
468 | 468 | |
|
469 | 469 | self.update_graph(msg_id, success=False) |
|
470 | 470 | |
|
471 | 471 | def maybe_run(self, job): |
|
472 | 472 | """check location dependencies, and run if they are met.""" |
|
473 | 473 | msg_id = job.msg_id |
|
474 | 474 | self.log.debug("Attempting to assign task %s", msg_id) |
|
475 | 475 | if not self.targets: |
|
476 | 476 | # no engines, definitely can't run |
|
477 | 477 | return False |
|
478 | 478 | |
|
479 | 479 | if job.follow or job.targets or job.blacklist or self.hwm: |
|
480 | 480 | # we need a can_run filter |
|
481 | 481 | def can_run(idx): |
|
482 | 482 | # check hwm |
|
483 | 483 | if self.hwm and self.loads[idx] == self.hwm: |
|
484 | 484 | return False |
|
485 | 485 | target = self.targets[idx] |
|
486 | 486 | # check blacklist |
|
487 | 487 | if target in job.blacklist: |
|
488 | 488 | return False |
|
489 | 489 | # check targets |
|
490 | 490 | if job.targets and target not in job.targets: |
|
491 | 491 | return False |
|
492 | 492 | # check follow |
|
493 | 493 | return job.follow.check(self.completed[target], self.failed[target]) |
|
494 | 494 | |
|
495 | 495 | indices = filter(can_run, range(len(self.targets))) |
|
496 | 496 | |
|
497 | 497 | if not indices: |
|
498 | 498 | # couldn't run |
|
499 | 499 | if job.follow.all: |
|
500 | 500 | # check follow for impossibility |
|
501 | 501 | dests = set() |
|
502 | 502 | relevant = set() |
|
503 | 503 | if job.follow.success: |
|
504 | 504 | relevant = self.all_completed |
|
505 | 505 | if job.follow.failure: |
|
506 | 506 | relevant = relevant.union(self.all_failed) |
|
507 | 507 | for m in job.follow.intersection(relevant): |
|
508 | 508 | dests.add(self.destinations[m]) |
|
509 | 509 | if len(dests) > 1: |
|
510 | 510 | self.depending[msg_id] = job |
|
511 | 511 | self.fail_unreachable(msg_id) |
|
512 | 512 | return False |
|
513 | 513 | if job.targets: |
|
514 | 514 | # check blacklist+targets for impossibility |
|
515 | job.targets.difference_update(blacklist) | |
|
515 | job.targets.difference_update(job.blacklist) | |
|
516 | 516 | if not job.targets or not job.targets.intersection(self.targets): |
|
517 | 517 | self.depending[msg_id] = job |
|
518 | 518 | self.fail_unreachable(msg_id) |
|
519 | 519 | return False |
|
520 | 520 | return False |
|
521 | 521 | else: |
|
522 | 522 | indices = None |
|
523 | 523 | |
|
524 | 524 | self.submit_task(job, indices) |
|
525 | 525 | return True |
|
526 | 526 | |
|
527 | 527 | def save_unmet(self, job): |
|
528 | 528 | """Save a message for later submission when its dependencies are met.""" |
|
529 | 529 | msg_id = job.msg_id |
|
530 | 530 | self.depending[msg_id] = job |
|
531 | 531 | # track the ids in follow or after, but not those already finished |
|
532 | 532 | for dep_id in job.after.union(job.follow).difference(self.all_done): |
|
533 | 533 | if dep_id not in self.graph: |
|
534 | 534 | self.graph[dep_id] = set() |
|
535 | 535 | self.graph[dep_id].add(msg_id) |
|
536 | 536 | |
|
537 | 537 | def submit_task(self, job, indices=None): |
|
538 | 538 | """Submit a task to any of a subset of our targets.""" |
|
539 | 539 | if indices: |
|
540 | 540 | loads = [self.loads[i] for i in indices] |
|
541 | 541 | else: |
|
542 | 542 | loads = self.loads |
|
543 | 543 | idx = self.scheme(loads) |
|
544 | 544 | if indices: |
|
545 | 545 | idx = indices[idx] |
|
546 | 546 | target = self.targets[idx] |
|
547 | 547 | # print (target, map(str, msg[:3])) |
|
548 | 548 | # send job to the engine |
|
549 | 549 | self.engine_stream.send(target, flags=zmq.SNDMORE, copy=False) |
|
550 | 550 | self.engine_stream.send_multipart(job.raw_msg, copy=False) |
|
551 | 551 | # update load |
|
552 | 552 | self.add_job(idx) |
|
553 | 553 | self.pending[target][job.msg_id] = job |
|
554 | 554 | # notify Hub |
|
555 | 555 | content = dict(msg_id=job.msg_id, engine_id=target.decode('ascii')) |
|
556 | 556 | self.session.send(self.mon_stream, 'task_destination', content=content, |
|
557 | 557 | ident=[b'tracktask',self.ident]) |
|
558 | 558 | |
|
559 | 559 | |
|
560 | 560 | #----------------------------------------------------------------------- |
|
561 | 561 | # Result Handling |
|
562 | 562 | #----------------------------------------------------------------------- |
|
563 | 563 | def dispatch_result(self, raw_msg): |
|
564 | 564 | """dispatch method for result replies""" |
|
565 | 565 | try: |
|
566 | 566 | idents,msg = self.session.feed_identities(raw_msg, copy=False) |
|
567 | 567 | msg = self.session.unserialize(msg, content=False, copy=False) |
|
568 | 568 | engine = idents[0] |
|
569 | 569 | try: |
|
570 | 570 | idx = self.targets.index(engine) |
|
571 | 571 | except ValueError: |
|
572 | 572 | pass # skip load-update for dead engines |
|
573 | 573 | else: |
|
574 | 574 | self.finish_job(idx) |
|
575 | 575 | except Exception: |
|
576 | 576 | self.log.error("task::Invaid result: %r", raw_msg, exc_info=True) |
|
577 | 577 | return |
|
578 | 578 | |
|
579 | 579 | header = msg['header'] |
|
580 | 580 | parent = msg['parent_header'] |
|
581 | 581 | if header.get('dependencies_met', True): |
|
582 | 582 | success = (header['status'] == 'ok') |
|
583 | 583 | msg_id = parent['msg_id'] |
|
584 | 584 | retries = self.retries[msg_id] |
|
585 | 585 | if not success and retries > 0: |
|
586 | 586 | # failed |
|
587 | 587 | self.retries[msg_id] = retries - 1 |
|
588 | 588 | self.handle_unmet_dependency(idents, parent) |
|
589 | 589 | else: |
|
590 | 590 | del self.retries[msg_id] |
|
591 | 591 | # relay to client and update graph |
|
592 | 592 | self.handle_result(idents, parent, raw_msg, success) |
|
593 | 593 | # send to Hub monitor |
|
594 | 594 | self.mon_stream.send_multipart([b'outtask']+raw_msg, copy=False) |
|
595 | 595 | else: |
|
596 | 596 | self.handle_unmet_dependency(idents, parent) |
|
597 | 597 | |
|
598 | 598 | def handle_result(self, idents, parent, raw_msg, success=True): |
|
599 | 599 | """handle a real task result, either success or failure""" |
|
600 | 600 | # first, relay result to client |
|
601 | 601 | engine = idents[0] |
|
602 | 602 | client = idents[1] |
|
603 | 603 | # swap_ids for XREP-XREP mirror |
|
604 | 604 | raw_msg[:2] = [client,engine] |
|
605 | 605 | # print (map(str, raw_msg[:4])) |
|
606 | 606 | self.client_stream.send_multipart(raw_msg, copy=False) |
|
607 | 607 | # now, update our data structures |
|
608 | 608 | msg_id = parent['msg_id'] |
|
609 | 609 | self.pending[engine].pop(msg_id) |
|
610 | 610 | if success: |
|
611 | 611 | self.completed[engine].add(msg_id) |
|
612 | 612 | self.all_completed.add(msg_id) |
|
613 | 613 | else: |
|
614 | 614 | self.failed[engine].add(msg_id) |
|
615 | 615 | self.all_failed.add(msg_id) |
|
616 | 616 | self.all_done.add(msg_id) |
|
617 | 617 | self.destinations[msg_id] = engine |
|
618 | 618 | |
|
619 | 619 | self.update_graph(msg_id, success) |
|
620 | 620 | |
|
621 | 621 | def handle_unmet_dependency(self, idents, parent): |
|
622 | 622 | """handle an unmet dependency""" |
|
623 | 623 | engine = idents[0] |
|
624 | 624 | msg_id = parent['msg_id'] |
|
625 | 625 | |
|
626 | 626 | job = self.pending[engine].pop(msg_id) |
|
627 | 627 | job.blacklist.add(engine) |
|
628 | 628 | |
|
629 | 629 | if job.blacklist == job.targets: |
|
630 | 630 | self.depending[msg_id] = job |
|
631 | 631 | self.fail_unreachable(msg_id) |
|
632 | 632 | elif not self.maybe_run(job): |
|
633 | 633 | # resubmit failed |
|
634 | 634 | if msg_id not in self.all_failed: |
|
635 | 635 | # put it back in our dependency tree |
|
636 | 636 | self.save_unmet(job) |
|
637 | 637 | |
|
638 | 638 | if self.hwm: |
|
639 | 639 | try: |
|
640 | 640 | idx = self.targets.index(engine) |
|
641 | 641 | except ValueError: |
|
642 | 642 | pass # skip load-update for dead engines |
|
643 | 643 | else: |
|
644 | 644 | if self.loads[idx] == self.hwm-1: |
|
645 | 645 | self.update_graph(None) |
|
646 | 646 | |
|
647 | 647 | |
|
648 | 648 | |
|
649 | 649 | def update_graph(self, dep_id=None, success=True): |
|
650 | 650 | """dep_id just finished. Update our dependency |
|
651 | 651 | graph and submit any jobs that just became runable. |
|
652 | 652 | |
|
653 | 653 | Called with dep_id=None to update entire graph for hwm, but without finishing |
|
654 | 654 | a task. |
|
655 | 655 | """ |
|
656 | 656 | # print ("\n\n***********") |
|
657 | 657 | # pprint (dep_id) |
|
658 | 658 | # pprint (self.graph) |
|
659 | 659 | # pprint (self.depending) |
|
660 | 660 | # pprint (self.all_completed) |
|
661 | 661 | # pprint (self.all_failed) |
|
662 | 662 | # print ("\n\n***********\n\n") |
|
663 | 663 | # update any jobs that depended on the dependency |
|
664 | 664 | jobs = self.graph.pop(dep_id, []) |
|
665 | 665 | |
|
666 | 666 | # recheck *all* jobs if |
|
667 | 667 | # a) we have HWM and an engine just become no longer full |
|
668 | 668 | # or b) dep_id was given as None |
|
669 | 669 | |
|
670 | 670 | if dep_id is None or self.hwm and any( [ load==self.hwm-1 for load in self.loads ]): |
|
671 | 671 | jobs = self.depending.keys() |
|
672 | 672 | |
|
673 | 673 | for msg_id in sorted(jobs, key=lambda msg_id: self.depending[msg_id].timestamp): |
|
674 | 674 | job = self.depending[msg_id] |
|
675 | 675 | |
|
676 | 676 | if job.after.unreachable(self.all_completed, self.all_failed)\ |
|
677 | 677 | or job.follow.unreachable(self.all_completed, self.all_failed): |
|
678 | 678 | self.fail_unreachable(msg_id) |
|
679 | 679 | |
|
680 | 680 | elif job.after.check(self.all_completed, self.all_failed): # time deps met, maybe run |
|
681 | 681 | if self.maybe_run(job): |
|
682 | 682 | |
|
683 | 683 | self.depending.pop(msg_id) |
|
684 | 684 | for mid in job.dependents: |
|
685 | 685 | if mid in self.graph: |
|
686 | 686 | self.graph[mid].remove(msg_id) |
|
687 | 687 | |
|
688 | 688 | #---------------------------------------------------------------------- |
|
689 | 689 | # methods to be overridden by subclasses |
|
690 | 690 | #---------------------------------------------------------------------- |
|
691 | 691 | |
|
692 | 692 | def add_job(self, idx): |
|
693 | 693 | """Called after self.targets[idx] just got the job with header. |
|
694 | 694 | Override with subclasses. The default ordering is simple LRU. |
|
695 | 695 | The default loads are the number of outstanding jobs.""" |
|
696 | 696 | self.loads[idx] += 1 |
|
697 | 697 | for lis in (self.targets, self.loads): |
|
698 | 698 | lis.append(lis.pop(idx)) |
|
699 | 699 | |
|
700 | 700 | |
|
701 | 701 | def finish_job(self, idx): |
|
702 | 702 | """Called after self.targets[idx] just finished a job. |
|
703 | 703 | Override with subclasses.""" |
|
704 | 704 | self.loads[idx] -= 1 |
|
705 | 705 | |
|
706 | 706 | |
|
707 | 707 | |
|
708 | 708 | def launch_scheduler(in_addr, out_addr, mon_addr, not_addr, config=None, |
|
709 | 709 | logname='root', log_url=None, loglevel=logging.DEBUG, |
|
710 | 710 | identity=b'task', in_thread=False): |
|
711 | 711 | |
|
712 | 712 | ZMQStream = zmqstream.ZMQStream |
|
713 | 713 | |
|
714 | 714 | if config: |
|
715 | 715 | # unwrap dict back into Config |
|
716 | 716 | config = Config(config) |
|
717 | 717 | |
|
718 | 718 | if in_thread: |
|
719 | 719 | # use instance() to get the same Context/Loop as our parent |
|
720 | 720 | ctx = zmq.Context.instance() |
|
721 | 721 | loop = ioloop.IOLoop.instance() |
|
722 | 722 | else: |
|
723 | 723 | # in a process, don't use instance() |
|
724 | 724 | # for safety with multiprocessing |
|
725 | 725 | ctx = zmq.Context() |
|
726 | 726 | loop = ioloop.IOLoop() |
|
727 | 727 | ins = ZMQStream(ctx.socket(zmq.ROUTER),loop) |
|
728 | 728 | ins.setsockopt(zmq.IDENTITY, identity) |
|
729 | 729 | ins.bind(in_addr) |
|
730 | 730 | |
|
731 | 731 | outs = ZMQStream(ctx.socket(zmq.ROUTER),loop) |
|
732 | 732 | outs.setsockopt(zmq.IDENTITY, identity) |
|
733 | 733 | outs.bind(out_addr) |
|
734 | 734 | mons = zmqstream.ZMQStream(ctx.socket(zmq.PUB),loop) |
|
735 | 735 | mons.connect(mon_addr) |
|
736 | 736 | nots = zmqstream.ZMQStream(ctx.socket(zmq.SUB),loop) |
|
737 | 737 | nots.setsockopt(zmq.SUBSCRIBE, b'') |
|
738 | 738 | nots.connect(not_addr) |
|
739 | 739 | |
|
740 | 740 | # setup logging. |
|
741 | 741 | if in_thread: |
|
742 | 742 | log = Application.instance().log |
|
743 | 743 | else: |
|
744 | 744 | if log_url: |
|
745 | 745 | log = connect_logger(logname, ctx, log_url, root="scheduler", loglevel=loglevel) |
|
746 | 746 | else: |
|
747 | 747 | log = local_logger(logname, loglevel) |
|
748 | 748 | |
|
749 | 749 | scheduler = TaskScheduler(client_stream=ins, engine_stream=outs, |
|
750 | 750 | mon_stream=mons, notifier_stream=nots, |
|
751 | 751 | loop=loop, log=log, |
|
752 | 752 | config=config) |
|
753 | 753 | scheduler.start() |
|
754 | 754 | if not in_thread: |
|
755 | 755 | try: |
|
756 | 756 | loop.start() |
|
757 | 757 | except KeyboardInterrupt: |
|
758 | 758 | scheduler.log.critical("Interrupted, exiting...") |
|
759 | 759 |
@@ -1,120 +1,122 b'' | |||
|
1 | 1 | """toplevel setup/teardown for parallel tests.""" |
|
2 | 2 | |
|
3 | 3 | #------------------------------------------------------------------------------- |
|
4 | 4 | # Copyright (C) 2011 The IPython Development Team |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | 7 | # the file COPYING, distributed as part of this software. |
|
8 | 8 | #------------------------------------------------------------------------------- |
|
9 | 9 | |
|
10 | 10 | #------------------------------------------------------------------------------- |
|
11 | 11 | # Imports |
|
12 | 12 | #------------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | import os |
|
15 | 15 | import tempfile |
|
16 | 16 | import time |
|
17 | 17 | from subprocess import Popen |
|
18 | 18 | |
|
19 | 19 | from IPython.utils.path import get_ipython_dir |
|
20 | 20 | from IPython.parallel import Client |
|
21 | 21 | from IPython.parallel.apps.launcher import (LocalProcessLauncher, |
|
22 | 22 | ipengine_cmd_argv, |
|
23 | 23 | ipcontroller_cmd_argv, |
|
24 |
SIGKILL |
|
|
24 | SIGKILL, | |
|
25 | ProcessStateError, | |
|
26 | ) | |
|
25 | 27 | |
|
26 | 28 | # globals |
|
27 | 29 | launchers = [] |
|
28 | 30 | blackhole = open(os.devnull, 'w') |
|
29 | 31 | |
|
30 | 32 | # Launcher class |
|
31 | 33 | class TestProcessLauncher(LocalProcessLauncher): |
|
32 | 34 | """subclass LocalProcessLauncher, to prevent extra sockets and threads being created on Windows""" |
|
33 | 35 | def start(self): |
|
34 | 36 | if self.state == 'before': |
|
35 | 37 | self.process = Popen(self.args, |
|
36 | 38 | stdout=blackhole, stderr=blackhole, |
|
37 | 39 | env=os.environ, |
|
38 | 40 | cwd=self.work_dir |
|
39 | 41 | ) |
|
40 | 42 | self.notify_start(self.process.pid) |
|
41 | 43 | self.poll = self.process.poll |
|
42 | 44 | else: |
|
43 | 45 | s = 'The process was already started and has state: %r' % self.state |
|
44 | 46 | raise ProcessStateError(s) |
|
45 | 47 | |
|
46 | 48 | # nose setup/teardown |
|
47 | 49 | |
|
48 | 50 | def setup(): |
|
49 | 51 | cluster_dir = os.path.join(get_ipython_dir(), 'profile_iptest') |
|
50 | 52 | engine_json = os.path.join(cluster_dir, 'security', 'ipcontroller-engine.json') |
|
51 | 53 | client_json = os.path.join(cluster_dir, 'security', 'ipcontroller-client.json') |
|
52 | 54 | for json in (engine_json, client_json): |
|
53 | 55 | if os.path.exists(json): |
|
54 | 56 | os.remove(json) |
|
55 | 57 | |
|
56 | 58 | cp = TestProcessLauncher() |
|
57 | 59 | cp.cmd_and_args = ipcontroller_cmd_argv + \ |
|
58 | 60 | ['--profile=iptest', '--log-level=50', '--ping=250'] |
|
59 | 61 | cp.start() |
|
60 | 62 | launchers.append(cp) |
|
61 | 63 | tic = time.time() |
|
62 | 64 | while not os.path.exists(engine_json) or not os.path.exists(client_json): |
|
63 | 65 | if cp.poll() is not None: |
|
64 | 66 | print cp.poll() |
|
65 | 67 | raise RuntimeError("The test controller failed to start.") |
|
66 | 68 | elif time.time()-tic > 10: |
|
67 | 69 | raise RuntimeError("Timeout waiting for the test controller to start.") |
|
68 | 70 | time.sleep(0.1) |
|
69 | 71 | add_engines(1) |
|
70 | 72 | |
|
71 | 73 | def add_engines(n=1, profile='iptest', total=False): |
|
72 | 74 | """add a number of engines to a given profile. |
|
73 | 75 | |
|
74 | 76 | If total is True, then already running engines are counted, and only |
|
75 | 77 | the additional engines necessary (if any) are started. |
|
76 | 78 | """ |
|
77 | 79 | rc = Client(profile=profile) |
|
78 | 80 | base = len(rc) |
|
79 | 81 | |
|
80 | 82 | if total: |
|
81 | 83 | n = max(n - base, 0) |
|
82 | 84 | |
|
83 | 85 | eps = [] |
|
84 | 86 | for i in range(n): |
|
85 | 87 | ep = TestProcessLauncher() |
|
86 | 88 | ep.cmd_and_args = ipengine_cmd_argv + ['--profile=%s'%profile, '--log-level=50'] |
|
87 | 89 | ep.start() |
|
88 | 90 | launchers.append(ep) |
|
89 | 91 | eps.append(ep) |
|
90 | 92 | tic = time.time() |
|
91 | 93 | while len(rc) < base+n: |
|
92 | 94 | if any([ ep.poll() is not None for ep in eps ]): |
|
93 | 95 | raise RuntimeError("A test engine failed to start.") |
|
94 | 96 | elif time.time()-tic > 10: |
|
95 | 97 | raise RuntimeError("Timeout waiting for engines to connect.") |
|
96 | 98 | time.sleep(.1) |
|
97 | 99 | rc.spin() |
|
98 | 100 | rc.close() |
|
99 | 101 | return eps |
|
100 | 102 | |
|
101 | 103 | def teardown(): |
|
102 | 104 | time.sleep(1) |
|
103 | 105 | while launchers: |
|
104 | 106 | p = launchers.pop() |
|
105 | 107 | if p.poll() is None: |
|
106 | 108 | try: |
|
107 | 109 | p.stop() |
|
108 | 110 | except Exception, e: |
|
109 | 111 | print e |
|
110 | 112 | pass |
|
111 | 113 | if p.poll() is None: |
|
112 | 114 | time.sleep(.25) |
|
113 | 115 | if p.poll() is None: |
|
114 | 116 | try: |
|
115 | 117 | print 'cleaning up test process...' |
|
116 | 118 | p.signal(SIGKILL) |
|
117 | 119 | except: |
|
118 | 120 | print "couldn't shutdown process: ", p |
|
119 | 121 | blackhole.close() |
|
120 | 122 |
@@ -1,364 +1,364 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | |
|
3 | 3 | """ PickleShare - a small 'shelve' like datastore with concurrency support |
|
4 | 4 | |
|
5 | 5 | Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike |
|
6 | 6 | shelve, many processes can access the database simultaneously. Changing a |
|
7 | 7 | value in database is immediately visible to other processes accessing the |
|
8 | 8 | same database. |
|
9 | 9 | |
|
10 | 10 | Concurrency is possible because the values are stored in separate files. Hence |
|
11 | 11 | the "database" is a directory where *all* files are governed by PickleShare. |
|
12 | 12 | |
|
13 | 13 | Example usage:: |
|
14 | 14 | |
|
15 | 15 | from pickleshare import * |
|
16 | 16 | db = PickleShareDB('~/testpickleshare') |
|
17 | 17 | db.clear() |
|
18 | 18 | print "Should be empty:",db.items() |
|
19 | 19 | db['hello'] = 15 |
|
20 | 20 | db['aku ankka'] = [1,2,313] |
|
21 | 21 | db['paths/are/ok/key'] = [1,(5,46)] |
|
22 | 22 | print db.keys() |
|
23 | 23 | del db['aku ankka'] |
|
24 | 24 | |
|
25 | 25 | This module is certainly not ZODB, but can be used for low-load |
|
26 | 26 | (non-mission-critical) situations where tiny code size trumps the |
|
27 | 27 | advanced features of a "real" object database. |
|
28 | 28 | |
|
29 | 29 | Installation guide: easy_install pickleshare |
|
30 | 30 | |
|
31 | 31 | Author: Ville Vainio <vivainio@gmail.com> |
|
32 | 32 | License: MIT open source license. |
|
33 | 33 | |
|
34 | 34 | """ |
|
35 | 35 | |
|
36 | 36 | from IPython.external.path import path as Path |
|
37 | 37 | import os,stat,time |
|
38 | 38 | import collections |
|
39 | 39 | import cPickle as pickle |
|
40 | 40 | import glob |
|
41 | 41 | |
|
42 | 42 | def gethashfile(key): |
|
43 | 43 | return ("%02x" % abs(hash(key) % 256))[-2:] |
|
44 | 44 | |
|
45 | 45 | _sentinel = object() |
|
46 | 46 | |
|
47 | 47 | class PickleShareDB(collections.MutableMapping): |
|
48 | 48 | """ The main 'connection' object for PickleShare database """ |
|
49 | 49 | def __init__(self,root): |
|
50 | 50 | """ Return a db object that will manage the specied directory""" |
|
51 | 51 | self.root = Path(root).expanduser().abspath() |
|
52 | 52 | if not self.root.isdir(): |
|
53 | 53 | self.root.makedirs() |
|
54 | 54 | # cache has { 'key' : (obj, orig_mod_time) } |
|
55 | 55 | self.cache = {} |
|
56 | 56 | |
|
57 | 57 | |
|
58 | 58 | def __getitem__(self,key): |
|
59 | 59 | """ db['key'] reading """ |
|
60 | 60 | fil = self.root / key |
|
61 | 61 | try: |
|
62 | 62 | mtime = (fil.stat()[stat.ST_MTIME]) |
|
63 | 63 | except OSError: |
|
64 | 64 | raise KeyError(key) |
|
65 | 65 | |
|
66 | 66 | if fil in self.cache and mtime == self.cache[fil][1]: |
|
67 | 67 | return self.cache[fil][0] |
|
68 | 68 | try: |
|
69 | 69 | # The cached item has expired, need to read |
|
70 | 70 | obj = pickle.loads(fil.open("rb").read()) |
|
71 | 71 | except: |
|
72 | 72 | raise KeyError(key) |
|
73 | 73 | |
|
74 | 74 | self.cache[fil] = (obj,mtime) |
|
75 | 75 | return obj |
|
76 | 76 | |
|
77 | 77 | def __setitem__(self,key,value): |
|
78 | 78 | """ db['key'] = 5 """ |
|
79 | 79 | fil = self.root / key |
|
80 | 80 | parent = fil.parent |
|
81 | 81 | if parent and not parent.isdir(): |
|
82 | 82 | parent.makedirs() |
|
83 | 83 | # We specify protocol 2, so that we can mostly go between Python 2 |
|
84 | 84 | # and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete. |
|
85 | 85 | pickled = pickle.dump(value,fil.open('wb'), protocol=2) |
|
86 | 86 | try: |
|
87 | 87 | self.cache[fil] = (value,fil.mtime) |
|
88 | 88 | except OSError,e: |
|
89 | 89 | if e.errno != 2: |
|
90 | 90 | raise |
|
91 | 91 | |
|
92 | 92 | def hset(self, hashroot, key, value): |
|
93 | 93 | """ hashed set """ |
|
94 | 94 | hroot = self.root / hashroot |
|
95 | 95 | if not hroot.isdir(): |
|
96 | 96 | hroot.makedirs() |
|
97 | 97 | hfile = hroot / gethashfile(key) |
|
98 | 98 | d = self.get(hfile, {}) |
|
99 | 99 | d.update( {key : value}) |
|
100 | 100 | self[hfile] = d |
|
101 | 101 | |
|
102 | 102 | |
|
103 | 103 | |
|
104 | 104 | def hget(self, hashroot, key, default = _sentinel, fast_only = True): |
|
105 | 105 | """ hashed get """ |
|
106 | 106 | hroot = self.root / hashroot |
|
107 | 107 | hfile = hroot / gethashfile(key) |
|
108 | 108 | |
|
109 | 109 | d = self.get(hfile, _sentinel ) |
|
110 | 110 | #print "got dict",d,"from",hfile |
|
111 | 111 | if d is _sentinel: |
|
112 | 112 | if fast_only: |
|
113 | 113 | if default is _sentinel: |
|
114 | 114 | raise KeyError(key) |
|
115 | 115 | |
|
116 | 116 | return default |
|
117 | 117 | |
|
118 | 118 | # slow mode ok, works even after hcompress() |
|
119 | 119 | d = self.hdict(hashroot) |
|
120 | 120 | |
|
121 | 121 | return d.get(key, default) |
|
122 | 122 | |
|
123 | 123 | def hdict(self, hashroot): |
|
124 | 124 | """ Get all data contained in hashed category 'hashroot' as dict """ |
|
125 | 125 | hfiles = self.keys(hashroot + "/*") |
|
126 | 126 | hfiles.sort() |
|
127 | 127 | last = len(hfiles) and hfiles[-1] or '' |
|
128 | 128 | if last.endswith('xx'): |
|
129 | 129 | # print "using xx" |
|
130 | 130 | hfiles = [last] + hfiles[:-1] |
|
131 | 131 | |
|
132 | 132 | all = {} |
|
133 | 133 | |
|
134 | 134 | for f in hfiles: |
|
135 | 135 | # print "using",f |
|
136 | 136 | try: |
|
137 | 137 | all.update(self[f]) |
|
138 | 138 | except KeyError: |
|
139 | 139 | print "Corrupt",f,"deleted - hset is not threadsafe!" |
|
140 | 140 | del self[f] |
|
141 | 141 | |
|
142 | 142 | self.uncache(f) |
|
143 | 143 | |
|
144 | 144 | return all |
|
145 | 145 | |
|
146 | 146 | def hcompress(self, hashroot): |
|
147 | 147 | """ Compress category 'hashroot', so hset is fast again |
|
148 | 148 | |
|
149 | 149 | hget will fail if fast_only is True for compressed items (that were |
|
150 | 150 | hset before hcompress). |
|
151 | 151 | |
|
152 | 152 | """ |
|
153 | 153 | hfiles = self.keys(hashroot + "/*") |
|
154 | 154 | all = {} |
|
155 | 155 | for f in hfiles: |
|
156 | 156 | # print "using",f |
|
157 | 157 | all.update(self[f]) |
|
158 | 158 | self.uncache(f) |
|
159 | 159 | |
|
160 | 160 | self[hashroot + '/xx'] = all |
|
161 | 161 | for f in hfiles: |
|
162 | 162 | p = self.root / f |
|
163 | 163 | if p.basename() == 'xx': |
|
164 | 164 | continue |
|
165 | 165 | p.remove() |
|
166 | 166 | |
|
167 | 167 | |
|
168 | 168 | |
|
169 | 169 | def __delitem__(self,key): |
|
170 | 170 | """ del db["key"] """ |
|
171 | 171 | fil = self.root / key |
|
172 | 172 | self.cache.pop(fil,None) |
|
173 | 173 | try: |
|
174 | 174 | fil.remove() |
|
175 | 175 | except OSError: |
|
176 | 176 | # notfound and permission denied are ok - we |
|
177 | 177 | # lost, the other process wins the conflict |
|
178 | 178 | pass |
|
179 | 179 | |
|
180 | 180 | def _normalized(self, p): |
|
181 | 181 | """ Make a key suitable for user's eyes """ |
|
182 | 182 | return str(self.root.relpathto(p)).replace('\\','/') |
|
183 | 183 | |
|
184 | 184 | def keys(self, globpat = None): |
|
185 | 185 | """ All keys in DB, or all keys matching a glob""" |
|
186 | 186 | |
|
187 | 187 | if globpat is None: |
|
188 | 188 | files = self.root.walkfiles() |
|
189 | 189 | else: |
|
190 | 190 | files = [Path(p) for p in glob.glob(self.root/globpat)] |
|
191 | 191 | return [self._normalized(p) for p in files if p.isfile()] |
|
192 | 192 | |
|
193 | 193 | def __iter__(self): |
|
194 | return iter(keys) | |
|
194 | return iter(self.keys()) | |
|
195 | 195 | |
|
196 | 196 | def __len__(self): |
|
197 | return len(keys) | |
|
197 | return len(self.keys()) | |
|
198 | 198 | |
|
199 | 199 | def uncache(self,*items): |
|
200 | 200 | """ Removes all, or specified items from cache |
|
201 | 201 | |
|
202 | 202 | Use this after reading a large amount of large objects |
|
203 | 203 | to free up memory, when you won't be needing the objects |
|
204 | 204 | for a while. |
|
205 | 205 | |
|
206 | 206 | """ |
|
207 | 207 | if not items: |
|
208 | 208 | self.cache = {} |
|
209 | 209 | for it in items: |
|
210 | 210 | self.cache.pop(it,None) |
|
211 | 211 | |
|
212 | 212 | def waitget(self,key, maxwaittime = 60 ): |
|
213 | 213 | """ Wait (poll) for a key to get a value |
|
214 | 214 | |
|
215 | 215 | Will wait for `maxwaittime` seconds before raising a KeyError. |
|
216 | 216 | The call exits normally if the `key` field in db gets a value |
|
217 | 217 | within the timeout period. |
|
218 | 218 | |
|
219 | 219 | Use this for synchronizing different processes or for ensuring |
|
220 | 220 | that an unfortunately timed "db['key'] = newvalue" operation |
|
221 | 221 | in another process (which causes all 'get' operation to cause a |
|
222 | 222 | KeyError for the duration of pickling) won't screw up your program |
|
223 | 223 | logic. |
|
224 | 224 | """ |
|
225 | 225 | |
|
226 | 226 | wtimes = [0.2] * 3 + [0.5] * 2 + [1] |
|
227 | 227 | tries = 0 |
|
228 | 228 | waited = 0 |
|
229 | 229 | while 1: |
|
230 | 230 | try: |
|
231 | 231 | val = self[key] |
|
232 | 232 | return val |
|
233 | 233 | except KeyError: |
|
234 | 234 | pass |
|
235 | 235 | |
|
236 | 236 | if waited > maxwaittime: |
|
237 | 237 | raise KeyError(key) |
|
238 | 238 | |
|
239 | 239 | time.sleep(wtimes[tries]) |
|
240 | 240 | waited+=wtimes[tries] |
|
241 | 241 | if tries < len(wtimes) -1: |
|
242 | 242 | tries+=1 |
|
243 | 243 | |
|
244 | 244 | def getlink(self,folder): |
|
245 | 245 | """ Get a convenient link for accessing items """ |
|
246 | 246 | return PickleShareLink(self, folder) |
|
247 | 247 | |
|
248 | 248 | def __repr__(self): |
|
249 | 249 | return "PickleShareDB('%s')" % self.root |
|
250 | 250 | |
|
251 | 251 | |
|
252 | 252 | |
|
253 | 253 | class PickleShareLink: |
|
254 | 254 | """ A shortdand for accessing nested PickleShare data conveniently. |
|
255 | 255 | |
|
256 | 256 | Created through PickleShareDB.getlink(), example:: |
|
257 | 257 | |
|
258 | 258 | lnk = db.getlink('myobjects/test') |
|
259 | 259 | lnk.foo = 2 |
|
260 | 260 | lnk.bar = lnk.foo + 5 |
|
261 | 261 | |
|
262 | 262 | """ |
|
263 | 263 | def __init__(self, db, keydir ): |
|
264 | 264 | self.__dict__.update(locals()) |
|
265 | 265 | |
|
266 | 266 | def __getattr__(self,key): |
|
267 | 267 | return self.__dict__['db'][self.__dict__['keydir']+'/' + key] |
|
268 | 268 | def __setattr__(self,key,val): |
|
269 | 269 | self.db[self.keydir+'/' + key] = val |
|
270 | 270 | def __repr__(self): |
|
271 | 271 | db = self.__dict__['db'] |
|
272 | 272 | keys = db.keys( self.__dict__['keydir'] +"/*") |
|
273 | 273 | return "<PickleShareLink '%s': %s>" % ( |
|
274 | 274 | self.__dict__['keydir'], |
|
275 | 275 | ";".join([Path(k).basename() for k in keys])) |
|
276 | 276 | |
|
277 | 277 | |
|
278 | 278 | def test(): |
|
279 | 279 | db = PickleShareDB('~/testpickleshare') |
|
280 | 280 | db.clear() |
|
281 | 281 | print "Should be empty:",db.items() |
|
282 | 282 | db['hello'] = 15 |
|
283 | 283 | db['aku ankka'] = [1,2,313] |
|
284 | 284 | db['paths/nest/ok/keyname'] = [1,(5,46)] |
|
285 | 285 | db.hset('hash', 'aku', 12) |
|
286 | 286 | db.hset('hash', 'ankka', 313) |
|
287 | 287 | print "12 =",db.hget('hash','aku') |
|
288 | 288 | print "313 =",db.hget('hash','ankka') |
|
289 | 289 | print "all hashed",db.hdict('hash') |
|
290 | 290 | print db.keys() |
|
291 | 291 | print db.keys('paths/nest/ok/k*') |
|
292 | 292 | print dict(db) # snapsot of whole db |
|
293 | 293 | db.uncache() # frees memory, causes re-reads later |
|
294 | 294 | |
|
295 | 295 | # shorthand for accessing deeply nested files |
|
296 | 296 | lnk = db.getlink('myobjects/test') |
|
297 | 297 | lnk.foo = 2 |
|
298 | 298 | lnk.bar = lnk.foo + 5 |
|
299 | 299 | print lnk.bar # 7 |
|
300 | 300 | |
|
301 | 301 | def stress(): |
|
302 | 302 | db = PickleShareDB('~/fsdbtest') |
|
303 | 303 | import time,sys |
|
304 | 304 | for i in range(1000): |
|
305 | 305 | for j in range(1000): |
|
306 | 306 | if i % 15 == 0 and i < 200: |
|
307 | 307 | if str(j) in db: |
|
308 | 308 | del db[str(j)] |
|
309 | 309 | continue |
|
310 | 310 | |
|
311 | 311 | if j%33 == 0: |
|
312 | 312 | time.sleep(0.02) |
|
313 | 313 | |
|
314 | 314 | db[str(j)] = db.get(str(j), []) + [(i,j,"proc %d" % os.getpid())] |
|
315 | 315 | db.hset('hash',j, db.hget('hash',j,15) + 1 ) |
|
316 | 316 | |
|
317 | 317 | print i, |
|
318 | 318 | sys.stdout.flush() |
|
319 | 319 | if i % 10 == 0: |
|
320 | 320 | db.uncache() |
|
321 | 321 | |
|
322 | 322 | def main(): |
|
323 | 323 | import textwrap |
|
324 | 324 | usage = textwrap.dedent("""\ |
|
325 | 325 | pickleshare - manage PickleShare databases |
|
326 | 326 | |
|
327 | 327 | Usage: |
|
328 | 328 | |
|
329 | 329 | pickleshare dump /path/to/db > dump.txt |
|
330 | 330 | pickleshare load /path/to/db < dump.txt |
|
331 | 331 | pickleshare test /path/to/db |
|
332 | 332 | """) |
|
333 | 333 | DB = PickleShareDB |
|
334 | 334 | import sys |
|
335 | 335 | if len(sys.argv) < 2: |
|
336 | 336 | print usage |
|
337 | 337 | return |
|
338 | 338 | |
|
339 | 339 | cmd = sys.argv[1] |
|
340 | 340 | args = sys.argv[2:] |
|
341 | 341 | if cmd == 'dump': |
|
342 | 342 | if not args: args= ['.'] |
|
343 | 343 | db = DB(args[0]) |
|
344 | 344 | import pprint |
|
345 | 345 | pprint.pprint(db.items()) |
|
346 | 346 | elif cmd == 'load': |
|
347 | 347 | cont = sys.stdin.read() |
|
348 | 348 | db = DB(args[0]) |
|
349 | 349 | data = eval(cont) |
|
350 | 350 | db.clear() |
|
351 | 351 | for k,v in db.items(): |
|
352 | 352 | db[k] = v |
|
353 | 353 | elif cmd == 'testwait': |
|
354 | 354 | db = DB(args[0]) |
|
355 | 355 | db.clear() |
|
356 | 356 | print db.waitget('250') |
|
357 | 357 | elif cmd == 'test': |
|
358 | 358 | test() |
|
359 | 359 | stress() |
|
360 | 360 | |
|
361 | 361 | if __name__== "__main__": |
|
362 | 362 | main() |
|
363 | 363 | |
|
364 | 364 |
@@ -1,890 +1,892 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Tests for IPython.utils.traitlets. |
|
4 | 4 | |
|
5 | 5 | Authors: |
|
6 | 6 | |
|
7 | 7 | * Brian Granger |
|
8 | 8 | * Enthought, Inc. Some of the code in this file comes from enthought.traits |
|
9 | 9 | and is licensed under the BSD license. Also, many of the ideas also come |
|
10 | 10 | from enthought.traits even though our implementation is very different. |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Copyright (C) 2008-2011 The IPython Development Team |
|
15 | 15 | # |
|
16 | 16 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | 17 | # the file COPYING, distributed as part of this software. |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | # Imports |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | |
|
24 | 24 | import sys |
|
25 | 25 | from unittest import TestCase |
|
26 | 26 | |
|
27 | from nose import SkipTest | |
|
28 | ||
|
27 | 29 | from IPython.utils.traitlets import ( |
|
28 | 30 | HasTraits, MetaHasTraits, TraitType, Any, CBytes, |
|
29 | 31 | Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError, |
|
30 | 32 | Undefined, Type, This, Instance, TCPAddress, List, Tuple, |
|
31 | 33 | ObjectName, DottedObjectName |
|
32 | 34 | ) |
|
33 | 35 | from IPython.utils import py3compat |
|
34 | 36 | from IPython.testing.decorators import skipif |
|
35 | 37 | |
|
36 | 38 | #----------------------------------------------------------------------------- |
|
37 | 39 | # Helper classes for testing |
|
38 | 40 | #----------------------------------------------------------------------------- |
|
39 | 41 | |
|
40 | 42 | |
|
41 | 43 | class HasTraitsStub(HasTraits): |
|
42 | 44 | |
|
43 | 45 | def _notify_trait(self, name, old, new): |
|
44 | 46 | self._notify_name = name |
|
45 | 47 | self._notify_old = old |
|
46 | 48 | self._notify_new = new |
|
47 | 49 | |
|
48 | 50 | |
|
49 | 51 | #----------------------------------------------------------------------------- |
|
50 | 52 | # Test classes |
|
51 | 53 | #----------------------------------------------------------------------------- |
|
52 | 54 | |
|
53 | 55 | |
|
54 | 56 | class TestTraitType(TestCase): |
|
55 | 57 | |
|
56 | 58 | def test_get_undefined(self): |
|
57 | 59 | class A(HasTraits): |
|
58 | 60 | a = TraitType |
|
59 | 61 | a = A() |
|
60 | 62 | self.assertEquals(a.a, Undefined) |
|
61 | 63 | |
|
62 | 64 | def test_set(self): |
|
63 | 65 | class A(HasTraitsStub): |
|
64 | 66 | a = TraitType |
|
65 | 67 | |
|
66 | 68 | a = A() |
|
67 | 69 | a.a = 10 |
|
68 | 70 | self.assertEquals(a.a, 10) |
|
69 | 71 | self.assertEquals(a._notify_name, 'a') |
|
70 | 72 | self.assertEquals(a._notify_old, Undefined) |
|
71 | 73 | self.assertEquals(a._notify_new, 10) |
|
72 | 74 | |
|
73 | 75 | def test_validate(self): |
|
74 | 76 | class MyTT(TraitType): |
|
75 | 77 | def validate(self, inst, value): |
|
76 | 78 | return -1 |
|
77 | 79 | class A(HasTraitsStub): |
|
78 | 80 | tt = MyTT |
|
79 | 81 | |
|
80 | 82 | a = A() |
|
81 | 83 | a.tt = 10 |
|
82 | 84 | self.assertEquals(a.tt, -1) |
|
83 | 85 | |
|
84 | 86 | def test_default_validate(self): |
|
85 | 87 | class MyIntTT(TraitType): |
|
86 | 88 | def validate(self, obj, value): |
|
87 | 89 | if isinstance(value, int): |
|
88 | 90 | return value |
|
89 | 91 | self.error(obj, value) |
|
90 | 92 | class A(HasTraits): |
|
91 | 93 | tt = MyIntTT(10) |
|
92 | 94 | a = A() |
|
93 | 95 | self.assertEquals(a.tt, 10) |
|
94 | 96 | |
|
95 | 97 | # Defaults are validated when the HasTraits is instantiated |
|
96 | 98 | class B(HasTraits): |
|
97 | 99 | tt = MyIntTT('bad default') |
|
98 | 100 | self.assertRaises(TraitError, B) |
|
99 | 101 | |
|
100 | 102 | def test_is_valid_for(self): |
|
101 | 103 | class MyTT(TraitType): |
|
102 | 104 | def is_valid_for(self, value): |
|
103 | 105 | return True |
|
104 | 106 | class A(HasTraits): |
|
105 | 107 | tt = MyTT |
|
106 | 108 | |
|
107 | 109 | a = A() |
|
108 | 110 | a.tt = 10 |
|
109 | 111 | self.assertEquals(a.tt, 10) |
|
110 | 112 | |
|
111 | 113 | def test_value_for(self): |
|
112 | 114 | class MyTT(TraitType): |
|
113 | 115 | def value_for(self, value): |
|
114 | 116 | return 20 |
|
115 | 117 | class A(HasTraits): |
|
116 | 118 | tt = MyTT |
|
117 | 119 | |
|
118 | 120 | a = A() |
|
119 | 121 | a.tt = 10 |
|
120 | 122 | self.assertEquals(a.tt, 20) |
|
121 | 123 | |
|
122 | 124 | def test_info(self): |
|
123 | 125 | class A(HasTraits): |
|
124 | 126 | tt = TraitType |
|
125 | 127 | a = A() |
|
126 | 128 | self.assertEquals(A.tt.info(), 'any value') |
|
127 | 129 | |
|
128 | 130 | def test_error(self): |
|
129 | 131 | class A(HasTraits): |
|
130 | 132 | tt = TraitType |
|
131 | 133 | a = A() |
|
132 | 134 | self.assertRaises(TraitError, A.tt.error, a, 10) |
|
133 | 135 | |
|
134 | 136 | def test_dynamic_initializer(self): |
|
135 | 137 | class A(HasTraits): |
|
136 | 138 | x = Int(10) |
|
137 | 139 | def _x_default(self): |
|
138 | 140 | return 11 |
|
139 | 141 | class B(A): |
|
140 | 142 | x = Int(20) |
|
141 | 143 | class C(A): |
|
142 | 144 | def _x_default(self): |
|
143 | 145 | return 21 |
|
144 | 146 | |
|
145 | 147 | a = A() |
|
146 | 148 | self.assertEquals(a._trait_values, {}) |
|
147 | 149 | self.assertEquals(a._trait_dyn_inits.keys(), ['x']) |
|
148 | 150 | self.assertEquals(a.x, 11) |
|
149 | 151 | self.assertEquals(a._trait_values, {'x': 11}) |
|
150 | 152 | b = B() |
|
151 | 153 | self.assertEquals(b._trait_values, {'x': 20}) |
|
152 | 154 | self.assertEquals(a._trait_dyn_inits.keys(), ['x']) |
|
153 | 155 | self.assertEquals(b.x, 20) |
|
154 | 156 | c = C() |
|
155 | 157 | self.assertEquals(c._trait_values, {}) |
|
156 | 158 | self.assertEquals(a._trait_dyn_inits.keys(), ['x']) |
|
157 | 159 | self.assertEquals(c.x, 21) |
|
158 | 160 | self.assertEquals(c._trait_values, {'x': 21}) |
|
159 | 161 | # Ensure that the base class remains unmolested when the _default |
|
160 | 162 | # initializer gets overridden in a subclass. |
|
161 | 163 | a = A() |
|
162 | 164 | c = C() |
|
163 | 165 | self.assertEquals(a._trait_values, {}) |
|
164 | 166 | self.assertEquals(a._trait_dyn_inits.keys(), ['x']) |
|
165 | 167 | self.assertEquals(a.x, 11) |
|
166 | 168 | self.assertEquals(a._trait_values, {'x': 11}) |
|
167 | 169 | |
|
168 | 170 | |
|
169 | 171 | |
|
170 | 172 | class TestHasTraitsMeta(TestCase): |
|
171 | 173 | |
|
172 | 174 | def test_metaclass(self): |
|
173 | 175 | self.assertEquals(type(HasTraits), MetaHasTraits) |
|
174 | 176 | |
|
175 | 177 | class A(HasTraits): |
|
176 | 178 | a = Int |
|
177 | 179 | |
|
178 | 180 | a = A() |
|
179 | 181 | self.assertEquals(type(a.__class__), MetaHasTraits) |
|
180 | 182 | self.assertEquals(a.a,0) |
|
181 | 183 | a.a = 10 |
|
182 | 184 | self.assertEquals(a.a,10) |
|
183 | 185 | |
|
184 | 186 | class B(HasTraits): |
|
185 | 187 | b = Int() |
|
186 | 188 | |
|
187 | 189 | b = B() |
|
188 | 190 | self.assertEquals(b.b,0) |
|
189 | 191 | b.b = 10 |
|
190 | 192 | self.assertEquals(b.b,10) |
|
191 | 193 | |
|
192 | 194 | class C(HasTraits): |
|
193 | 195 | c = Int(30) |
|
194 | 196 | |
|
195 | 197 | c = C() |
|
196 | 198 | self.assertEquals(c.c,30) |
|
197 | 199 | c.c = 10 |
|
198 | 200 | self.assertEquals(c.c,10) |
|
199 | 201 | |
|
200 | 202 | def test_this_class(self): |
|
201 | 203 | class A(HasTraits): |
|
202 | 204 | t = This() |
|
203 | 205 | tt = This() |
|
204 | 206 | class B(A): |
|
205 | 207 | tt = This() |
|
206 | 208 | ttt = This() |
|
207 | 209 | self.assertEquals(A.t.this_class, A) |
|
208 | 210 | self.assertEquals(B.t.this_class, A) |
|
209 | 211 | self.assertEquals(B.tt.this_class, B) |
|
210 | 212 | self.assertEquals(B.ttt.this_class, B) |
|
211 | 213 | |
|
212 | 214 | class TestHasTraitsNotify(TestCase): |
|
213 | 215 | |
|
214 | 216 | def setUp(self): |
|
215 | 217 | self._notify1 = [] |
|
216 | 218 | self._notify2 = [] |
|
217 | 219 | |
|
218 | 220 | def notify1(self, name, old, new): |
|
219 | 221 | self._notify1.append((name, old, new)) |
|
220 | 222 | |
|
221 | 223 | def notify2(self, name, old, new): |
|
222 | 224 | self._notify2.append((name, old, new)) |
|
223 | 225 | |
|
224 | 226 | def test_notify_all(self): |
|
225 | 227 | |
|
226 | 228 | class A(HasTraits): |
|
227 | 229 | a = Int |
|
228 | 230 | b = Float |
|
229 | 231 | |
|
230 | 232 | a = A() |
|
231 | 233 | a.on_trait_change(self.notify1) |
|
232 | 234 | a.a = 0 |
|
233 | 235 | self.assertEquals(len(self._notify1),0) |
|
234 | 236 | a.b = 0.0 |
|
235 | 237 | self.assertEquals(len(self._notify1),0) |
|
236 | 238 | a.a = 10 |
|
237 | 239 | self.assert_(('a',0,10) in self._notify1) |
|
238 | 240 | a.b = 10.0 |
|
239 | 241 | self.assert_(('b',0.0,10.0) in self._notify1) |
|
240 | 242 | self.assertRaises(TraitError,setattr,a,'a','bad string') |
|
241 | 243 | self.assertRaises(TraitError,setattr,a,'b','bad string') |
|
242 | 244 | self._notify1 = [] |
|
243 | 245 | a.on_trait_change(self.notify1,remove=True) |
|
244 | 246 | a.a = 20 |
|
245 | 247 | a.b = 20.0 |
|
246 | 248 | self.assertEquals(len(self._notify1),0) |
|
247 | 249 | |
|
248 | 250 | def test_notify_one(self): |
|
249 | 251 | |
|
250 | 252 | class A(HasTraits): |
|
251 | 253 | a = Int |
|
252 | 254 | b = Float |
|
253 | 255 | |
|
254 | 256 | a = A() |
|
255 | 257 | a.on_trait_change(self.notify1, 'a') |
|
256 | 258 | a.a = 0 |
|
257 | 259 | self.assertEquals(len(self._notify1),0) |
|
258 | 260 | a.a = 10 |
|
259 | 261 | self.assert_(('a',0,10) in self._notify1) |
|
260 | 262 | self.assertRaises(TraitError,setattr,a,'a','bad string') |
|
261 | 263 | |
|
262 | 264 | def test_subclass(self): |
|
263 | 265 | |
|
264 | 266 | class A(HasTraits): |
|
265 | 267 | a = Int |
|
266 | 268 | |
|
267 | 269 | class B(A): |
|
268 | 270 | b = Float |
|
269 | 271 | |
|
270 | 272 | b = B() |
|
271 | 273 | self.assertEquals(b.a,0) |
|
272 | 274 | self.assertEquals(b.b,0.0) |
|
273 | 275 | b.a = 100 |
|
274 | 276 | b.b = 100.0 |
|
275 | 277 | self.assertEquals(b.a,100) |
|
276 | 278 | self.assertEquals(b.b,100.0) |
|
277 | 279 | |
|
278 | 280 | def test_notify_subclass(self): |
|
279 | 281 | |
|
280 | 282 | class A(HasTraits): |
|
281 | 283 | a = Int |
|
282 | 284 | |
|
283 | 285 | class B(A): |
|
284 | 286 | b = Float |
|
285 | 287 | |
|
286 | 288 | b = B() |
|
287 | 289 | b.on_trait_change(self.notify1, 'a') |
|
288 | 290 | b.on_trait_change(self.notify2, 'b') |
|
289 | 291 | b.a = 0 |
|
290 | 292 | b.b = 0.0 |
|
291 | 293 | self.assertEquals(len(self._notify1),0) |
|
292 | 294 | self.assertEquals(len(self._notify2),0) |
|
293 | 295 | b.a = 10 |
|
294 | 296 | b.b = 10.0 |
|
295 | 297 | self.assert_(('a',0,10) in self._notify1) |
|
296 | 298 | self.assert_(('b',0.0,10.0) in self._notify2) |
|
297 | 299 | |
|
298 | 300 | def test_static_notify(self): |
|
299 | 301 | |
|
300 | 302 | class A(HasTraits): |
|
301 | 303 | a = Int |
|
302 | 304 | _notify1 = [] |
|
303 | 305 | def _a_changed(self, name, old, new): |
|
304 | 306 | self._notify1.append((name, old, new)) |
|
305 | 307 | |
|
306 | 308 | a = A() |
|
307 | 309 | a.a = 0 |
|
308 | 310 | # This is broken!!! |
|
309 | 311 | self.assertEquals(len(a._notify1),0) |
|
310 | 312 | a.a = 10 |
|
311 | 313 | self.assert_(('a',0,10) in a._notify1) |
|
312 | 314 | |
|
313 | 315 | class B(A): |
|
314 | 316 | b = Float |
|
315 | 317 | _notify2 = [] |
|
316 | 318 | def _b_changed(self, name, old, new): |
|
317 | 319 | self._notify2.append((name, old, new)) |
|
318 | 320 | |
|
319 | 321 | b = B() |
|
320 | 322 | b.a = 10 |
|
321 | 323 | b.b = 10.0 |
|
322 | 324 | self.assert_(('a',0,10) in b._notify1) |
|
323 | 325 | self.assert_(('b',0.0,10.0) in b._notify2) |
|
324 | 326 | |
|
325 | 327 | def test_notify_args(self): |
|
326 | 328 | |
|
327 | 329 | def callback0(): |
|
328 | 330 | self.cb = () |
|
329 | 331 | def callback1(name): |
|
330 | 332 | self.cb = (name,) |
|
331 | 333 | def callback2(name, new): |
|
332 | 334 | self.cb = (name, new) |
|
333 | 335 | def callback3(name, old, new): |
|
334 | 336 | self.cb = (name, old, new) |
|
335 | 337 | |
|
336 | 338 | class A(HasTraits): |
|
337 | 339 | a = Int |
|
338 | 340 | |
|
339 | 341 | a = A() |
|
340 | 342 | a.on_trait_change(callback0, 'a') |
|
341 | 343 | a.a = 10 |
|
342 | 344 | self.assertEquals(self.cb,()) |
|
343 | 345 | a.on_trait_change(callback0, 'a', remove=True) |
|
344 | 346 | |
|
345 | 347 | a.on_trait_change(callback1, 'a') |
|
346 | 348 | a.a = 100 |
|
347 | 349 | self.assertEquals(self.cb,('a',)) |
|
348 | 350 | a.on_trait_change(callback1, 'a', remove=True) |
|
349 | 351 | |
|
350 | 352 | a.on_trait_change(callback2, 'a') |
|
351 | 353 | a.a = 1000 |
|
352 | 354 | self.assertEquals(self.cb,('a',1000)) |
|
353 | 355 | a.on_trait_change(callback2, 'a', remove=True) |
|
354 | 356 | |
|
355 | 357 | a.on_trait_change(callback3, 'a') |
|
356 | 358 | a.a = 10000 |
|
357 | 359 | self.assertEquals(self.cb,('a',1000,10000)) |
|
358 | 360 | a.on_trait_change(callback3, 'a', remove=True) |
|
359 | 361 | |
|
360 | 362 | self.assertEquals(len(a._trait_notifiers['a']),0) |
|
361 | 363 | |
|
362 | 364 | |
|
363 | 365 | class TestHasTraits(TestCase): |
|
364 | 366 | |
|
365 | 367 | def test_trait_names(self): |
|
366 | 368 | class A(HasTraits): |
|
367 | 369 | i = Int |
|
368 | 370 | f = Float |
|
369 | 371 | a = A() |
|
370 | 372 | self.assertEquals(a.trait_names(),['i','f']) |
|
371 | 373 | self.assertEquals(A.class_trait_names(),['i','f']) |
|
372 | 374 | |
|
373 | 375 | def test_trait_metadata(self): |
|
374 | 376 | class A(HasTraits): |
|
375 | 377 | i = Int(config_key='MY_VALUE') |
|
376 | 378 | a = A() |
|
377 | 379 | self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE') |
|
378 | 380 | |
|
379 | 381 | def test_traits(self): |
|
380 | 382 | class A(HasTraits): |
|
381 | 383 | i = Int |
|
382 | 384 | f = Float |
|
383 | 385 | a = A() |
|
384 | 386 | self.assertEquals(a.traits(), dict(i=A.i, f=A.f)) |
|
385 | 387 | self.assertEquals(A.class_traits(), dict(i=A.i, f=A.f)) |
|
386 | 388 | |
|
387 | 389 | def test_traits_metadata(self): |
|
388 | 390 | class A(HasTraits): |
|
389 | 391 | i = Int(config_key='VALUE1', other_thing='VALUE2') |
|
390 | 392 | f = Float(config_key='VALUE3', other_thing='VALUE2') |
|
391 | 393 | j = Int(0) |
|
392 | 394 | a = A() |
|
393 | 395 | self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j)) |
|
394 | 396 | traits = a.traits(config_key='VALUE1', other_thing='VALUE2') |
|
395 | 397 | self.assertEquals(traits, dict(i=A.i)) |
|
396 | 398 | |
|
397 | 399 | # This passes, but it shouldn't because I am replicating a bug in |
|
398 | 400 | # traits. |
|
399 | 401 | traits = a.traits(config_key=lambda v: True) |
|
400 | 402 | self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j)) |
|
401 | 403 | |
|
402 | 404 | def test_init(self): |
|
403 | 405 | class A(HasTraits): |
|
404 | 406 | i = Int() |
|
405 | 407 | x = Float() |
|
406 | 408 | a = A(i=1, x=10.0) |
|
407 | 409 | self.assertEquals(a.i, 1) |
|
408 | 410 | self.assertEquals(a.x, 10.0) |
|
409 | 411 | |
|
410 | 412 | #----------------------------------------------------------------------------- |
|
411 | 413 | # Tests for specific trait types |
|
412 | 414 | #----------------------------------------------------------------------------- |
|
413 | 415 | |
|
414 | 416 | |
|
415 | 417 | class TestType(TestCase): |
|
416 | 418 | |
|
417 | 419 | def test_default(self): |
|
418 | 420 | |
|
419 | 421 | class B(object): pass |
|
420 | 422 | class A(HasTraits): |
|
421 | 423 | klass = Type |
|
422 | 424 | |
|
423 | 425 | a = A() |
|
424 | 426 | self.assertEquals(a.klass, None) |
|
425 | 427 | |
|
426 | 428 | a.klass = B |
|
427 | 429 | self.assertEquals(a.klass, B) |
|
428 | 430 | self.assertRaises(TraitError, setattr, a, 'klass', 10) |
|
429 | 431 | |
|
430 | 432 | def test_value(self): |
|
431 | 433 | |
|
432 | 434 | class B(object): pass |
|
433 | 435 | class C(object): pass |
|
434 | 436 | class A(HasTraits): |
|
435 | 437 | klass = Type(B) |
|
436 | 438 | |
|
437 | 439 | a = A() |
|
438 | 440 | self.assertEquals(a.klass, B) |
|
439 | 441 | self.assertRaises(TraitError, setattr, a, 'klass', C) |
|
440 | 442 | self.assertRaises(TraitError, setattr, a, 'klass', object) |
|
441 | 443 | a.klass = B |
|
442 | 444 | |
|
443 | 445 | def test_allow_none(self): |
|
444 | 446 | |
|
445 | 447 | class B(object): pass |
|
446 | 448 | class C(B): pass |
|
447 | 449 | class A(HasTraits): |
|
448 | 450 | klass = Type(B, allow_none=False) |
|
449 | 451 | |
|
450 | 452 | a = A() |
|
451 | 453 | self.assertEquals(a.klass, B) |
|
452 | 454 | self.assertRaises(TraitError, setattr, a, 'klass', None) |
|
453 | 455 | a.klass = C |
|
454 | 456 | self.assertEquals(a.klass, C) |
|
455 | 457 | |
|
456 | 458 | def test_validate_klass(self): |
|
457 | 459 | |
|
458 | 460 | class A(HasTraits): |
|
459 | 461 | klass = Type('no strings allowed') |
|
460 | 462 | |
|
461 | 463 | self.assertRaises(ImportError, A) |
|
462 | 464 | |
|
463 | 465 | class A(HasTraits): |
|
464 | 466 | klass = Type('rub.adub.Duck') |
|
465 | 467 | |
|
466 | 468 | self.assertRaises(ImportError, A) |
|
467 | 469 | |
|
468 | 470 | def test_validate_default(self): |
|
469 | 471 | |
|
470 | 472 | class B(object): pass |
|
471 | 473 | class A(HasTraits): |
|
472 | 474 | klass = Type('bad default', B) |
|
473 | 475 | |
|
474 | 476 | self.assertRaises(ImportError, A) |
|
475 | 477 | |
|
476 | 478 | class C(HasTraits): |
|
477 | 479 | klass = Type(None, B, allow_none=False) |
|
478 | 480 | |
|
479 | 481 | self.assertRaises(TraitError, C) |
|
480 | 482 | |
|
481 | 483 | def test_str_klass(self): |
|
482 | 484 | |
|
483 | 485 | class A(HasTraits): |
|
484 | 486 | klass = Type('IPython.utils.ipstruct.Struct') |
|
485 | 487 | |
|
486 | 488 | from IPython.utils.ipstruct import Struct |
|
487 | 489 | a = A() |
|
488 | 490 | a.klass = Struct |
|
489 | 491 | self.assertEquals(a.klass, Struct) |
|
490 | 492 | |
|
491 | 493 | self.assertRaises(TraitError, setattr, a, 'klass', 10) |
|
492 | 494 | |
|
493 | 495 | class TestInstance(TestCase): |
|
494 | 496 | |
|
495 | 497 | def test_basic(self): |
|
496 | 498 | class Foo(object): pass |
|
497 | 499 | class Bar(Foo): pass |
|
498 | 500 | class Bah(object): pass |
|
499 | 501 | |
|
500 | 502 | class A(HasTraits): |
|
501 | 503 | inst = Instance(Foo) |
|
502 | 504 | |
|
503 | 505 | a = A() |
|
504 | 506 | self.assert_(a.inst is None) |
|
505 | 507 | a.inst = Foo() |
|
506 | 508 | self.assert_(isinstance(a.inst, Foo)) |
|
507 | 509 | a.inst = Bar() |
|
508 | 510 | self.assert_(isinstance(a.inst, Foo)) |
|
509 | 511 | self.assertRaises(TraitError, setattr, a, 'inst', Foo) |
|
510 | 512 | self.assertRaises(TraitError, setattr, a, 'inst', Bar) |
|
511 | 513 | self.assertRaises(TraitError, setattr, a, 'inst', Bah()) |
|
512 | 514 | |
|
513 | 515 | def test_unique_default_value(self): |
|
514 | 516 | class Foo(object): pass |
|
515 | 517 | class A(HasTraits): |
|
516 | 518 | inst = Instance(Foo,(),{}) |
|
517 | 519 | |
|
518 | 520 | a = A() |
|
519 | 521 | b = A() |
|
520 | 522 | self.assert_(a.inst is not b.inst) |
|
521 | 523 | |
|
522 | 524 | def test_args_kw(self): |
|
523 | 525 | class Foo(object): |
|
524 | 526 | def __init__(self, c): self.c = c |
|
525 | 527 | class Bar(object): pass |
|
526 | 528 | class Bah(object): |
|
527 | 529 | def __init__(self, c, d): |
|
528 | 530 | self.c = c; self.d = d |
|
529 | 531 | |
|
530 | 532 | class A(HasTraits): |
|
531 | 533 | inst = Instance(Foo, (10,)) |
|
532 | 534 | a = A() |
|
533 | 535 | self.assertEquals(a.inst.c, 10) |
|
534 | 536 | |
|
535 | 537 | class B(HasTraits): |
|
536 | 538 | inst = Instance(Bah, args=(10,), kw=dict(d=20)) |
|
537 | 539 | b = B() |
|
538 | 540 | self.assertEquals(b.inst.c, 10) |
|
539 | 541 | self.assertEquals(b.inst.d, 20) |
|
540 | 542 | |
|
541 | 543 | class C(HasTraits): |
|
542 | 544 | inst = Instance(Foo) |
|
543 | 545 | c = C() |
|
544 | 546 | self.assert_(c.inst is None) |
|
545 | 547 | |
|
546 | 548 | def test_bad_default(self): |
|
547 | 549 | class Foo(object): pass |
|
548 | 550 | |
|
549 | 551 | class A(HasTraits): |
|
550 | 552 | inst = Instance(Foo, allow_none=False) |
|
551 | 553 | |
|
552 | 554 | self.assertRaises(TraitError, A) |
|
553 | 555 | |
|
554 | 556 | def test_instance(self): |
|
555 | 557 | class Foo(object): pass |
|
556 | 558 | |
|
557 | 559 | def inner(): |
|
558 | 560 | class A(HasTraits): |
|
559 | 561 | inst = Instance(Foo()) |
|
560 | 562 | |
|
561 | 563 | self.assertRaises(TraitError, inner) |
|
562 | 564 | |
|
563 | 565 | |
|
564 | 566 | class TestThis(TestCase): |
|
565 | 567 | |
|
566 | 568 | def test_this_class(self): |
|
567 | 569 | class Foo(HasTraits): |
|
568 | 570 | this = This |
|
569 | 571 | |
|
570 | 572 | f = Foo() |
|
571 | 573 | self.assertEquals(f.this, None) |
|
572 | 574 | g = Foo() |
|
573 | 575 | f.this = g |
|
574 | 576 | self.assertEquals(f.this, g) |
|
575 | 577 | self.assertRaises(TraitError, setattr, f, 'this', 10) |
|
576 | 578 | |
|
577 | 579 | def test_this_inst(self): |
|
578 | 580 | class Foo(HasTraits): |
|
579 | 581 | this = This() |
|
580 | 582 | |
|
581 | 583 | f = Foo() |
|
582 | 584 | f.this = Foo() |
|
583 | 585 | self.assert_(isinstance(f.this, Foo)) |
|
584 | 586 | |
|
585 | 587 | def test_subclass(self): |
|
586 | 588 | class Foo(HasTraits): |
|
587 | 589 | t = This() |
|
588 | 590 | class Bar(Foo): |
|
589 | 591 | pass |
|
590 | 592 | f = Foo() |
|
591 | 593 | b = Bar() |
|
592 | 594 | f.t = b |
|
593 | 595 | b.t = f |
|
594 | 596 | self.assertEquals(f.t, b) |
|
595 | 597 | self.assertEquals(b.t, f) |
|
596 | 598 | |
|
597 | 599 | def test_subclass_override(self): |
|
598 | 600 | class Foo(HasTraits): |
|
599 | 601 | t = This() |
|
600 | 602 | class Bar(Foo): |
|
601 | 603 | t = This() |
|
602 | 604 | f = Foo() |
|
603 | 605 | b = Bar() |
|
604 | 606 | f.t = b |
|
605 | 607 | self.assertEquals(f.t, b) |
|
606 | 608 | self.assertRaises(TraitError, setattr, b, 't', f) |
|
607 | 609 | |
|
608 | 610 | class TraitTestBase(TestCase): |
|
609 | 611 | """A best testing class for basic trait types.""" |
|
610 | 612 | |
|
611 | 613 | def assign(self, value): |
|
612 | 614 | self.obj.value = value |
|
613 | 615 | |
|
614 | 616 | def coerce(self, value): |
|
615 | 617 | return value |
|
616 | 618 | |
|
617 | 619 | def test_good_values(self): |
|
618 | 620 | if hasattr(self, '_good_values'): |
|
619 | 621 | for value in self._good_values: |
|
620 | 622 | self.assign(value) |
|
621 | 623 | self.assertEquals(self.obj.value, self.coerce(value)) |
|
622 | 624 | |
|
623 | 625 | def test_bad_values(self): |
|
624 | 626 | if hasattr(self, '_bad_values'): |
|
625 | 627 | for value in self._bad_values: |
|
626 | 628 | try: |
|
627 | 629 | self.assertRaises(TraitError, self.assign, value) |
|
628 | 630 | except AssertionError: |
|
629 | 631 | assert False, value |
|
630 | 632 | |
|
631 | 633 | def test_default_value(self): |
|
632 | 634 | if hasattr(self, '_default_value'): |
|
633 | 635 | self.assertEquals(self._default_value, self.obj.value) |
|
634 | 636 | |
|
635 | 637 | def tearDown(self): |
|
636 | 638 | # restore default value after tests, if set |
|
637 | 639 | if hasattr(self, '_default_value'): |
|
638 | 640 | self.obj.value = self._default_value |
|
639 | 641 | |
|
640 | 642 | |
|
641 | 643 | class AnyTrait(HasTraits): |
|
642 | 644 | |
|
643 | 645 | value = Any |
|
644 | 646 | |
|
645 | 647 | class AnyTraitTest(TraitTestBase): |
|
646 | 648 | |
|
647 | 649 | obj = AnyTrait() |
|
648 | 650 | |
|
649 | 651 | _default_value = None |
|
650 | 652 | _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j] |
|
651 | 653 | _bad_values = [] |
|
652 | 654 | |
|
653 | 655 | |
|
654 | 656 | class IntTrait(HasTraits): |
|
655 | 657 | |
|
656 | 658 | value = Int(99) |
|
657 | 659 | |
|
658 | 660 | class TestInt(TraitTestBase): |
|
659 | 661 | |
|
660 | 662 | obj = IntTrait() |
|
661 | 663 | _default_value = 99 |
|
662 | 664 | _good_values = [10, -10] |
|
663 | 665 | _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j, |
|
664 | 666 | 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L', |
|
665 | 667 | u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10'] |
|
666 | 668 | if not py3compat.PY3: |
|
667 | 669 | _bad_values.extend([10L, -10L, 10*sys.maxint, -10*sys.maxint]) |
|
668 | 670 | |
|
669 | 671 | |
|
670 | 672 | class LongTrait(HasTraits): |
|
671 | 673 | |
|
672 | 674 | value = Long(99L) |
|
673 | 675 | |
|
674 | 676 | class TestLong(TraitTestBase): |
|
675 | 677 | |
|
676 | 678 | obj = LongTrait() |
|
677 | 679 | |
|
678 | 680 | _default_value = 99L |
|
679 | 681 | _good_values = [10, -10, 10L, -10L] |
|
680 | 682 | _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,), |
|
681 | 683 | None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1', |
|
682 | 684 | '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1', |
|
683 | 685 | u'-10.1'] |
|
684 | 686 | if not py3compat.PY3: |
|
685 | 687 | # maxint undefined on py3, because int == long |
|
686 | 688 | _good_values.extend([10*sys.maxint, -10*sys.maxint]) |
|
687 | 689 | |
|
688 | 690 | @skipif(py3compat.PY3, "not relevant on py3") |
|
689 | 691 | def test_cast_small(self): |
|
690 | 692 | """Long casts ints to long""" |
|
691 | 693 | self.obj.value = 10 |
|
692 | 694 | self.assertEquals(type(self.obj.value), long) |
|
693 | 695 | |
|
694 | 696 | |
|
695 | 697 | class IntegerTrait(HasTraits): |
|
696 | 698 | value = Integer(1) |
|
697 | 699 | |
|
698 | 700 | class TestInteger(TestLong): |
|
699 | 701 | obj = IntegerTrait() |
|
700 | 702 | _default_value = 1 |
|
701 | 703 | |
|
702 | 704 | def coerce(self, n): |
|
703 | 705 | return int(n) |
|
704 | 706 | |
|
705 | 707 | @skipif(py3compat.PY3, "not relevant on py3") |
|
706 | 708 | def test_cast_small(self): |
|
707 | 709 | """Integer casts small longs to int""" |
|
708 | 710 | if py3compat.PY3: |
|
709 | 711 | raise SkipTest("not relevant on py3") |
|
710 | 712 | |
|
711 | 713 | self.obj.value = 100L |
|
712 | 714 | self.assertEquals(type(self.obj.value), int) |
|
713 | 715 | |
|
714 | 716 | |
|
715 | 717 | class FloatTrait(HasTraits): |
|
716 | 718 | |
|
717 | 719 | value = Float(99.0) |
|
718 | 720 | |
|
719 | 721 | class TestFloat(TraitTestBase): |
|
720 | 722 | |
|
721 | 723 | obj = FloatTrait() |
|
722 | 724 | |
|
723 | 725 | _default_value = 99.0 |
|
724 | 726 | _good_values = [10, -10, 10.1, -10.1] |
|
725 | 727 | _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, |
|
726 | 728 | 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10', |
|
727 | 729 | u'-10', u'10L', u'-10L', u'10.1', u'-10.1'] |
|
728 | 730 | if not py3compat.PY3: |
|
729 | 731 | _bad_values.extend([10L, -10L]) |
|
730 | 732 | |
|
731 | 733 | |
|
732 | 734 | class ComplexTrait(HasTraits): |
|
733 | 735 | |
|
734 | 736 | value = Complex(99.0-99.0j) |
|
735 | 737 | |
|
736 | 738 | class TestComplex(TraitTestBase): |
|
737 | 739 | |
|
738 | 740 | obj = ComplexTrait() |
|
739 | 741 | |
|
740 | 742 | _default_value = 99.0-99.0j |
|
741 | 743 | _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j, |
|
742 | 744 | 10.1j, 10.1+10.1j, 10.1-10.1j] |
|
743 | 745 | _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None] |
|
744 | 746 | if not py3compat.PY3: |
|
745 | 747 | _bad_values.extend([10L, -10L]) |
|
746 | 748 | |
|
747 | 749 | |
|
748 | 750 | class BytesTrait(HasTraits): |
|
749 | 751 | |
|
750 | 752 | value = Bytes(b'string') |
|
751 | 753 | |
|
752 | 754 | class TestBytes(TraitTestBase): |
|
753 | 755 | |
|
754 | 756 | obj = BytesTrait() |
|
755 | 757 | |
|
756 | 758 | _default_value = b'string' |
|
757 | 759 | _good_values = [b'10', b'-10', b'10L', |
|
758 | 760 | b'-10L', b'10.1', b'-10.1', b'string'] |
|
759 | 761 | _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10], |
|
760 | 762 | ['ten'],{'ten': 10},(10,), None, u'string'] |
|
761 | 763 | |
|
762 | 764 | |
|
763 | 765 | class UnicodeTrait(HasTraits): |
|
764 | 766 | |
|
765 | 767 | value = Unicode(u'unicode') |
|
766 | 768 | |
|
767 | 769 | class TestUnicode(TraitTestBase): |
|
768 | 770 | |
|
769 | 771 | obj = UnicodeTrait() |
|
770 | 772 | |
|
771 | 773 | _default_value = u'unicode' |
|
772 | 774 | _good_values = ['10', '-10', '10L', '-10L', '10.1', |
|
773 | 775 | '-10.1', '', u'', 'string', u'string', u"€"] |
|
774 | 776 | _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, |
|
775 | 777 | [10], ['ten'], [u'ten'], {'ten': 10},(10,), None] |
|
776 | 778 | |
|
777 | 779 | |
|
778 | 780 | class ObjectNameTrait(HasTraits): |
|
779 | 781 | value = ObjectName("abc") |
|
780 | 782 | |
|
781 | 783 | class TestObjectName(TraitTestBase): |
|
782 | 784 | obj = ObjectNameTrait() |
|
783 | 785 | |
|
784 | 786 | _default_value = "abc" |
|
785 | 787 | _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"] |
|
786 | 788 | _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]", |
|
787 | 789 | object(), object] |
|
788 | 790 | if sys.version_info[0] < 3: |
|
789 | 791 | _bad_values.append(u"þ") |
|
790 | 792 | else: |
|
791 | 793 | _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131). |
|
792 | 794 | |
|
793 | 795 | |
|
794 | 796 | class DottedObjectNameTrait(HasTraits): |
|
795 | 797 | value = DottedObjectName("a.b") |
|
796 | 798 | |
|
797 | 799 | class TestDottedObjectName(TraitTestBase): |
|
798 | 800 | obj = DottedObjectNameTrait() |
|
799 | 801 | |
|
800 | 802 | _default_value = "a.b" |
|
801 | 803 | _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"] |
|
802 | 804 | _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc."] |
|
803 | 805 | if sys.version_info[0] < 3: |
|
804 | 806 | _bad_values.append(u"t.þ") |
|
805 | 807 | else: |
|
806 | 808 | _good_values.append(u"t.þ") |
|
807 | 809 | |
|
808 | 810 | |
|
809 | 811 | class TCPAddressTrait(HasTraits): |
|
810 | 812 | |
|
811 | 813 | value = TCPAddress() |
|
812 | 814 | |
|
813 | 815 | class TestTCPAddress(TraitTestBase): |
|
814 | 816 | |
|
815 | 817 | obj = TCPAddressTrait() |
|
816 | 818 | |
|
817 | 819 | _default_value = ('127.0.0.1',0) |
|
818 | 820 | _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)] |
|
819 | 821 | _bad_values = [(0,0),('localhost',10.0),('localhost',-1)] |
|
820 | 822 | |
|
821 | 823 | class ListTrait(HasTraits): |
|
822 | 824 | |
|
823 | 825 | value = List(Int) |
|
824 | 826 | |
|
825 | 827 | class TestList(TraitTestBase): |
|
826 | 828 | |
|
827 | 829 | obj = ListTrait() |
|
828 | 830 | |
|
829 | 831 | _default_value = [] |
|
830 | 832 | _good_values = [[], [1], range(10)] |
|
831 | 833 | _bad_values = [10, [1,'a'], 'a', (1,2)] |
|
832 | 834 | |
|
833 | 835 | class LenListTrait(HasTraits): |
|
834 | 836 | |
|
835 | 837 | value = List(Int, [0], minlen=1, maxlen=2) |
|
836 | 838 | |
|
837 | 839 | class TestLenList(TraitTestBase): |
|
838 | 840 | |
|
839 | 841 | obj = LenListTrait() |
|
840 | 842 | |
|
841 | 843 | _default_value = [0] |
|
842 | 844 | _good_values = [[1], range(2)] |
|
843 | 845 | _bad_values = [10, [1,'a'], 'a', (1,2), [], range(3)] |
|
844 | 846 | |
|
845 | 847 | class TupleTrait(HasTraits): |
|
846 | 848 | |
|
847 | 849 | value = Tuple(Int) |
|
848 | 850 | |
|
849 | 851 | class TestTupleTrait(TraitTestBase): |
|
850 | 852 | |
|
851 | 853 | obj = TupleTrait() |
|
852 | 854 | |
|
853 | 855 | _default_value = None |
|
854 | 856 | _good_values = [(1,), None,(0,)] |
|
855 | 857 | _bad_values = [10, (1,2), [1],('a'), ()] |
|
856 | 858 | |
|
857 | 859 | def test_invalid_args(self): |
|
858 | 860 | self.assertRaises(TypeError, Tuple, 5) |
|
859 | 861 | self.assertRaises(TypeError, Tuple, default_value='hello') |
|
860 | 862 | t = Tuple(Int, CBytes, default_value=(1,5)) |
|
861 | 863 | |
|
862 | 864 | class LooseTupleTrait(HasTraits): |
|
863 | 865 | |
|
864 | 866 | value = Tuple((1,2,3)) |
|
865 | 867 | |
|
866 | 868 | class TestLooseTupleTrait(TraitTestBase): |
|
867 | 869 | |
|
868 | 870 | obj = LooseTupleTrait() |
|
869 | 871 | |
|
870 | 872 | _default_value = (1,2,3) |
|
871 | 873 | _good_values = [(1,), None, (0,), tuple(range(5)), tuple('hello'), ('a',5), ()] |
|
872 | 874 | _bad_values = [10, 'hello', [1], []] |
|
873 | 875 | |
|
874 | 876 | def test_invalid_args(self): |
|
875 | 877 | self.assertRaises(TypeError, Tuple, 5) |
|
876 | 878 | self.assertRaises(TypeError, Tuple, default_value='hello') |
|
877 | 879 | t = Tuple(Int, CBytes, default_value=(1,5)) |
|
878 | 880 | |
|
879 | 881 | |
|
880 | 882 | class MultiTupleTrait(HasTraits): |
|
881 | 883 | |
|
882 | 884 | value = Tuple(Int, Bytes, default_value=[99,b'bottles']) |
|
883 | 885 | |
|
884 | 886 | class TestMultiTuple(TraitTestBase): |
|
885 | 887 | |
|
886 | 888 | obj = MultiTupleTrait() |
|
887 | 889 | |
|
888 | 890 | _default_value = (99,b'bottles') |
|
889 | 891 | _good_values = [(1,b'a'), (2,b'b')] |
|
890 | 892 | _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a')) |
@@ -1,91 +1,91 b'' | |||
|
1 | 1 | """Tab-completion over zmq""" |
|
2 | 2 | |
|
3 | 3 | # Trying to get print statements to work during completion, not very |
|
4 | 4 | # successfully... |
|
5 | 5 | from __future__ import print_function |
|
6 | 6 | |
|
7 | 7 | import itertools |
|
8 | 8 | try: |
|
9 | 9 | import readline |
|
10 | 10 | except ImportError: |
|
11 | 11 | readline = None |
|
12 | 12 | import rlcompleter |
|
13 | 13 | import time |
|
14 | 14 | |
|
15 | 15 | import session |
|
16 | 16 | |
|
17 | 17 | class KernelCompleter(object): |
|
18 | 18 | """Kernel-side completion machinery.""" |
|
19 | 19 | def __init__(self, namespace): |
|
20 | 20 | self.namespace = namespace |
|
21 | 21 | self.completer = rlcompleter.Completer(namespace) |
|
22 | 22 | |
|
23 | 23 | def complete(self, line, text): |
|
24 | 24 | # We'll likely use linel later even if now it's not used for anything |
|
25 | 25 | matches = [] |
|
26 | 26 | complete = self.completer.complete |
|
27 | 27 | for state in itertools.count(): |
|
28 | 28 | comp = complete(text, state) |
|
29 | 29 | if comp is None: |
|
30 | 30 | break |
|
31 | 31 | matches.append(comp) |
|
32 | 32 | return matches |
|
33 | 33 | |
|
34 | 34 | |
|
35 | 35 | class ClientCompleter(object): |
|
36 | 36 | """Client-side completion machinery. |
|
37 | 37 | |
|
38 | 38 | How it works: self.complete will be called multiple times, with |
|
39 | 39 | state=0,1,2,... When state=0 it should compute ALL the completion matches, |
|
40 | 40 | and then return them for each value of state.""" |
|
41 | 41 | |
|
42 | 42 | def __init__(self, client, session, socket): |
|
43 | 43 | # ugly, but we get called asynchronously and need access to some |
|
44 | 44 | # client state, like backgrounded code |
|
45 | 45 | assert readline is not None, "ClientCompleter depends on readline" |
|
46 | 46 | self.client = client |
|
47 | 47 | self.session = session |
|
48 | 48 | self.socket = socket |
|
49 | 49 | self.matches = [] |
|
50 | 50 | |
|
51 | 51 | def request_completion(self, text): |
|
52 | 52 | # Get full line to give to the kernel in case it wants more info. |
|
53 | 53 | line = readline.get_line_buffer() |
|
54 | 54 | # send completion request to kernel |
|
55 | 55 | msg = self.session.send(self.socket, |
|
56 | 56 | 'complete_request', |
|
57 | 57 | dict(text=text, line=line)) |
|
58 | 58 | |
|
59 | 59 | # Give the kernel up to 0.5s to respond |
|
60 | 60 | for i in range(5): |
|
61 | 61 | ident,rep = self.session.recv(self.socket) |
|
62 | rep = Message(rep) | |
|
62 | rep = session.Message(rep) | |
|
63 | 63 | if rep is not None and rep.msg_type == 'complete_reply': |
|
64 | 64 | matches = rep.content.matches |
|
65 | 65 | break |
|
66 | 66 | time.sleep(0.1) |
|
67 | 67 | else: |
|
68 | 68 | # timeout |
|
69 | 69 | print ('TIMEOUT') # Can't see this message... |
|
70 | 70 | matches = None |
|
71 | 71 | return matches |
|
72 | 72 | |
|
73 | 73 | def complete(self, text, state): |
|
74 | 74 | |
|
75 | 75 | if self.client.backgrounded > 0: |
|
76 | 76 | print("\n[Not completing, background tasks active]") |
|
77 | 77 | print(readline.get_line_buffer(), end='') |
|
78 | 78 | return None |
|
79 | 79 | |
|
80 | 80 | if state==0: |
|
81 | 81 | matches = self.request_completion(text) |
|
82 | 82 | if matches is None: |
|
83 | 83 | self.matches = [] |
|
84 | 84 | print('WARNING: Kernel timeout on tab completion.') |
|
85 | 85 | else: |
|
86 | 86 | self.matches = matches |
|
87 | 87 | |
|
88 | 88 | try: |
|
89 | 89 | return self.matches[state] |
|
90 | 90 | except IndexError: |
|
91 | 91 | return None |
@@ -1,196 +1,197 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | """A simple interactive frontend that talks to a kernel over 0MQ. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Imports |
|
7 | 7 | #----------------------------------------------------------------------------- |
|
8 | 8 | # stdlib |
|
9 | 9 | import cPickle as pickle |
|
10 | 10 | import code |
|
11 | 11 | import readline |
|
12 | 12 | import sys |
|
13 | 13 | import time |
|
14 | 14 | import uuid |
|
15 | 15 | |
|
16 | 16 | # our own |
|
17 | 17 | import zmq |
|
18 | 18 | import session |
|
19 | 19 | import completer |
|
20 | 20 | from IPython.utils.localinterfaces import LOCALHOST |
|
21 | from IPython.zmq.session import Message | |
|
21 | 22 | |
|
22 | 23 | #----------------------------------------------------------------------------- |
|
23 | 24 | # Classes and functions |
|
24 | 25 | #----------------------------------------------------------------------------- |
|
25 | 26 | |
|
26 | 27 | class Console(code.InteractiveConsole): |
|
27 | 28 | |
|
28 | 29 | def __init__(self, locals=None, filename="<console>", |
|
29 | 30 | session = session, |
|
30 | 31 | request_socket=None, |
|
31 | 32 | sub_socket=None): |
|
32 | 33 | code.InteractiveConsole.__init__(self, locals, filename) |
|
33 | 34 | self.session = session |
|
34 | 35 | self.request_socket = request_socket |
|
35 | 36 | self.sub_socket = sub_socket |
|
36 | 37 | self.backgrounded = 0 |
|
37 | 38 | self.messages = {} |
|
38 | 39 | |
|
39 | 40 | # Set tab completion |
|
40 | 41 | self.completer = completer.ClientCompleter(self, session, request_socket) |
|
41 | 42 | readline.parse_and_bind('tab: complete') |
|
42 | 43 | readline.parse_and_bind('set show-all-if-ambiguous on') |
|
43 | 44 | readline.set_completer(self.completer.complete) |
|
44 | 45 | |
|
45 | 46 | # Set system prompts |
|
46 | 47 | sys.ps1 = 'Py>>> ' |
|
47 | 48 | sys.ps2 = ' ... ' |
|
48 | 49 | sys.ps3 = 'Out : ' |
|
49 | 50 | # Build dict of handlers for message types |
|
50 | 51 | self.handlers = {} |
|
51 | 52 | for msg_type in ['pyin', 'pyout', 'pyerr', 'stream']: |
|
52 | 53 | self.handlers[msg_type] = getattr(self, 'handle_%s' % msg_type) |
|
53 | 54 | |
|
54 | 55 | def handle_pyin(self, omsg): |
|
55 | 56 | if omsg.parent_header.session == self.session.session: |
|
56 | 57 | return |
|
57 | 58 | c = omsg.content.code.rstrip() |
|
58 | 59 | if c: |
|
59 | 60 | print '[IN from %s]' % omsg.parent_header.username |
|
60 | 61 | print c |
|
61 | 62 | |
|
62 | 63 | def handle_pyout(self, omsg): |
|
63 | 64 | #print omsg # dbg |
|
64 | 65 | if omsg.parent_header.session == self.session.session: |
|
65 | 66 | print "%s%s" % (sys.ps3, omsg.content.data) |
|
66 | 67 | else: |
|
67 | 68 | print '[Out from %s]' % omsg.parent_header.username |
|
68 | 69 | print omsg.content.data |
|
69 | 70 | |
|
70 | 71 | def print_pyerr(self, err): |
|
71 | 72 | print >> sys.stderr, err.etype,':', err.evalue |
|
72 | 73 | print >> sys.stderr, ''.join(err.traceback) |
|
73 | 74 | |
|
74 | 75 | def handle_pyerr(self, omsg): |
|
75 | 76 | if omsg.parent_header.session == self.session.session: |
|
76 | 77 | return |
|
77 | 78 | print >> sys.stderr, '[ERR from %s]' % omsg.parent_header.username |
|
78 | 79 | self.print_pyerr(omsg.content) |
|
79 | 80 | |
|
80 | 81 | def handle_stream(self, omsg): |
|
81 | 82 | if omsg.content.name == 'stdout': |
|
82 | 83 | outstream = sys.stdout |
|
83 | 84 | else: |
|
84 | 85 | outstream = sys.stderr |
|
85 | 86 | print >> outstream, '*ERR*', |
|
86 | 87 | print >> outstream, omsg.content.data, |
|
87 | 88 | |
|
88 | 89 | def handle_output(self, omsg): |
|
89 | 90 | handler = self.handlers.get(omsg.msg_type, None) |
|
90 | 91 | if handler is not None: |
|
91 | 92 | handler(omsg) |
|
92 | 93 | |
|
93 | 94 | def recv_output(self): |
|
94 | 95 | while True: |
|
95 | 96 | ident,msg = self.session.recv(self.sub_socket) |
|
96 | 97 | if msg is None: |
|
97 | 98 | break |
|
98 | 99 | self.handle_output(Message(msg)) |
|
99 | 100 | |
|
100 | 101 | def handle_reply(self, rep): |
|
101 | 102 | # Handle any side effects on output channels |
|
102 | 103 | self.recv_output() |
|
103 | 104 | # Now, dispatch on the possible reply types we must handle |
|
104 | 105 | if rep is None: |
|
105 | 106 | return |
|
106 | 107 | if rep.content.status == 'error': |
|
107 | 108 | self.print_pyerr(rep.content) |
|
108 | 109 | elif rep.content.status == 'aborted': |
|
109 | 110 | print >> sys.stderr, "ERROR: ABORTED" |
|
110 | 111 | ab = self.messages[rep.parent_header.msg_id].content |
|
111 | 112 | if 'code' in ab: |
|
112 | 113 | print >> sys.stderr, ab.code |
|
113 | 114 | else: |
|
114 | 115 | print >> sys.stderr, ab |
|
115 | 116 | |
|
116 | 117 | def recv_reply(self): |
|
117 | 118 | ident,rep = self.session.recv(self.request_socket) |
|
118 | 119 | mrep = Message(rep) |
|
119 | 120 | self.handle_reply(mrep) |
|
120 | 121 | return mrep |
|
121 | 122 | |
|
122 | 123 | def runcode(self, code): |
|
123 | 124 | # We can't pickle code objects, so fetch the actual source |
|
124 | 125 | src = '\n'.join(self.buffer) |
|
125 | 126 | |
|
126 | 127 | # for non-background inputs, if we do have previoiusly backgrounded |
|
127 | 128 | # jobs, check to see if they've produced results |
|
128 | 129 | if not src.endswith(';'): |
|
129 | 130 | while self.backgrounded > 0: |
|
130 | 131 | #print 'checking background' |
|
131 | 132 | rep = self.recv_reply() |
|
132 | 133 | if rep: |
|
133 | 134 | self.backgrounded -= 1 |
|
134 | 135 | time.sleep(0.05) |
|
135 | 136 | |
|
136 | 137 | # Send code execution message to kernel |
|
137 | 138 | omsg = self.session.send(self.request_socket, |
|
138 | 139 | 'execute_request', dict(code=src)) |
|
139 | 140 | self.messages[omsg.header.msg_id] = omsg |
|
140 | 141 | |
|
141 | 142 | # Fake asynchronicity by letting the user put ';' at the end of the line |
|
142 | 143 | if src.endswith(';'): |
|
143 | 144 | self.backgrounded += 1 |
|
144 | 145 | return |
|
145 | 146 | |
|
146 | 147 | # For foreground jobs, wait for reply |
|
147 | 148 | while True: |
|
148 | 149 | rep = self.recv_reply() |
|
149 | 150 | if rep is not None: |
|
150 | 151 | break |
|
151 | 152 | self.recv_output() |
|
152 | 153 | time.sleep(0.05) |
|
153 | 154 | else: |
|
154 | 155 | # We exited without hearing back from the kernel! |
|
155 | 156 | print >> sys.stderr, 'ERROR!!! kernel never got back to us!!!' |
|
156 | 157 | |
|
157 | 158 | |
|
158 | 159 | class InteractiveClient(object): |
|
159 | 160 | def __init__(self, session, request_socket, sub_socket): |
|
160 | 161 | self.session = session |
|
161 | 162 | self.request_socket = request_socket |
|
162 | 163 | self.sub_socket = sub_socket |
|
163 | 164 | self.console = Console(None, '<zmq-console>', |
|
164 | 165 | session, request_socket, sub_socket) |
|
165 | 166 | |
|
166 | 167 | def interact(self): |
|
167 | 168 | self.console.interact() |
|
168 | 169 | |
|
169 | 170 | |
|
170 | 171 | def main(): |
|
171 | 172 | # Defaults |
|
172 | 173 | #ip = '192.168.2.109' |
|
173 | 174 | ip = LOCALHOST |
|
174 | 175 | #ip = '99.146.222.252' |
|
175 | 176 | port_base = 5575 |
|
176 | 177 | connection = ('tcp://%s' % ip) + ':%i' |
|
177 | 178 | req_conn = connection % port_base |
|
178 | 179 | sub_conn = connection % (port_base+1) |
|
179 | 180 | |
|
180 | 181 | # Create initial sockets |
|
181 | 182 | c = zmq.Context() |
|
182 | 183 | request_socket = c.socket(zmq.DEALER) |
|
183 | 184 | request_socket.connect(req_conn) |
|
184 | 185 | |
|
185 | 186 | sub_socket = c.socket(zmq.SUB) |
|
186 | 187 | sub_socket.connect(sub_conn) |
|
187 | 188 | sub_socket.setsockopt(zmq.SUBSCRIBE, '') |
|
188 | 189 | |
|
189 | 190 | # Make session and user-facing client |
|
190 | 191 | sess = session.Session() |
|
191 | 192 | client = InteractiveClient(sess, request_socket, sub_socket) |
|
192 | 193 | client.interact() |
|
193 | 194 | |
|
194 | 195 | |
|
195 | 196 | if __name__ == '__main__': |
|
196 | 197 | main() |
|
1 | NO CONTENT: file was removed |
General Comments 0
You need to be logged in to leave comments.
Login now