##// END OF EJS Templates
saner default encoding mechanism
Brandon Parsons -
Show More
@@ -1,703 +1,703 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 from IPython.utils.encoding import getdefaultencoding
29 from IPython.utils.encoding import DEFAULT_ENCODING
30 30
31 31 #-----------------------------------------------------------------------------
32 32 # Exceptions
33 33 #-----------------------------------------------------------------------------
34 34
35 35
36 36 class ConfigError(Exception):
37 37 pass
38 38
39 39 class ConfigLoaderError(ConfigError):
40 40 pass
41 41
42 42 class ConfigFileNotFound(ConfigError):
43 43 pass
44 44
45 45 class ArgumentError(ConfigLoaderError):
46 46 pass
47 47
48 48 #-----------------------------------------------------------------------------
49 49 # Argparse fix
50 50 #-----------------------------------------------------------------------------
51 51
52 52 # Unfortunately argparse by default prints help messages to stderr instead of
53 53 # stdout. This makes it annoying to capture long help screens at the command
54 54 # line, since one must know how to pipe stderr, which many users don't know how
55 55 # to do. So we override the print_help method with one that defaults to
56 56 # stdout and use our class instead.
57 57
58 58 class ArgumentParser(argparse.ArgumentParser):
59 59 """Simple argparse subclass that prints help to stdout by default."""
60 60
61 61 def print_help(self, file=None):
62 62 if file is None:
63 63 file = sys.stdout
64 64 return super(ArgumentParser, self).print_help(file)
65 65
66 66 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
67 67
68 68 #-----------------------------------------------------------------------------
69 69 # Config class for holding config information
70 70 #-----------------------------------------------------------------------------
71 71
72 72
73 73 class Config(dict):
74 74 """An attribute based dict that can do smart merges."""
75 75
76 76 def __init__(self, *args, **kwds):
77 77 dict.__init__(self, *args, **kwds)
78 78 # This sets self.__dict__ = self, but it has to be done this way
79 79 # because we are also overriding __setattr__.
80 80 dict.__setattr__(self, '__dict__', self)
81 81
82 82 def _merge(self, other):
83 83 to_update = {}
84 84 for k, v in other.iteritems():
85 85 if not self.has_key(k):
86 86 to_update[k] = v
87 87 else: # I have this key
88 88 if isinstance(v, Config):
89 89 # Recursively merge common sub Configs
90 90 self[k]._merge(v)
91 91 else:
92 92 # Plain updates for non-Configs
93 93 to_update[k] = v
94 94
95 95 self.update(to_update)
96 96
97 97 def _is_section_key(self, key):
98 98 if key[0].upper()==key[0] and not key.startswith('_'):
99 99 return True
100 100 else:
101 101 return False
102 102
103 103 def __contains__(self, key):
104 104 if self._is_section_key(key):
105 105 return True
106 106 else:
107 107 return super(Config, self).__contains__(key)
108 108 # .has_key is deprecated for dictionaries.
109 109 has_key = __contains__
110 110
111 111 def _has_section(self, key):
112 112 if self._is_section_key(key):
113 113 if super(Config, self).__contains__(key):
114 114 return True
115 115 return False
116 116
117 117 def copy(self):
118 118 return type(self)(dict.copy(self))
119 119
120 120 def __copy__(self):
121 121 return self.copy()
122 122
123 123 def __deepcopy__(self, memo):
124 124 import copy
125 125 return type(self)(copy.deepcopy(self.items()))
126 126
127 127 def __getitem__(self, key):
128 128 # We cannot use directly self._is_section_key, because it triggers
129 129 # infinite recursion on top of PyPy. Instead, we manually fish the
130 130 # bound method.
131 131 is_section_key = self.__class__._is_section_key.__get__(self)
132 132
133 133 # Because we use this for an exec namespace, we need to delegate
134 134 # the lookup of names in __builtin__ to itself. This means
135 135 # that you can't have section or attribute names that are
136 136 # builtins.
137 137 try:
138 138 return getattr(builtin_mod, key)
139 139 except AttributeError:
140 140 pass
141 141 if is_section_key(key):
142 142 try:
143 143 return dict.__getitem__(self, key)
144 144 except KeyError:
145 145 c = Config()
146 146 dict.__setitem__(self, key, c)
147 147 return c
148 148 else:
149 149 return dict.__getitem__(self, key)
150 150
151 151 def __setitem__(self, key, value):
152 152 # Don't allow names in __builtin__ to be modified.
153 153 if hasattr(builtin_mod, key):
154 154 raise ConfigError('Config variable names cannot have the same name '
155 155 'as a Python builtin: %s' % key)
156 156 if self._is_section_key(key):
157 157 if not isinstance(value, Config):
158 158 raise ValueError('values whose keys begin with an uppercase '
159 159 'char must be Config instances: %r, %r' % (key, value))
160 160 else:
161 161 dict.__setitem__(self, key, value)
162 162
163 163 def __getattr__(self, key):
164 164 try:
165 165 return self.__getitem__(key)
166 166 except KeyError, e:
167 167 raise AttributeError(e)
168 168
169 169 def __setattr__(self, key, value):
170 170 try:
171 171 self.__setitem__(key, value)
172 172 except KeyError, e:
173 173 raise AttributeError(e)
174 174
175 175 def __delattr__(self, key):
176 176 try:
177 177 dict.__delitem__(self, key)
178 178 except KeyError, e:
179 179 raise AttributeError(e)
180 180
181 181
182 182 #-----------------------------------------------------------------------------
183 183 # Config loading classes
184 184 #-----------------------------------------------------------------------------
185 185
186 186
187 187 class ConfigLoader(object):
188 188 """A object for loading configurations from just about anywhere.
189 189
190 190 The resulting configuration is packaged as a :class:`Struct`.
191 191
192 192 Notes
193 193 -----
194 194 A :class:`ConfigLoader` does one thing: load a config from a source
195 195 (file, command line arguments) and returns the data as a :class:`Struct`.
196 196 There are lots of things that :class:`ConfigLoader` does not do. It does
197 197 not implement complex logic for finding config files. It does not handle
198 198 default values or merge multiple configs. These things need to be
199 199 handled elsewhere.
200 200 """
201 201
202 202 def __init__(self):
203 203 """A base class for config loaders.
204 204
205 205 Examples
206 206 --------
207 207
208 208 >>> cl = ConfigLoader()
209 209 >>> config = cl.load_config()
210 210 >>> config
211 211 {}
212 212 """
213 213 self.clear()
214 214
215 215 def clear(self):
216 216 self.config = Config()
217 217
218 218 def load_config(self):
219 219 """Load a config from somewhere, return a :class:`Config` instance.
220 220
221 221 Usually, this will cause self.config to be set and then returned.
222 222 However, in most cases, :meth:`ConfigLoader.clear` should be called
223 223 to erase any previous state.
224 224 """
225 225 self.clear()
226 226 return self.config
227 227
228 228
229 229 class FileConfigLoader(ConfigLoader):
230 230 """A base class for file based configurations.
231 231
232 232 As we add more file based config loaders, the common logic should go
233 233 here.
234 234 """
235 235 pass
236 236
237 237
238 238 class PyFileConfigLoader(FileConfigLoader):
239 239 """A config loader for pure python files.
240 240
241 241 This calls execfile on a plain python file and looks for attributes
242 242 that are all caps. These attribute are added to the config Struct.
243 243 """
244 244
245 245 def __init__(self, filename, path=None):
246 246 """Build a config loader for a filename and path.
247 247
248 248 Parameters
249 249 ----------
250 250 filename : str
251 251 The file name of the config file.
252 252 path : str, list, tuple
253 253 The path to search for the config file on, or a sequence of
254 254 paths to try in order.
255 255 """
256 256 super(PyFileConfigLoader, self).__init__()
257 257 self.filename = filename
258 258 self.path = path
259 259 self.full_filename = ''
260 260 self.data = None
261 261
262 262 def load_config(self):
263 263 """Load the config from a file and return it as a Struct."""
264 264 self.clear()
265 265 try:
266 266 self._find_file()
267 267 except IOError as e:
268 268 raise ConfigFileNotFound(str(e))
269 269 self._read_file_as_dict()
270 270 self._convert_to_config()
271 271 return self.config
272 272
273 273 def _find_file(self):
274 274 """Try to find the file by searching the paths."""
275 275 self.full_filename = filefind(self.filename, self.path)
276 276
277 277 def _read_file_as_dict(self):
278 278 """Load the config file into self.config, with recursive loading."""
279 279 # This closure is made available in the namespace that is used
280 280 # to exec the config file. It allows users to call
281 281 # load_subconfig('myconfig.py') to load config files recursively.
282 282 # It needs to be a closure because it has references to self.path
283 283 # and self.config. The sub-config is loaded with the same path
284 284 # as the parent, but it uses an empty config which is then merged
285 285 # with the parents.
286 286
287 287 # If a profile is specified, the config file will be loaded
288 288 # from that profile
289 289
290 290 def load_subconfig(fname, profile=None):
291 291 # import here to prevent circular imports
292 292 from IPython.core.profiledir import ProfileDir, ProfileDirError
293 293 if profile is not None:
294 294 try:
295 295 profile_dir = ProfileDir.find_profile_dir_by_name(
296 296 get_ipython_dir(),
297 297 profile,
298 298 )
299 299 except ProfileDirError:
300 300 return
301 301 path = profile_dir.location
302 302 else:
303 303 path = self.path
304 304 loader = PyFileConfigLoader(fname, path)
305 305 try:
306 306 sub_config = loader.load_config()
307 307 except ConfigFileNotFound:
308 308 # Pass silently if the sub config is not there. This happens
309 309 # when a user s using a profile, but not the default config.
310 310 pass
311 311 else:
312 312 self.config._merge(sub_config)
313 313
314 314 # Again, this needs to be a closure and should be used in config
315 315 # files to get the config being loaded.
316 316 def get_config():
317 317 return self.config
318 318
319 319 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
320 320 fs_encoding = sys.getfilesystemencoding() or 'ascii'
321 321 conf_filename = self.full_filename.encode(fs_encoding)
322 322 py3compat.execfile(conf_filename, namespace)
323 323
324 324 def _convert_to_config(self):
325 325 if self.data is None:
326 326 ConfigLoaderError('self.data does not exist')
327 327
328 328
329 329 class CommandLineConfigLoader(ConfigLoader):
330 330 """A config loader for command line arguments.
331 331
332 332 As we add more command line based loaders, the common logic should go
333 333 here.
334 334 """
335 335
336 336 def _exec_config_str(self, lhs, rhs):
337 337 """execute self.config.<lhs>=<rhs>
338 338
339 339 * expands ~ with expanduser
340 340 * tries to assign with raw exec, otherwise assigns with just the string,
341 341 allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
342 342 equivalent are `--C.a=4` and `--C.a='4'`.
343 343 """
344 344 rhs = os.path.expanduser(rhs)
345 345 exec_str = 'self.config.' + lhs + '=' + rhs
346 346 try:
347 347 # Try to see if regular Python syntax will work. This
348 348 # won't handle strings as the quote marks are removed
349 349 # by the system shell.
350 350 exec exec_str in locals(), globals()
351 351 except (NameError, SyntaxError):
352 352 # This case happens if the rhs is a string but without
353 353 # the quote marks. Use repr, to get quote marks, and
354 354 # 'u' prefix and see if
355 355 # it succeeds. If it still fails, we let it raise.
356 356 exec_str = u'self.config.' + lhs + '= rhs'
357 357 exec exec_str in locals(), globals()
358 358
359 359 def _load_flag(self, cfg):
360 360 """update self.config from a flag, which can be a dict or Config"""
361 361 if isinstance(cfg, (dict, Config)):
362 362 # don't clobber whole config sections, update
363 363 # each section from config:
364 364 for sec,c in cfg.iteritems():
365 365 self.config[sec].update(c)
366 366 else:
367 367 raise TypeError("Invalid flag: %r" % cfg)
368 368
369 369 # raw --identifier=value pattern
370 370 # but *also* accept '-' as wordsep, for aliases
371 371 # accepts: --foo=a
372 372 # --Class.trait=value
373 373 # --alias-name=value
374 374 # rejects: -foo=value
375 375 # --foo
376 376 # --Class.trait
377 377 kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*')
378 378
379 379 # just flags, no assignments, with two *or one* leading '-'
380 380 # accepts: --foo
381 381 # -foo-bar-again
382 382 # rejects: --anything=anything
383 383 # --two.word
384 384
385 385 flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
386 386
387 387 class KeyValueConfigLoader(CommandLineConfigLoader):
388 388 """A config loader that loads key value pairs from the command line.
389 389
390 390 This allows command line options to be gives in the following form::
391 391
392 392 ipython --profile="foo" --InteractiveShell.autocall=False
393 393 """
394 394
395 395 def __init__(self, argv=None, aliases=None, flags=None):
396 396 """Create a key value pair config loader.
397 397
398 398 Parameters
399 399 ----------
400 400 argv : list
401 401 A list that has the form of sys.argv[1:] which has unicode
402 402 elements of the form u"key=value". If this is None (default),
403 403 then sys.argv[1:] will be used.
404 404 aliases : dict
405 405 A dict of aliases for configurable traits.
406 406 Keys are the short aliases, Values are the resolved trait.
407 407 Of the form: `{'alias' : 'Configurable.trait'}`
408 408 flags : dict
409 409 A dict of flags, keyed by str name. Vaues can be Config objects,
410 410 dicts, or "key=value" strings. If Config or dict, when the flag
411 411 is triggered, The flag is loaded as `self.config.update(m)`.
412 412
413 413 Returns
414 414 -------
415 415 config : Config
416 416 The resulting Config object.
417 417
418 418 Examples
419 419 --------
420 420
421 421 >>> from IPython.config.loader import KeyValueConfigLoader
422 422 >>> cl = KeyValueConfigLoader()
423 423 >>> cl.load_config(["--A.name='brian'","--B.number=0"])
424 424 {'A': {'name': 'brian'}, 'B': {'number': 0}}
425 425 """
426 426 self.clear()
427 427 if argv is None:
428 428 argv = sys.argv[1:]
429 429 self.argv = argv
430 430 self.aliases = aliases or {}
431 431 self.flags = flags or {}
432 432
433 433
434 434 def clear(self):
435 435 super(KeyValueConfigLoader, self).clear()
436 436 self.extra_args = []
437 437
438 438
439 439 def _decode_argv(self, argv, enc=None):
440 440 """decode argv if bytes, using stin.encoding, falling back on default enc"""
441 441 uargv = []
442 442 if enc is None:
443 enc = getdefaultencoding()
443 enc = DEFAULT_ENCODING
444 444 for arg in argv:
445 445 if not isinstance(arg, unicode):
446 446 # only decode if not already decoded
447 447 arg = arg.decode(enc)
448 448 uargv.append(arg)
449 449 return uargv
450 450
451 451
452 452 def load_config(self, argv=None, aliases=None, flags=None):
453 453 """Parse the configuration and generate the Config object.
454 454
455 455 After loading, any arguments that are not key-value or
456 456 flags will be stored in self.extra_args - a list of
457 457 unparsed command-line arguments. This is used for
458 458 arguments such as input files or subcommands.
459 459
460 460 Parameters
461 461 ----------
462 462 argv : list, optional
463 463 A list that has the form of sys.argv[1:] which has unicode
464 464 elements of the form u"key=value". If this is None (default),
465 465 then self.argv will be used.
466 466 aliases : dict
467 467 A dict of aliases for configurable traits.
468 468 Keys are the short aliases, Values are the resolved trait.
469 469 Of the form: `{'alias' : 'Configurable.trait'}`
470 470 flags : dict
471 471 A dict of flags, keyed by str name. Values can be Config objects
472 472 or dicts. When the flag is triggered, The config is loaded as
473 473 `self.config.update(cfg)`.
474 474 """
475 475 from IPython.config.configurable import Configurable
476 476
477 477 self.clear()
478 478 if argv is None:
479 479 argv = self.argv
480 480 if aliases is None:
481 481 aliases = self.aliases
482 482 if flags is None:
483 483 flags = self.flags
484 484
485 485 # ensure argv is a list of unicode strings:
486 486 uargv = self._decode_argv(argv)
487 487 for idx,raw in enumerate(uargv):
488 488 # strip leading '-'
489 489 item = raw.lstrip('-')
490 490
491 491 if raw == '--':
492 492 # don't parse arguments after '--'
493 493 # this is useful for relaying arguments to scripts, e.g.
494 494 # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py
495 495 self.extra_args.extend(uargv[idx+1:])
496 496 break
497 497
498 498 if kv_pattern.match(raw):
499 499 lhs,rhs = item.split('=',1)
500 500 # Substitute longnames for aliases.
501 501 if lhs in aliases:
502 502 lhs = aliases[lhs]
503 503 if '.' not in lhs:
504 504 # probably a mistyped alias, but not technically illegal
505 505 warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs)
506 506 try:
507 507 self._exec_config_str(lhs, rhs)
508 508 except Exception:
509 509 raise ArgumentError("Invalid argument: '%s'" % raw)
510 510
511 511 elif flag_pattern.match(raw):
512 512 if item in flags:
513 513 cfg,help = flags[item]
514 514 self._load_flag(cfg)
515 515 else:
516 516 raise ArgumentError("Unrecognized flag: '%s'"%raw)
517 517 elif raw.startswith('-'):
518 518 kv = '--'+item
519 519 if kv_pattern.match(kv):
520 520 raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
521 521 else:
522 522 raise ArgumentError("Invalid argument: '%s'"%raw)
523 523 else:
524 524 # keep all args that aren't valid in a list,
525 525 # in case our parent knows what to do with them.
526 526 self.extra_args.append(item)
527 527 return self.config
528 528
529 529 class ArgParseConfigLoader(CommandLineConfigLoader):
530 530 """A loader that uses the argparse module to load from the command line."""
531 531
532 532 def __init__(self, argv=None, aliases=None, flags=None, *parser_args, **parser_kw):
533 533 """Create a config loader for use with argparse.
534 534
535 535 Parameters
536 536 ----------
537 537
538 538 argv : optional, list
539 539 If given, used to read command-line arguments from, otherwise
540 540 sys.argv[1:] is used.
541 541
542 542 parser_args : tuple
543 543 A tuple of positional arguments that will be passed to the
544 544 constructor of :class:`argparse.ArgumentParser`.
545 545
546 546 parser_kw : dict
547 547 A tuple of keyword arguments that will be passed to the
548 548 constructor of :class:`argparse.ArgumentParser`.
549 549
550 550 Returns
551 551 -------
552 552 config : Config
553 553 The resulting Config object.
554 554 """
555 555 super(CommandLineConfigLoader, self).__init__()
556 556 self.clear()
557 557 if argv is None:
558 558 argv = sys.argv[1:]
559 559 self.argv = argv
560 560 self.aliases = aliases or {}
561 561 self.flags = flags or {}
562 562
563 563 self.parser_args = parser_args
564 564 self.version = parser_kw.pop("version", None)
565 565 kwargs = dict(argument_default=argparse.SUPPRESS)
566 566 kwargs.update(parser_kw)
567 567 self.parser_kw = kwargs
568 568
569 569 def load_config(self, argv=None, aliases=None, flags=None):
570 570 """Parse command line arguments and return as a Config object.
571 571
572 572 Parameters
573 573 ----------
574 574
575 575 args : optional, list
576 576 If given, a list with the structure of sys.argv[1:] to parse
577 577 arguments from. If not given, the instance's self.argv attribute
578 578 (given at construction time) is used."""
579 579 self.clear()
580 580 if argv is None:
581 581 argv = self.argv
582 582 if aliases is None:
583 583 aliases = self.aliases
584 584 if flags is None:
585 585 flags = self.flags
586 586 self._create_parser(aliases, flags)
587 587 self._parse_args(argv)
588 588 self._convert_to_config()
589 589 return self.config
590 590
591 591 def get_extra_args(self):
592 592 if hasattr(self, 'extra_args'):
593 593 return self.extra_args
594 594 else:
595 595 return []
596 596
597 597 def _create_parser(self, aliases=None, flags=None):
598 598 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
599 599 self._add_arguments(aliases, flags)
600 600
601 601 def _add_arguments(self, aliases=None, flags=None):
602 602 raise NotImplementedError("subclasses must implement _add_arguments")
603 603
604 604 def _parse_args(self, args):
605 605 """self.parser->self.parsed_data"""
606 606 # decode sys.argv to support unicode command-line options
607 enc = getdefaultencoding()
607 enc = DEFAULT_ENCODING
608 608 uargs = [py3compat.cast_unicode(a, enc) for a in args]
609 609 self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
610 610
611 611 def _convert_to_config(self):
612 612 """self.parsed_data->self.config"""
613 613 for k, v in vars(self.parsed_data).iteritems():
614 614 exec "self.config.%s = v"%k in locals(), globals()
615 615
616 616 class KVArgParseConfigLoader(ArgParseConfigLoader):
617 617 """A config loader that loads aliases and flags with argparse,
618 618 but will use KVLoader for the rest. This allows better parsing
619 619 of common args, such as `ipython -c 'print 5'`, but still gets
620 620 arbitrary config with `ipython --InteractiveShell.use_readline=False`"""
621 621
622 622 def _convert_to_config(self):
623 623 """self.parsed_data->self.config"""
624 624 for k, v in vars(self.parsed_data).iteritems():
625 625 self._exec_config_str(k, v)
626 626
627 627 def _add_arguments(self, aliases=None, flags=None):
628 628 self.alias_flags = {}
629 629 # print aliases, flags
630 630 if aliases is None:
631 631 aliases = self.aliases
632 632 if flags is None:
633 633 flags = self.flags
634 634 paa = self.parser.add_argument
635 635 for key,value in aliases.iteritems():
636 636 if key in flags:
637 637 # flags
638 638 nargs = '?'
639 639 else:
640 640 nargs = None
641 641 if len(key) is 1:
642 642 paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs)
643 643 else:
644 644 paa('--'+key, type=unicode, dest=value, nargs=nargs)
645 645 for key, (value, help) in flags.iteritems():
646 646 if key in self.aliases:
647 647 #
648 648 self.alias_flags[self.aliases[key]] = value
649 649 continue
650 650 if len(key) is 1:
651 651 paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value)
652 652 else:
653 653 paa('--'+key, action='append_const', dest='_flags', const=value)
654 654
655 655 def _convert_to_config(self):
656 656 """self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
657 657 # remove subconfigs list from namespace before transforming the Namespace
658 658 if '_flags' in self.parsed_data:
659 659 subcs = self.parsed_data._flags
660 660 del self.parsed_data._flags
661 661 else:
662 662 subcs = []
663 663
664 664 for k, v in vars(self.parsed_data).iteritems():
665 665 if v is None:
666 666 # it was a flag that shares the name of an alias
667 667 subcs.append(self.alias_flags[k])
668 668 else:
669 669 # eval the KV assignment
670 670 self._exec_config_str(k, v)
671 671
672 672 for subc in subcs:
673 673 self._load_flag(subc)
674 674
675 675 if self.extra_args:
676 676 sub_parser = KeyValueConfigLoader()
677 677 sub_parser.load_config(self.extra_args)
678 678 self.config._merge(sub_parser.config)
679 679 self.extra_args = sub_parser.extra_args
680 680
681 681
682 682 def load_pyconfig_files(config_files, path):
683 683 """Load multiple Python config files, merging each of them in turn.
684 684
685 685 Parameters
686 686 ==========
687 687 config_files : list of str
688 688 List of config files names to load and merge into the config.
689 689 path : unicode
690 690 The full path to the location of the config files.
691 691 """
692 692 config = Config()
693 693 for cf in config_files:
694 694 loader = PyFileConfigLoader(cf, path=path)
695 695 try:
696 696 next_config = loader.load_config()
697 697 except ConfigFileNotFound:
698 698 pass
699 699 except:
700 700 raise
701 701 else:
702 702 config._merge(next_config)
703 703 return config
@@ -1,60 +1,60 b''
1 1 """Support for interactive macros in IPython"""
2 2
3 3 #*****************************************************************************
4 4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
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 import re
11 11 import sys
12 12
13 13 from IPython.utils import py3compat
14 from IPython.utils.encoding import getdefaultencoding
14 from IPython.utils.encoding import DEFAULT_ENCODING
15 15
16 16 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
17 17
18 18 class Macro(object):
19 19 """Simple class to store the value of macros as strings.
20 20
21 21 Macro is just a callable that executes a string of IPython
22 22 input when called.
23 23
24 24 Args to macro are available in _margv list if you need them.
25 25 """
26 26
27 27 def __init__(self,code):
28 28 """store the macro value, as a single string which can be executed"""
29 29 lines = []
30 30 enc = None
31 31 for line in code.splitlines():
32 32 coding_match = coding_declaration.match(line)
33 33 if coding_match:
34 34 enc = coding_match.group(1)
35 35 else:
36 36 lines.append(line)
37 37 code = "\n".join(lines)
38 38 if isinstance(code, bytes):
39 code = code.decode(enc or getdefaultencoding())
39 code = code.decode(enc or DEFAULT_ENCODING)
40 40 self.value = code + '\n'
41 41
42 42 def __str__(self):
43 43 return py3compat.unicode_to_str(self.value)
44 44
45 45 def __unicode__(self):
46 46 return self.value
47 47
48 48 def __repr__(self):
49 49 return 'IPython.macro.Macro(%s)' % repr(self.value)
50 50
51 51 def __getstate__(self):
52 52 """ needed for safe pickling via %store """
53 53 return {'value': self.value}
54 54
55 55 def __add__(self, other):
56 56 if isinstance(other, Macro):
57 57 return Macro(self.value + other.value)
58 58 elif isinstance(other, basestring):
59 59 return Macro(self.value + other)
60 60 raise TypeError
@@ -1,3799 +1,3799 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 io
24 24 import os
25 25 import sys
26 26 import shutil
27 27 import re
28 28 import time
29 29 import gc
30 30 from StringIO import StringIO
31 31 from getopt import getopt,GetoptError
32 32 from pprint import pformat
33 33 from xmlrpclib import ServerProxy
34 34
35 35 # cProfile was added in Python2.5
36 36 try:
37 37 import cProfile as profile
38 38 import pstats
39 39 except ImportError:
40 40 # profile isn't bundled by default in Debian for license reasons
41 41 try:
42 42 import profile,pstats
43 43 except ImportError:
44 44 profile = pstats = None
45 45
46 46 import IPython
47 47 from IPython.core import debugger, oinspect
48 48 from IPython.core.error import TryNext
49 49 from IPython.core.error import UsageError
50 50 from IPython.core.error import StdinNotImplementedError
51 51 from IPython.core.fakemodule import FakeModule
52 52 from IPython.core.profiledir import ProfileDir
53 53 from IPython.core.macro import Macro
54 54 from IPython.core import magic_arguments, page
55 55 from IPython.core.prefilter import ESC_MAGIC
56 56 from IPython.core.pylabtools import mpl_runner
57 57 from IPython.testing.skipdoctest import skip_doctest
58 58 from IPython.utils import py3compat
59 59 from IPython.utils import openpy
60 from IPython.utils.encoding import getdefaultencoding
60 from IPython.utils.encoding import DEFAULT_ENCODING
61 61 from IPython.utils.io import file_read, nlprint
62 62 from IPython.utils.module_paths import find_mod
63 63 from IPython.utils.path import get_py_filename, unquote_filename
64 64 from IPython.utils.process import arg_split, abbrev_cwd
65 65 from IPython.utils.terminal import set_term_title
66 66 from IPython.utils.text import LSString, SList, format_screen
67 67 from IPython.utils.timing import clock, clock2
68 68 from IPython.utils.warn import warn, error
69 69 from IPython.utils.ipstruct import Struct
70 70 from IPython.config.application import Application
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Utility functions
74 74 #-----------------------------------------------------------------------------
75 75
76 76 def on_off(tag):
77 77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
78 78 return ['OFF','ON'][tag]
79 79
80 80 class Bunch: pass
81 81
82 82 def compress_dhist(dh):
83 83 head, tail = dh[:-10], dh[-10:]
84 84
85 85 newhead = []
86 86 done = set()
87 87 for h in head:
88 88 if h in done:
89 89 continue
90 90 newhead.append(h)
91 91 done.add(h)
92 92
93 93 return newhead + tail
94 94
95 95 def needs_local_scope(func):
96 96 """Decorator to mark magic functions which need to local scope to run."""
97 97 func.needs_local_scope = True
98 98 return func
99 99
100 100
101 101 # Used for exception handling in magic_edit
102 102 class MacroToEdit(ValueError): pass
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(open(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 print
833 833 print
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 940
941 941 if vbytes < 100000:
942 942 print aformat % (vshape,vsize,vdtype,vbytes)
943 943 else:
944 944 print aformat % (vshape,vsize,vdtype,vbytes),
945 945 if vbytes < Mb:
946 946 print '(%s kb)' % (vbytes/kb,)
947 947 else:
948 948 print '(%s Mb)' % (vbytes/Mb,)
949 949 else:
950 950 try:
951 951 vstr = str(var)
952 952 except UnicodeEncodeError:
953 vstr = unicode(var).encode(getdefaultencoding(),
953 vstr = unicode(var).encode(DEFAULT_ENCODING,
954 954 'backslashreplace')
955 955 vstr = vstr.replace('\n','\\n')
956 956 if len(vstr) < 50:
957 957 print vstr
958 958 else:
959 959 print vstr[:25] + "<...>" + vstr[-25:]
960 960
961 961 def magic_reset(self, parameter_s=''):
962 962 """Resets the namespace by removing all names defined by the user, if
963 963 called without arguments, or by removing some types of objects, such
964 964 as everything currently in IPython's In[] and Out[] containers (see
965 965 the parameters for details).
966 966
967 967 Parameters
968 968 ----------
969 969 -f : force reset without asking for confirmation.
970 970
971 971 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
972 972 References to objects may be kept. By default (without this option),
973 973 we do a 'hard' reset, giving you a new session and removing all
974 974 references to objects from the current session.
975 975
976 976 in : reset input history
977 977
978 978 out : reset output history
979 979
980 980 dhist : reset directory history
981 981
982 982 array : reset only variables that are NumPy arrays
983 983
984 984 See Also
985 985 --------
986 986 magic_reset_selective : invoked as ``%reset_selective``
987 987
988 988 Examples
989 989 --------
990 990 ::
991 991
992 992 In [6]: a = 1
993 993
994 994 In [7]: a
995 995 Out[7]: 1
996 996
997 997 In [8]: 'a' in _ip.user_ns
998 998 Out[8]: True
999 999
1000 1000 In [9]: %reset -f
1001 1001
1002 1002 In [1]: 'a' in _ip.user_ns
1003 1003 Out[1]: False
1004 1004
1005 1005 In [2]: %reset -f in
1006 1006 Flushing input history
1007 1007
1008 1008 In [3]: %reset -f dhist in
1009 1009 Flushing directory history
1010 1010 Flushing input history
1011 1011
1012 1012 Notes
1013 1013 -----
1014 1014 Calling this magic from clients that do not implement standard input,
1015 1015 such as the ipython notebook interface, will reset the namespace
1016 1016 without confirmation.
1017 1017 """
1018 1018 opts, args = self.parse_options(parameter_s,'sf', mode='list')
1019 1019 if 'f' in opts:
1020 1020 ans = True
1021 1021 else:
1022 1022 try:
1023 1023 ans = self.shell.ask_yes_no(
1024 1024 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1025 1025 except StdinNotImplementedError:
1026 1026 ans = True
1027 1027 if not ans:
1028 1028 print 'Nothing done.'
1029 1029 return
1030 1030
1031 1031 if 's' in opts: # Soft reset
1032 1032 user_ns = self.shell.user_ns
1033 1033 for i in self.magic_who_ls():
1034 1034 del(user_ns[i])
1035 1035 elif len(args) == 0: # Hard reset
1036 1036 self.shell.reset(new_session = False)
1037 1037
1038 1038 # reset in/out/dhist/array: previously extensinions/clearcmd.py
1039 1039 ip = self.shell
1040 1040 user_ns = self.user_ns # local lookup, heavily used
1041 1041
1042 1042 for target in args:
1043 1043 target = target.lower() # make matches case insensitive
1044 1044 if target == 'out':
1045 1045 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1046 1046 self.displayhook.flush()
1047 1047
1048 1048 elif target == 'in':
1049 1049 print "Flushing input history"
1050 1050 pc = self.displayhook.prompt_count + 1
1051 1051 for n in range(1, pc):
1052 1052 key = '_i'+repr(n)
1053 1053 user_ns.pop(key,None)
1054 1054 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1055 1055 hm = ip.history_manager
1056 1056 # don't delete these, as %save and %macro depending on the length
1057 1057 # of these lists to be preserved
1058 1058 hm.input_hist_parsed[:] = [''] * pc
1059 1059 hm.input_hist_raw[:] = [''] * pc
1060 1060 # hm has internal machinery for _i,_ii,_iii, clear it out
1061 1061 hm._i = hm._ii = hm._iii = hm._i00 = u''
1062 1062
1063 1063 elif target == 'array':
1064 1064 # Support cleaning up numpy arrays
1065 1065 try:
1066 1066 from numpy import ndarray
1067 1067 # This must be done with items and not iteritems because we're
1068 1068 # going to modify the dict in-place.
1069 1069 for x,val in user_ns.items():
1070 1070 if isinstance(val,ndarray):
1071 1071 del user_ns[x]
1072 1072 except ImportError:
1073 1073 print "reset array only works if Numpy is available."
1074 1074
1075 1075 elif target == 'dhist':
1076 1076 print "Flushing directory history"
1077 1077 del user_ns['_dh'][:]
1078 1078
1079 1079 else:
1080 1080 print "Don't know how to reset ",
1081 1081 print target + ", please run `%reset?` for details"
1082 1082
1083 1083 gc.collect()
1084 1084
1085 1085 def magic_reset_selective(self, parameter_s=''):
1086 1086 """Resets the namespace by removing names defined by the user.
1087 1087
1088 1088 Input/Output history are left around in case you need them.
1089 1089
1090 1090 %reset_selective [-f] regex
1091 1091
1092 1092 No action is taken if regex is not included
1093 1093
1094 1094 Options
1095 1095 -f : force reset without asking for confirmation.
1096 1096
1097 1097 See Also
1098 1098 --------
1099 1099 magic_reset : invoked as ``%reset``
1100 1100
1101 1101 Examples
1102 1102 --------
1103 1103
1104 1104 We first fully reset the namespace so your output looks identical to
1105 1105 this example for pedagogical reasons; in practice you do not need a
1106 1106 full reset::
1107 1107
1108 1108 In [1]: %reset -f
1109 1109
1110 1110 Now, with a clean namespace we can make a few variables and use
1111 1111 ``%reset_selective`` to only delete names that match our regexp::
1112 1112
1113 1113 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1114 1114
1115 1115 In [3]: who_ls
1116 1116 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1117 1117
1118 1118 In [4]: %reset_selective -f b[2-3]m
1119 1119
1120 1120 In [5]: who_ls
1121 1121 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1122 1122
1123 1123 In [6]: %reset_selective -f d
1124 1124
1125 1125 In [7]: who_ls
1126 1126 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1127 1127
1128 1128 In [8]: %reset_selective -f c
1129 1129
1130 1130 In [9]: who_ls
1131 1131 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1132 1132
1133 1133 In [10]: %reset_selective -f b
1134 1134
1135 1135 In [11]: who_ls
1136 1136 Out[11]: ['a']
1137 1137
1138 1138 Notes
1139 1139 -----
1140 1140 Calling this magic from clients that do not implement standard input,
1141 1141 such as the ipython notebook interface, will reset the namespace
1142 1142 without confirmation.
1143 1143 """
1144 1144
1145 1145 opts, regex = self.parse_options(parameter_s,'f')
1146 1146
1147 1147 if opts.has_key('f'):
1148 1148 ans = True
1149 1149 else:
1150 1150 try:
1151 1151 ans = self.shell.ask_yes_no(
1152 1152 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1153 1153 default='n')
1154 1154 except StdinNotImplementedError:
1155 1155 ans = True
1156 1156 if not ans:
1157 1157 print 'Nothing done.'
1158 1158 return
1159 1159 user_ns = self.shell.user_ns
1160 1160 if not regex:
1161 1161 print 'No regex pattern specified. Nothing done.'
1162 1162 return
1163 1163 else:
1164 1164 try:
1165 1165 m = re.compile(regex)
1166 1166 except TypeError:
1167 1167 raise TypeError('regex must be a string or compiled pattern')
1168 1168 for i in self.magic_who_ls():
1169 1169 if m.search(i):
1170 1170 del(user_ns[i])
1171 1171
1172 1172 def magic_xdel(self, parameter_s=''):
1173 1173 """Delete a variable, trying to clear it from anywhere that
1174 1174 IPython's machinery has references to it. By default, this uses
1175 1175 the identity of the named object in the user namespace to remove
1176 1176 references held under other names. The object is also removed
1177 1177 from the output history.
1178 1178
1179 1179 Options
1180 1180 -n : Delete the specified name from all namespaces, without
1181 1181 checking their identity.
1182 1182 """
1183 1183 opts, varname = self.parse_options(parameter_s,'n')
1184 1184 try:
1185 1185 self.shell.del_var(varname, ('n' in opts))
1186 1186 except (NameError, ValueError) as e:
1187 1187 print type(e).__name__ +": "+ str(e)
1188 1188
1189 1189 def magic_logstart(self,parameter_s=''):
1190 1190 """Start logging anywhere in a session.
1191 1191
1192 1192 %logstart [-o|-r|-t] [log_name [log_mode]]
1193 1193
1194 1194 If no name is given, it defaults to a file named 'ipython_log.py' in your
1195 1195 current directory, in 'rotate' mode (see below).
1196 1196
1197 1197 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1198 1198 history up to that point and then continues logging.
1199 1199
1200 1200 %logstart takes a second optional parameter: logging mode. This can be one
1201 1201 of (note that the modes are given unquoted):\\
1202 1202 append: well, that says it.\\
1203 1203 backup: rename (if exists) to name~ and start name.\\
1204 1204 global: single logfile in your home dir, appended to.\\
1205 1205 over : overwrite existing log.\\
1206 1206 rotate: create rotating logs name.1~, name.2~, etc.
1207 1207
1208 1208 Options:
1209 1209
1210 1210 -o: log also IPython's output. In this mode, all commands which
1211 1211 generate an Out[NN] prompt are recorded to the logfile, right after
1212 1212 their corresponding input line. The output lines are always
1213 1213 prepended with a '#[Out]# ' marker, so that the log remains valid
1214 1214 Python code.
1215 1215
1216 1216 Since this marker is always the same, filtering only the output from
1217 1217 a log is very easy, using for example a simple awk call::
1218 1218
1219 1219 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1220 1220
1221 1221 -r: log 'raw' input. Normally, IPython's logs contain the processed
1222 1222 input, so that user lines are logged in their final form, converted
1223 1223 into valid Python. For example, %Exit is logged as
1224 1224 _ip.magic("Exit"). If the -r flag is given, all input is logged
1225 1225 exactly as typed, with no transformations applied.
1226 1226
1227 1227 -t: put timestamps before each input line logged (these are put in
1228 1228 comments)."""
1229 1229
1230 1230 opts,par = self.parse_options(parameter_s,'ort')
1231 1231 log_output = 'o' in opts
1232 1232 log_raw_input = 'r' in opts
1233 1233 timestamp = 't' in opts
1234 1234
1235 1235 logger = self.shell.logger
1236 1236
1237 1237 # if no args are given, the defaults set in the logger constructor by
1238 1238 # ipython remain valid
1239 1239 if par:
1240 1240 try:
1241 1241 logfname,logmode = par.split()
1242 1242 except:
1243 1243 logfname = par
1244 1244 logmode = 'backup'
1245 1245 else:
1246 1246 logfname = logger.logfname
1247 1247 logmode = logger.logmode
1248 1248 # put logfname into rc struct as if it had been called on the command
1249 1249 # line, so it ends up saved in the log header Save it in case we need
1250 1250 # to restore it...
1251 1251 old_logfile = self.shell.logfile
1252 1252 if logfname:
1253 1253 logfname = os.path.expanduser(logfname)
1254 1254 self.shell.logfile = logfname
1255 1255
1256 1256 loghead = '# IPython log file\n\n'
1257 1257 try:
1258 1258 started = logger.logstart(logfname,loghead,logmode,
1259 1259 log_output,timestamp,log_raw_input)
1260 1260 except:
1261 1261 self.shell.logfile = old_logfile
1262 1262 warn("Couldn't start log: %s" % sys.exc_info()[1])
1263 1263 else:
1264 1264 # log input history up to this point, optionally interleaving
1265 1265 # output if requested
1266 1266
1267 1267 if timestamp:
1268 1268 # disable timestamping for the previous history, since we've
1269 1269 # lost those already (no time machine here).
1270 1270 logger.timestamp = False
1271 1271
1272 1272 if log_raw_input:
1273 1273 input_hist = self.shell.history_manager.input_hist_raw
1274 1274 else:
1275 1275 input_hist = self.shell.history_manager.input_hist_parsed
1276 1276
1277 1277 if log_output:
1278 1278 log_write = logger.log_write
1279 1279 output_hist = self.shell.history_manager.output_hist
1280 1280 for n in range(1,len(input_hist)-1):
1281 1281 log_write(input_hist[n].rstrip() + '\n')
1282 1282 if n in output_hist:
1283 1283 log_write(repr(output_hist[n]),'output')
1284 1284 else:
1285 1285 logger.log_write('\n'.join(input_hist[1:]))
1286 1286 logger.log_write('\n')
1287 1287 if timestamp:
1288 1288 # re-enable timestamping
1289 1289 logger.timestamp = True
1290 1290
1291 1291 print ('Activating auto-logging. '
1292 1292 'Current session state plus future input saved.')
1293 1293 logger.logstate()
1294 1294
1295 1295 def magic_logstop(self,parameter_s=''):
1296 1296 """Fully stop logging and close log file.
1297 1297
1298 1298 In order to start logging again, a new %logstart call needs to be made,
1299 1299 possibly (though not necessarily) with a new filename, mode and other
1300 1300 options."""
1301 1301 self.logger.logstop()
1302 1302
1303 1303 def magic_logoff(self,parameter_s=''):
1304 1304 """Temporarily stop logging.
1305 1305
1306 1306 You must have previously started logging."""
1307 1307 self.shell.logger.switch_log(0)
1308 1308
1309 1309 def magic_logon(self,parameter_s=''):
1310 1310 """Restart logging.
1311 1311
1312 1312 This function is for restarting logging which you've temporarily
1313 1313 stopped with %logoff. For starting logging for the first time, you
1314 1314 must use the %logstart function, which allows you to specify an
1315 1315 optional log filename."""
1316 1316
1317 1317 self.shell.logger.switch_log(1)
1318 1318
1319 1319 def magic_logstate(self,parameter_s=''):
1320 1320 """Print the status of the logging system."""
1321 1321
1322 1322 self.shell.logger.logstate()
1323 1323
1324 1324 def magic_pdb(self, parameter_s=''):
1325 1325 """Control the automatic calling of the pdb interactive debugger.
1326 1326
1327 1327 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1328 1328 argument it works as a toggle.
1329 1329
1330 1330 When an exception is triggered, IPython can optionally call the
1331 1331 interactive pdb debugger after the traceback printout. %pdb toggles
1332 1332 this feature on and off.
1333 1333
1334 1334 The initial state of this feature is set in your configuration
1335 1335 file (the option is ``InteractiveShell.pdb``).
1336 1336
1337 1337 If you want to just activate the debugger AFTER an exception has fired,
1338 1338 without having to type '%pdb on' and rerunning your code, you can use
1339 1339 the %debug magic."""
1340 1340
1341 1341 par = parameter_s.strip().lower()
1342 1342
1343 1343 if par:
1344 1344 try:
1345 1345 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1346 1346 except KeyError:
1347 1347 print ('Incorrect argument. Use on/1, off/0, '
1348 1348 'or nothing for a toggle.')
1349 1349 return
1350 1350 else:
1351 1351 # toggle
1352 1352 new_pdb = not self.shell.call_pdb
1353 1353
1354 1354 # set on the shell
1355 1355 self.shell.call_pdb = new_pdb
1356 1356 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1357 1357
1358 1358 def magic_debug(self, parameter_s=''):
1359 1359 """Activate the interactive debugger in post-mortem mode.
1360 1360
1361 1361 If an exception has just occurred, this lets you inspect its stack
1362 1362 frames interactively. Note that this will always work only on the last
1363 1363 traceback that occurred, so you must call this quickly after an
1364 1364 exception that you wish to inspect has fired, because if another one
1365 1365 occurs, it clobbers the previous one.
1366 1366
1367 1367 If you want IPython to automatically do this on every exception, see
1368 1368 the %pdb magic for more details.
1369 1369 """
1370 1370 self.shell.debugger(force=True)
1371 1371
1372 1372 @skip_doctest
1373 1373 def magic_prun(self, parameter_s ='',user_mode=1,
1374 1374 opts=None,arg_lst=None,prog_ns=None):
1375 1375
1376 1376 """Run a statement through the python code profiler.
1377 1377
1378 1378 Usage:
1379 1379 %prun [options] statement
1380 1380
1381 1381 The given statement (which doesn't require quote marks) is run via the
1382 1382 python profiler in a manner similar to the profile.run() function.
1383 1383 Namespaces are internally managed to work correctly; profile.run
1384 1384 cannot be used in IPython because it makes certain assumptions about
1385 1385 namespaces which do not hold under IPython.
1386 1386
1387 1387 Options:
1388 1388
1389 1389 -l <limit>: you can place restrictions on what or how much of the
1390 1390 profile gets printed. The limit value can be:
1391 1391
1392 1392 * A string: only information for function names containing this string
1393 1393 is printed.
1394 1394
1395 1395 * An integer: only these many lines are printed.
1396 1396
1397 1397 * A float (between 0 and 1): this fraction of the report is printed
1398 1398 (for example, use a limit of 0.4 to see the topmost 40% only).
1399 1399
1400 1400 You can combine several limits with repeated use of the option. For
1401 1401 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1402 1402 information about class constructors.
1403 1403
1404 1404 -r: return the pstats.Stats object generated by the profiling. This
1405 1405 object has all the information about the profile in it, and you can
1406 1406 later use it for further analysis or in other functions.
1407 1407
1408 1408 -s <key>: sort profile by given key. You can provide more than one key
1409 1409 by using the option several times: '-s key1 -s key2 -s key3...'. The
1410 1410 default sorting key is 'time'.
1411 1411
1412 1412 The following is copied verbatim from the profile documentation
1413 1413 referenced below:
1414 1414
1415 1415 When more than one key is provided, additional keys are used as
1416 1416 secondary criteria when the there is equality in all keys selected
1417 1417 before them.
1418 1418
1419 1419 Abbreviations can be used for any key names, as long as the
1420 1420 abbreviation is unambiguous. The following are the keys currently
1421 1421 defined:
1422 1422
1423 1423 Valid Arg Meaning
1424 1424 "calls" call count
1425 1425 "cumulative" cumulative time
1426 1426 "file" file name
1427 1427 "module" file name
1428 1428 "pcalls" primitive call count
1429 1429 "line" line number
1430 1430 "name" function name
1431 1431 "nfl" name/file/line
1432 1432 "stdname" standard name
1433 1433 "time" internal time
1434 1434
1435 1435 Note that all sorts on statistics are in descending order (placing
1436 1436 most time consuming items first), where as name, file, and line number
1437 1437 searches are in ascending order (i.e., alphabetical). The subtle
1438 1438 distinction between "nfl" and "stdname" is that the standard name is a
1439 1439 sort of the name as printed, which means that the embedded line
1440 1440 numbers get compared in an odd way. For example, lines 3, 20, and 40
1441 1441 would (if the file names were the same) appear in the string order
1442 1442 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1443 1443 line numbers. In fact, sort_stats("nfl") is the same as
1444 1444 sort_stats("name", "file", "line").
1445 1445
1446 1446 -T <filename>: save profile results as shown on screen to a text
1447 1447 file. The profile is still shown on screen.
1448 1448
1449 1449 -D <filename>: save (via dump_stats) profile statistics to given
1450 1450 filename. This data is in a format understood by the pstats module, and
1451 1451 is generated by a call to the dump_stats() method of profile
1452 1452 objects. The profile is still shown on screen.
1453 1453
1454 1454 -q: suppress output to the pager. Best used with -T and/or -D above.
1455 1455
1456 1456 If you want to run complete programs under the profiler's control, use
1457 1457 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1458 1458 contains profiler specific options as described here.
1459 1459
1460 1460 You can read the complete documentation for the profile module with::
1461 1461
1462 1462 In [1]: import profile; profile.help()
1463 1463 """
1464 1464
1465 1465 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1466 1466
1467 1467 if user_mode: # regular user call
1468 1468 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1469 1469 list_all=1, posix=False)
1470 1470 namespace = self.shell.user_ns
1471 1471 else: # called to run a program by %run -p
1472 1472 try:
1473 1473 filename = get_py_filename(arg_lst[0])
1474 1474 except IOError as e:
1475 1475 try:
1476 1476 msg = str(e)
1477 1477 except UnicodeError:
1478 1478 msg = e.message
1479 1479 error(msg)
1480 1480 return
1481 1481
1482 1482 arg_str = 'execfile(filename,prog_ns)'
1483 1483 namespace = {
1484 1484 'execfile': self.shell.safe_execfile,
1485 1485 'prog_ns': prog_ns,
1486 1486 'filename': filename
1487 1487 }
1488 1488
1489 1489 opts.merge(opts_def)
1490 1490
1491 1491 prof = profile.Profile()
1492 1492 try:
1493 1493 prof = prof.runctx(arg_str,namespace,namespace)
1494 1494 sys_exit = ''
1495 1495 except SystemExit:
1496 1496 sys_exit = """*** SystemExit exception caught in code being profiled."""
1497 1497
1498 1498 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1499 1499
1500 1500 lims = opts.l
1501 1501 if lims:
1502 1502 lims = [] # rebuild lims with ints/floats/strings
1503 1503 for lim in opts.l:
1504 1504 try:
1505 1505 lims.append(int(lim))
1506 1506 except ValueError:
1507 1507 try:
1508 1508 lims.append(float(lim))
1509 1509 except ValueError:
1510 1510 lims.append(lim)
1511 1511
1512 1512 # Trap output.
1513 1513 stdout_trap = StringIO()
1514 1514
1515 1515 if hasattr(stats,'stream'):
1516 1516 # In newer versions of python, the stats object has a 'stream'
1517 1517 # attribute to write into.
1518 1518 stats.stream = stdout_trap
1519 1519 stats.print_stats(*lims)
1520 1520 else:
1521 1521 # For older versions, we manually redirect stdout during printing
1522 1522 sys_stdout = sys.stdout
1523 1523 try:
1524 1524 sys.stdout = stdout_trap
1525 1525 stats.print_stats(*lims)
1526 1526 finally:
1527 1527 sys.stdout = sys_stdout
1528 1528
1529 1529 output = stdout_trap.getvalue()
1530 1530 output = output.rstrip()
1531 1531
1532 1532 if 'q' not in opts:
1533 1533 page.page(output)
1534 1534 print sys_exit,
1535 1535
1536 1536 dump_file = opts.D[0]
1537 1537 text_file = opts.T[0]
1538 1538 if dump_file:
1539 1539 dump_file = unquote_filename(dump_file)
1540 1540 prof.dump_stats(dump_file)
1541 1541 print '\n*** Profile stats marshalled to file',\
1542 1542 `dump_file`+'.',sys_exit
1543 1543 if text_file:
1544 1544 text_file = unquote_filename(text_file)
1545 1545 pfile = open(text_file,'w')
1546 1546 pfile.write(output)
1547 1547 pfile.close()
1548 1548 print '\n*** Profile printout saved to text file',\
1549 1549 `text_file`+'.',sys_exit
1550 1550
1551 1551 if opts.has_key('r'):
1552 1552 return stats
1553 1553 else:
1554 1554 return None
1555 1555
1556 1556 @skip_doctest
1557 1557 def magic_run(self, parameter_s ='', runner=None,
1558 1558 file_finder=get_py_filename):
1559 1559 """Run the named file inside IPython as a program.
1560 1560
1561 1561 Usage:\\
1562 1562 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1563 1563
1564 1564 Parameters after the filename are passed as command-line arguments to
1565 1565 the program (put in sys.argv). Then, control returns to IPython's
1566 1566 prompt.
1567 1567
1568 1568 This is similar to running at a system prompt:\\
1569 1569 $ python file args\\
1570 1570 but with the advantage of giving you IPython's tracebacks, and of
1571 1571 loading all variables into your interactive namespace for further use
1572 1572 (unless -p is used, see below).
1573 1573
1574 1574 The file is executed in a namespace initially consisting only of
1575 1575 __name__=='__main__' and sys.argv constructed as indicated. It thus
1576 1576 sees its environment as if it were being run as a stand-alone program
1577 1577 (except for sharing global objects such as previously imported
1578 1578 modules). But after execution, the IPython interactive namespace gets
1579 1579 updated with all variables defined in the program (except for __name__
1580 1580 and sys.argv). This allows for very convenient loading of code for
1581 1581 interactive work, while giving each program a 'clean sheet' to run in.
1582 1582
1583 1583 Options:
1584 1584
1585 1585 -n: __name__ is NOT set to '__main__', but to the running file's name
1586 1586 without extension (as python does under import). This allows running
1587 1587 scripts and reloading the definitions in them without calling code
1588 1588 protected by an ' if __name__ == "__main__" ' clause.
1589 1589
1590 1590 -i: run the file in IPython's namespace instead of an empty one. This
1591 1591 is useful if you are experimenting with code written in a text editor
1592 1592 which depends on variables defined interactively.
1593 1593
1594 1594 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1595 1595 being run. This is particularly useful if IPython is being used to
1596 1596 run unittests, which always exit with a sys.exit() call. In such
1597 1597 cases you are interested in the output of the test results, not in
1598 1598 seeing a traceback of the unittest module.
1599 1599
1600 1600 -t: print timing information at the end of the run. IPython will give
1601 1601 you an estimated CPU time consumption for your script, which under
1602 1602 Unix uses the resource module to avoid the wraparound problems of
1603 1603 time.clock(). Under Unix, an estimate of time spent on system tasks
1604 1604 is also given (for Windows platforms this is reported as 0.0).
1605 1605
1606 1606 If -t is given, an additional -N<N> option can be given, where <N>
1607 1607 must be an integer indicating how many times you want the script to
1608 1608 run. The final timing report will include total and per run results.
1609 1609
1610 1610 For example (testing the script uniq_stable.py)::
1611 1611
1612 1612 In [1]: run -t uniq_stable
1613 1613
1614 1614 IPython CPU timings (estimated):\\
1615 1615 User : 0.19597 s.\\
1616 1616 System: 0.0 s.\\
1617 1617
1618 1618 In [2]: run -t -N5 uniq_stable
1619 1619
1620 1620 IPython CPU timings (estimated):\\
1621 1621 Total runs performed: 5\\
1622 1622 Times : Total Per run\\
1623 1623 User : 0.910862 s, 0.1821724 s.\\
1624 1624 System: 0.0 s, 0.0 s.
1625 1625
1626 1626 -d: run your program under the control of pdb, the Python debugger.
1627 1627 This allows you to execute your program step by step, watch variables,
1628 1628 etc. Internally, what IPython does is similar to calling:
1629 1629
1630 1630 pdb.run('execfile("YOURFILENAME")')
1631 1631
1632 1632 with a breakpoint set on line 1 of your file. You can change the line
1633 1633 number for this automatic breakpoint to be <N> by using the -bN option
1634 1634 (where N must be an integer). For example::
1635 1635
1636 1636 %run -d -b40 myscript
1637 1637
1638 1638 will set the first breakpoint at line 40 in myscript.py. Note that
1639 1639 the first breakpoint must be set on a line which actually does
1640 1640 something (not a comment or docstring) for it to stop execution.
1641 1641
1642 1642 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1643 1643 first enter 'c' (without quotes) to start execution up to the first
1644 1644 breakpoint.
1645 1645
1646 1646 Entering 'help' gives information about the use of the debugger. You
1647 1647 can easily see pdb's full documentation with "import pdb;pdb.help()"
1648 1648 at a prompt.
1649 1649
1650 1650 -p: run program under the control of the Python profiler module (which
1651 1651 prints a detailed report of execution times, function calls, etc).
1652 1652
1653 1653 You can pass other options after -p which affect the behavior of the
1654 1654 profiler itself. See the docs for %prun for details.
1655 1655
1656 1656 In this mode, the program's variables do NOT propagate back to the
1657 1657 IPython interactive namespace (because they remain in the namespace
1658 1658 where the profiler executes them).
1659 1659
1660 1660 Internally this triggers a call to %prun, see its documentation for
1661 1661 details on the options available specifically for profiling.
1662 1662
1663 1663 There is one special usage for which the text above doesn't apply:
1664 1664 if the filename ends with .ipy, the file is run as ipython script,
1665 1665 just as if the commands were written on IPython prompt.
1666 1666
1667 1667 -m: specify module name to load instead of script path. Similar to
1668 1668 the -m option for the python interpreter. Use this option last if you
1669 1669 want to combine with other %run options. Unlike the python interpreter
1670 1670 only source modules are allowed no .pyc or .pyo files.
1671 1671 For example::
1672 1672
1673 1673 %run -m example
1674 1674
1675 1675 will run the example module.
1676 1676
1677 1677 """
1678 1678
1679 1679 # get arguments and set sys.argv for program to be run.
1680 1680 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1681 1681 mode='list', list_all=1)
1682 1682 if "m" in opts:
1683 1683 modulename = opts["m"][0]
1684 1684 modpath = find_mod(modulename)
1685 1685 if modpath is None:
1686 1686 warn('%r is not a valid modulename on sys.path'%modulename)
1687 1687 return
1688 1688 arg_lst = [modpath] + arg_lst
1689 1689 try:
1690 1690 filename = file_finder(arg_lst[0])
1691 1691 except IndexError:
1692 1692 warn('you must provide at least a filename.')
1693 1693 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1694 1694 return
1695 1695 except IOError as e:
1696 1696 try:
1697 1697 msg = str(e)
1698 1698 except UnicodeError:
1699 1699 msg = e.message
1700 1700 error(msg)
1701 1701 return
1702 1702
1703 1703 if filename.lower().endswith('.ipy'):
1704 1704 self.shell.safe_execfile_ipy(filename)
1705 1705 return
1706 1706
1707 1707 # Control the response to exit() calls made by the script being run
1708 1708 exit_ignore = 'e' in opts
1709 1709
1710 1710 # Make sure that the running script gets a proper sys.argv as if it
1711 1711 # were run from a system shell.
1712 1712 save_argv = sys.argv # save it for later restoring
1713 1713
1714 1714 # simulate shell expansion on arguments, at least tilde expansion
1715 1715 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1716 1716
1717 1717 sys.argv = [filename] + args # put in the proper filename
1718 1718 # protect sys.argv from potential unicode strings on Python 2:
1719 1719 if not py3compat.PY3:
1720 1720 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1721 1721
1722 1722 if 'i' in opts:
1723 1723 # Run in user's interactive namespace
1724 1724 prog_ns = self.shell.user_ns
1725 1725 __name__save = self.shell.user_ns['__name__']
1726 1726 prog_ns['__name__'] = '__main__'
1727 1727 main_mod = self.shell.new_main_mod(prog_ns)
1728 1728 else:
1729 1729 # Run in a fresh, empty namespace
1730 1730 if 'n' in opts:
1731 1731 name = os.path.splitext(os.path.basename(filename))[0]
1732 1732 else:
1733 1733 name = '__main__'
1734 1734
1735 1735 main_mod = self.shell.new_main_mod()
1736 1736 prog_ns = main_mod.__dict__
1737 1737 prog_ns['__name__'] = name
1738 1738
1739 1739 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1740 1740 # set the __file__ global in the script's namespace
1741 1741 prog_ns['__file__'] = filename
1742 1742
1743 1743 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1744 1744 # that, if we overwrite __main__, we replace it at the end
1745 1745 main_mod_name = prog_ns['__name__']
1746 1746
1747 1747 if main_mod_name == '__main__':
1748 1748 restore_main = sys.modules['__main__']
1749 1749 else:
1750 1750 restore_main = False
1751 1751
1752 1752 # This needs to be undone at the end to prevent holding references to
1753 1753 # every single object ever created.
1754 1754 sys.modules[main_mod_name] = main_mod
1755 1755
1756 1756 try:
1757 1757 stats = None
1758 1758 with self.readline_no_record:
1759 1759 if 'p' in opts:
1760 1760 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1761 1761 else:
1762 1762 if 'd' in opts:
1763 1763 deb = debugger.Pdb(self.shell.colors)
1764 1764 # reset Breakpoint state, which is moronically kept
1765 1765 # in a class
1766 1766 bdb.Breakpoint.next = 1
1767 1767 bdb.Breakpoint.bplist = {}
1768 1768 bdb.Breakpoint.bpbynumber = [None]
1769 1769 # Set an initial breakpoint to stop execution
1770 1770 maxtries = 10
1771 1771 bp = int(opts.get('b', [1])[0])
1772 1772 checkline = deb.checkline(filename, bp)
1773 1773 if not checkline:
1774 1774 for bp in range(bp + 1, bp + maxtries + 1):
1775 1775 if deb.checkline(filename, bp):
1776 1776 break
1777 1777 else:
1778 1778 msg = ("\nI failed to find a valid line to set "
1779 1779 "a breakpoint\n"
1780 1780 "after trying up to line: %s.\n"
1781 1781 "Please set a valid breakpoint manually "
1782 1782 "with the -b option." % bp)
1783 1783 error(msg)
1784 1784 return
1785 1785 # if we find a good linenumber, set the breakpoint
1786 1786 deb.do_break('%s:%s' % (filename, bp))
1787 1787 # Start file run
1788 1788 print "NOTE: Enter 'c' at the",
1789 1789 print "%s prompt to start your script." % deb.prompt
1790 1790 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
1791 1791 try:
1792 1792 deb.run('execfile("%s", prog_ns)' % filename, ns)
1793 1793
1794 1794 except:
1795 1795 etype, value, tb = sys.exc_info()
1796 1796 # Skip three frames in the traceback: the %run one,
1797 1797 # one inside bdb.py, and the command-line typed by the
1798 1798 # user (run by exec in pdb itself).
1799 1799 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1800 1800 else:
1801 1801 if runner is None:
1802 1802 runner = self.shell.safe_execfile
1803 1803 if 't' in opts:
1804 1804 # timed execution
1805 1805 try:
1806 1806 nruns = int(opts['N'][0])
1807 1807 if nruns < 1:
1808 1808 error('Number of runs must be >=1')
1809 1809 return
1810 1810 except (KeyError):
1811 1811 nruns = 1
1812 1812 twall0 = time.time()
1813 1813 if nruns == 1:
1814 1814 t0 = clock2()
1815 1815 runner(filename, prog_ns, prog_ns,
1816 1816 exit_ignore=exit_ignore)
1817 1817 t1 = clock2()
1818 1818 t_usr = t1[0] - t0[0]
1819 1819 t_sys = t1[1] - t0[1]
1820 1820 print "\nIPython CPU timings (estimated):"
1821 1821 print " User : %10.2f s." % t_usr
1822 1822 print " System : %10.2f s." % t_sys
1823 1823 else:
1824 1824 runs = range(nruns)
1825 1825 t0 = clock2()
1826 1826 for nr in runs:
1827 1827 runner(filename, prog_ns, prog_ns,
1828 1828 exit_ignore=exit_ignore)
1829 1829 t1 = clock2()
1830 1830 t_usr = t1[0] - t0[0]
1831 1831 t_sys = t1[1] - t0[1]
1832 1832 print "\nIPython CPU timings (estimated):"
1833 1833 print "Total runs performed:", nruns
1834 1834 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1835 1835 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1836 1836 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1837 1837 twall1 = time.time()
1838 1838 print "Wall time: %10.2f s." % (twall1 - twall0)
1839 1839
1840 1840 else:
1841 1841 # regular execution
1842 1842 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1843 1843
1844 1844 if 'i' in opts:
1845 1845 self.shell.user_ns['__name__'] = __name__save
1846 1846 else:
1847 1847 # The shell MUST hold a reference to prog_ns so after %run
1848 1848 # exits, the python deletion mechanism doesn't zero it out
1849 1849 # (leaving dangling references).
1850 1850 self.shell.cache_main_mod(prog_ns, filename)
1851 1851 # update IPython interactive namespace
1852 1852
1853 1853 # Some forms of read errors on the file may mean the
1854 1854 # __name__ key was never set; using pop we don't have to
1855 1855 # worry about a possible KeyError.
1856 1856 prog_ns.pop('__name__', None)
1857 1857
1858 1858 self.shell.user_ns.update(prog_ns)
1859 1859 finally:
1860 1860 # It's a bit of a mystery why, but __builtins__ can change from
1861 1861 # being a module to becoming a dict missing some key data after
1862 1862 # %run. As best I can see, this is NOT something IPython is doing
1863 1863 # at all, and similar problems have been reported before:
1864 1864 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1865 1865 # Since this seems to be done by the interpreter itself, the best
1866 1866 # we can do is to at least restore __builtins__ for the user on
1867 1867 # exit.
1868 1868 self.shell.user_ns['__builtins__'] = builtin_mod
1869 1869
1870 1870 # Ensure key global structures are restored
1871 1871 sys.argv = save_argv
1872 1872 if restore_main:
1873 1873 sys.modules['__main__'] = restore_main
1874 1874 else:
1875 1875 # Remove from sys.modules the reference to main_mod we'd
1876 1876 # added. Otherwise it will trap references to objects
1877 1877 # contained therein.
1878 1878 del sys.modules[main_mod_name]
1879 1879
1880 1880 return stats
1881 1881
1882 1882 @skip_doctest
1883 1883 def magic_timeit(self, parameter_s =''):
1884 1884 """Time execution of a Python statement or expression
1885 1885
1886 1886 Usage:\\
1887 1887 %timeit [-n<N> -r<R> [-t|-c]] statement
1888 1888
1889 1889 Time execution of a Python statement or expression using the timeit
1890 1890 module.
1891 1891
1892 1892 Options:
1893 1893 -n<N>: execute the given statement <N> times in a loop. If this value
1894 1894 is not given, a fitting value is chosen.
1895 1895
1896 1896 -r<R>: repeat the loop iteration <R> times and take the best result.
1897 1897 Default: 3
1898 1898
1899 1899 -t: use time.time to measure the time, which is the default on Unix.
1900 1900 This function measures wall time.
1901 1901
1902 1902 -c: use time.clock to measure the time, which is the default on
1903 1903 Windows and measures wall time. On Unix, resource.getrusage is used
1904 1904 instead and returns the CPU user time.
1905 1905
1906 1906 -p<P>: use a precision of <P> digits to display the timing result.
1907 1907 Default: 3
1908 1908
1909 1909
1910 1910 Examples
1911 1911 --------
1912 1912 ::
1913 1913
1914 1914 In [1]: %timeit pass
1915 1915 10000000 loops, best of 3: 53.3 ns per loop
1916 1916
1917 1917 In [2]: u = None
1918 1918
1919 1919 In [3]: %timeit u is None
1920 1920 10000000 loops, best of 3: 184 ns per loop
1921 1921
1922 1922 In [4]: %timeit -r 4 u == None
1923 1923 1000000 loops, best of 4: 242 ns per loop
1924 1924
1925 1925 In [5]: import time
1926 1926
1927 1927 In [6]: %timeit -n1 time.sleep(2)
1928 1928 1 loops, best of 3: 2 s per loop
1929 1929
1930 1930
1931 1931 The times reported by %timeit will be slightly higher than those
1932 1932 reported by the timeit.py script when variables are accessed. This is
1933 1933 due to the fact that %timeit executes the statement in the namespace
1934 1934 of the shell, compared with timeit.py, which uses a single setup
1935 1935 statement to import function or create variables. Generally, the bias
1936 1936 does not matter as long as results from timeit.py are not mixed with
1937 1937 those from %timeit."""
1938 1938
1939 1939 import timeit
1940 1940 import math
1941 1941
1942 1942 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1943 1943 # certain terminals. Until we figure out a robust way of
1944 1944 # auto-detecting if the terminal can deal with it, use plain 'us' for
1945 1945 # microseconds. I am really NOT happy about disabling the proper
1946 1946 # 'micro' prefix, but crashing is worse... If anyone knows what the
1947 1947 # right solution for this is, I'm all ears...
1948 1948 #
1949 1949 # Note: using
1950 1950 #
1951 1951 # s = u'\xb5'
1952 1952 # s.encode(sys.getdefaultencoding())
1953 1953 #
1954 1954 # is not sufficient, as I've seen terminals where that fails but
1955 1955 # print s
1956 1956 #
1957 1957 # succeeds
1958 1958 #
1959 1959 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1960 1960
1961 1961 #units = [u"s", u"ms",u'\xb5',"ns"]
1962 1962 units = [u"s", u"ms",u'us',"ns"]
1963 1963
1964 1964 scaling = [1, 1e3, 1e6, 1e9]
1965 1965
1966 1966 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1967 1967 posix=False, strict=False)
1968 1968 if stmt == "":
1969 1969 return
1970 1970 timefunc = timeit.default_timer
1971 1971 number = int(getattr(opts, "n", 0))
1972 1972 repeat = int(getattr(opts, "r", timeit.default_repeat))
1973 1973 precision = int(getattr(opts, "p", 3))
1974 1974 if hasattr(opts, "t"):
1975 1975 timefunc = time.time
1976 1976 if hasattr(opts, "c"):
1977 1977 timefunc = clock
1978 1978
1979 1979 timer = timeit.Timer(timer=timefunc)
1980 1980 # this code has tight coupling to the inner workings of timeit.Timer,
1981 1981 # but is there a better way to achieve that the code stmt has access
1982 1982 # to the shell namespace?
1983 1983
1984 1984 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1985 1985 'setup': "pass"}
1986 1986 # Track compilation time so it can be reported if too long
1987 1987 # Minimum time above which compilation time will be reported
1988 1988 tc_min = 0.1
1989 1989
1990 1990 t0 = clock()
1991 1991 code = compile(src, "<magic-timeit>", "exec")
1992 1992 tc = clock()-t0
1993 1993
1994 1994 ns = {}
1995 1995 exec code in self.shell.user_ns, ns
1996 1996 timer.inner = ns["inner"]
1997 1997
1998 1998 if number == 0:
1999 1999 # determine number so that 0.2 <= total time < 2.0
2000 2000 number = 1
2001 2001 for i in range(1, 10):
2002 2002 if timer.timeit(number) >= 0.2:
2003 2003 break
2004 2004 number *= 10
2005 2005
2006 2006 best = min(timer.repeat(repeat, number)) / number
2007 2007
2008 2008 if best > 0.0 and best < 1000.0:
2009 2009 order = min(-int(math.floor(math.log10(best)) // 3), 3)
2010 2010 elif best >= 1000.0:
2011 2011 order = 0
2012 2012 else:
2013 2013 order = 3
2014 2014 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
2015 2015 precision,
2016 2016 best * scaling[order],
2017 2017 units[order])
2018 2018 if tc > tc_min:
2019 2019 print "Compiler time: %.2f s" % tc
2020 2020
2021 2021 @skip_doctest
2022 2022 @needs_local_scope
2023 2023 def magic_time(self,parameter_s = ''):
2024 2024 """Time execution of a Python statement or expression.
2025 2025
2026 2026 The CPU and wall clock times are printed, and the value of the
2027 2027 expression (if any) is returned. Note that under Win32, system time
2028 2028 is always reported as 0, since it can not be measured.
2029 2029
2030 2030 This function provides very basic timing functionality. In Python
2031 2031 2.3, the timeit module offers more control and sophistication, so this
2032 2032 could be rewritten to use it (patches welcome).
2033 2033
2034 2034 Examples
2035 2035 --------
2036 2036 ::
2037 2037
2038 2038 In [1]: time 2**128
2039 2039 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2040 2040 Wall time: 0.00
2041 2041 Out[1]: 340282366920938463463374607431768211456L
2042 2042
2043 2043 In [2]: n = 1000000
2044 2044
2045 2045 In [3]: time sum(range(n))
2046 2046 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2047 2047 Wall time: 1.37
2048 2048 Out[3]: 499999500000L
2049 2049
2050 2050 In [4]: time print 'hello world'
2051 2051 hello world
2052 2052 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2053 2053 Wall time: 0.00
2054 2054
2055 2055 Note that the time needed by Python to compile the given expression
2056 2056 will be reported if it is more than 0.1s. In this example, the
2057 2057 actual exponentiation is done by Python at compilation time, so while
2058 2058 the expression can take a noticeable amount of time to compute, that
2059 2059 time is purely due to the compilation:
2060 2060
2061 2061 In [5]: time 3**9999;
2062 2062 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2063 2063 Wall time: 0.00 s
2064 2064
2065 2065 In [6]: time 3**999999;
2066 2066 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2067 2067 Wall time: 0.00 s
2068 2068 Compiler : 0.78 s
2069 2069 """
2070 2070
2071 2071 # fail immediately if the given expression can't be compiled
2072 2072
2073 2073 expr = self.shell.prefilter(parameter_s,False)
2074 2074
2075 2075 # Minimum time above which compilation time will be reported
2076 2076 tc_min = 0.1
2077 2077
2078 2078 try:
2079 2079 mode = 'eval'
2080 2080 t0 = clock()
2081 2081 code = compile(expr,'<timed eval>',mode)
2082 2082 tc = clock()-t0
2083 2083 except SyntaxError:
2084 2084 mode = 'exec'
2085 2085 t0 = clock()
2086 2086 code = compile(expr,'<timed exec>',mode)
2087 2087 tc = clock()-t0
2088 2088 # skew measurement as little as possible
2089 2089 glob = self.shell.user_ns
2090 2090 locs = self._magic_locals
2091 2091 clk = clock2
2092 2092 wtime = time.time
2093 2093 # time execution
2094 2094 wall_st = wtime()
2095 2095 if mode=='eval':
2096 2096 st = clk()
2097 2097 out = eval(code, glob, locs)
2098 2098 end = clk()
2099 2099 else:
2100 2100 st = clk()
2101 2101 exec code in glob, locs
2102 2102 end = clk()
2103 2103 out = None
2104 2104 wall_end = wtime()
2105 2105 # Compute actual times and report
2106 2106 wall_time = wall_end-wall_st
2107 2107 cpu_user = end[0]-st[0]
2108 2108 cpu_sys = end[1]-st[1]
2109 2109 cpu_tot = cpu_user+cpu_sys
2110 2110 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2111 2111 (cpu_user,cpu_sys,cpu_tot)
2112 2112 print "Wall time: %.2f s" % wall_time
2113 2113 if tc > tc_min:
2114 2114 print "Compiler : %.2f s" % tc
2115 2115 return out
2116 2116
2117 2117 @skip_doctest
2118 2118 def magic_macro(self,parameter_s = ''):
2119 2119 """Define a macro for future re-execution. It accepts ranges of history,
2120 2120 filenames or string objects.
2121 2121
2122 2122 Usage:\\
2123 2123 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2124 2124
2125 2125 Options:
2126 2126
2127 2127 -r: use 'raw' input. By default, the 'processed' history is used,
2128 2128 so that magics are loaded in their transformed version to valid
2129 2129 Python. If this option is given, the raw input as typed as the
2130 2130 command line is used instead.
2131 2131
2132 2132 This will define a global variable called `name` which is a string
2133 2133 made of joining the slices and lines you specify (n1,n2,... numbers
2134 2134 above) from your input history into a single string. This variable
2135 2135 acts like an automatic function which re-executes those lines as if
2136 2136 you had typed them. You just type 'name' at the prompt and the code
2137 2137 executes.
2138 2138
2139 2139 The syntax for indicating input ranges is described in %history.
2140 2140
2141 2141 Note: as a 'hidden' feature, you can also use traditional python slice
2142 2142 notation, where N:M means numbers N through M-1.
2143 2143
2144 2144 For example, if your history contains (%hist prints it)::
2145 2145
2146 2146 44: x=1
2147 2147 45: y=3
2148 2148 46: z=x+y
2149 2149 47: print x
2150 2150 48: a=5
2151 2151 49: print 'x',x,'y',y
2152 2152
2153 2153 you can create a macro with lines 44 through 47 (included) and line 49
2154 2154 called my_macro with::
2155 2155
2156 2156 In [55]: %macro my_macro 44-47 49
2157 2157
2158 2158 Now, typing `my_macro` (without quotes) will re-execute all this code
2159 2159 in one pass.
2160 2160
2161 2161 You don't need to give the line-numbers in order, and any given line
2162 2162 number can appear multiple times. You can assemble macros with any
2163 2163 lines from your input history in any order.
2164 2164
2165 2165 The macro is a simple object which holds its value in an attribute,
2166 2166 but IPython's display system checks for macros and executes them as
2167 2167 code instead of printing them when you type their name.
2168 2168
2169 2169 You can view a macro's contents by explicitly printing it with::
2170 2170
2171 2171 print macro_name
2172 2172
2173 2173 """
2174 2174 opts,args = self.parse_options(parameter_s,'r',mode='list')
2175 2175 if not args: # List existing macros
2176 2176 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2177 2177 isinstance(v, Macro))
2178 2178 if len(args) == 1:
2179 2179 raise UsageError(
2180 2180 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2181 2181 name, codefrom = args[0], " ".join(args[1:])
2182 2182
2183 2183 #print 'rng',ranges # dbg
2184 2184 try:
2185 2185 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2186 2186 except (ValueError, TypeError) as e:
2187 2187 print e.args[0]
2188 2188 return
2189 2189 macro = Macro(lines)
2190 2190 self.shell.define_macro(name, macro)
2191 2191 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2192 2192 print '=== Macro contents: ==='
2193 2193 print macro,
2194 2194
2195 2195 def magic_save(self,parameter_s = ''):
2196 2196 """Save a set of lines or a macro to a given filename.
2197 2197
2198 2198 Usage:\\
2199 2199 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2200 2200
2201 2201 Options:
2202 2202
2203 2203 -r: use 'raw' input. By default, the 'processed' history is used,
2204 2204 so that magics are loaded in their transformed version to valid
2205 2205 Python. If this option is given, the raw input as typed as the
2206 2206 command line is used instead.
2207 2207
2208 2208 This function uses the same syntax as %history for input ranges,
2209 2209 then saves the lines to the filename you specify.
2210 2210
2211 2211 It adds a '.py' extension to the file if you don't do so yourself, and
2212 2212 it asks for confirmation before overwriting existing files."""
2213 2213
2214 2214 opts,args = self.parse_options(parameter_s,'r',mode='list')
2215 2215 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2216 2216 if not fname.endswith('.py'):
2217 2217 fname += '.py'
2218 2218 if os.path.isfile(fname):
2219 2219 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2220 2220 if ans.lower() not in ['y','yes']:
2221 2221 print 'Operation cancelled.'
2222 2222 return
2223 2223 try:
2224 2224 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2225 2225 except (TypeError, ValueError) as e:
2226 2226 print e.args[0]
2227 2227 return
2228 2228 with io.open(fname,'w', encoding="utf-8") as f:
2229 2229 f.write(u"# coding: utf-8\n")
2230 2230 f.write(py3compat.cast_unicode(cmds))
2231 2231 print 'The following commands were written to file `%s`:' % fname
2232 2232 print cmds
2233 2233
2234 2234 def magic_pastebin(self, parameter_s = ''):
2235 2235 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2236 2236 try:
2237 2237 code = self.shell.find_user_code(parameter_s)
2238 2238 except (ValueError, TypeError) as e:
2239 2239 print e.args[0]
2240 2240 return
2241 2241 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2242 2242 id = pbserver.pastes.newPaste("python", code)
2243 2243 return "http://paste.pocoo.org/show/" + id
2244 2244
2245 2245 def magic_loadpy(self, arg_s):
2246 2246 """Load a .py python script into the GUI console.
2247 2247
2248 2248 This magic command can either take a local filename or a url::
2249 2249
2250 2250 %loadpy myscript.py
2251 2251 %loadpy http://www.example.com/myscript.py
2252 2252 """
2253 2253 arg_s = unquote_filename(arg_s)
2254 2254 remote_url = arg_s.startswith(('http://', 'https://'))
2255 2255 local_url = not remote_url
2256 2256 if local_url and not arg_s.endswith('.py'):
2257 2257 # Local files must be .py; for remote URLs it's possible that the
2258 2258 # fetch URL doesn't have a .py in it (many servers have an opaque
2259 2259 # URL, such as scipy-central.org).
2260 2260 raise ValueError('%%loadpy only works with .py files: %s' % arg_s)
2261 2261
2262 2262 # openpy takes care of finding the source encoding (per PEP 263)
2263 2263 if remote_url:
2264 2264 contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True)
2265 2265 else:
2266 2266 contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True)
2267 2267
2268 2268 self.set_next_input(contents)
2269 2269
2270 2270 def _find_edit_target(self, args, opts, last_call):
2271 2271 """Utility method used by magic_edit to find what to edit."""
2272 2272
2273 2273 def make_filename(arg):
2274 2274 "Make a filename from the given args"
2275 2275 arg = unquote_filename(arg)
2276 2276 try:
2277 2277 filename = get_py_filename(arg)
2278 2278 except IOError:
2279 2279 # If it ends with .py but doesn't already exist, assume we want
2280 2280 # a new file.
2281 2281 if arg.endswith('.py'):
2282 2282 filename = arg
2283 2283 else:
2284 2284 filename = None
2285 2285 return filename
2286 2286
2287 2287 # Set a few locals from the options for convenience:
2288 2288 opts_prev = 'p' in opts
2289 2289 opts_raw = 'r' in opts
2290 2290
2291 2291 # custom exceptions
2292 2292 class DataIsObject(Exception): pass
2293 2293
2294 2294 # Default line number value
2295 2295 lineno = opts.get('n',None)
2296 2296
2297 2297 if opts_prev:
2298 2298 args = '_%s' % last_call[0]
2299 2299 if not self.shell.user_ns.has_key(args):
2300 2300 args = last_call[1]
2301 2301
2302 2302 # use last_call to remember the state of the previous call, but don't
2303 2303 # let it be clobbered by successive '-p' calls.
2304 2304 try:
2305 2305 last_call[0] = self.shell.displayhook.prompt_count
2306 2306 if not opts_prev:
2307 2307 last_call[1] = args
2308 2308 except:
2309 2309 pass
2310 2310
2311 2311 # by default this is done with temp files, except when the given
2312 2312 # arg is a filename
2313 2313 use_temp = True
2314 2314
2315 2315 data = ''
2316 2316
2317 2317 # First, see if the arguments should be a filename.
2318 2318 filename = make_filename(args)
2319 2319 if filename:
2320 2320 use_temp = False
2321 2321 elif args:
2322 2322 # Mode where user specifies ranges of lines, like in %macro.
2323 2323 data = self.extract_input_lines(args, opts_raw)
2324 2324 if not data:
2325 2325 try:
2326 2326 # Load the parameter given as a variable. If not a string,
2327 2327 # process it as an object instead (below)
2328 2328
2329 2329 #print '*** args',args,'type',type(args) # dbg
2330 2330 data = eval(args, self.shell.user_ns)
2331 2331 if not isinstance(data, basestring):
2332 2332 raise DataIsObject
2333 2333
2334 2334 except (NameError,SyntaxError):
2335 2335 # given argument is not a variable, try as a filename
2336 2336 filename = make_filename(args)
2337 2337 if filename is None:
2338 2338 warn("Argument given (%s) can't be found as a variable "
2339 2339 "or as a filename." % args)
2340 2340 return
2341 2341 use_temp = False
2342 2342
2343 2343 except DataIsObject:
2344 2344 # macros have a special edit function
2345 2345 if isinstance(data, Macro):
2346 2346 raise MacroToEdit(data)
2347 2347
2348 2348 # For objects, try to edit the file where they are defined
2349 2349 try:
2350 2350 filename = inspect.getabsfile(data)
2351 2351 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2352 2352 # class created by %edit? Try to find source
2353 2353 # by looking for method definitions instead, the
2354 2354 # __module__ in those classes is FakeModule.
2355 2355 attrs = [getattr(data, aname) for aname in dir(data)]
2356 2356 for attr in attrs:
2357 2357 if not inspect.ismethod(attr):
2358 2358 continue
2359 2359 filename = inspect.getabsfile(attr)
2360 2360 if filename and 'fakemodule' not in filename.lower():
2361 2361 # change the attribute to be the edit target instead
2362 2362 data = attr
2363 2363 break
2364 2364
2365 2365 datafile = 1
2366 2366 except TypeError:
2367 2367 filename = make_filename(args)
2368 2368 datafile = 1
2369 2369 warn('Could not find file where `%s` is defined.\n'
2370 2370 'Opening a file named `%s`' % (args,filename))
2371 2371 # Now, make sure we can actually read the source (if it was in
2372 2372 # a temp file it's gone by now).
2373 2373 if datafile:
2374 2374 try:
2375 2375 if lineno is None:
2376 2376 lineno = inspect.getsourcelines(data)[1]
2377 2377 except IOError:
2378 2378 filename = make_filename(args)
2379 2379 if filename is None:
2380 2380 warn('The file `%s` where `%s` was defined cannot '
2381 2381 'be read.' % (filename,data))
2382 2382 return
2383 2383 use_temp = False
2384 2384
2385 2385 if use_temp:
2386 2386 filename = self.shell.mktempfile(data)
2387 2387 print 'IPython will make a temporary file named:',filename
2388 2388
2389 2389 return filename, lineno, use_temp
2390 2390
2391 2391 def _edit_macro(self,mname,macro):
2392 2392 """open an editor with the macro data in a file"""
2393 2393 filename = self.shell.mktempfile(macro.value)
2394 2394 self.shell.hooks.editor(filename)
2395 2395
2396 2396 # and make a new macro object, to replace the old one
2397 2397 mfile = open(filename)
2398 2398 mvalue = mfile.read()
2399 2399 mfile.close()
2400 2400 self.shell.user_ns[mname] = Macro(mvalue)
2401 2401
2402 2402 def magic_ed(self,parameter_s=''):
2403 2403 """Alias to %edit."""
2404 2404 return self.magic_edit(parameter_s)
2405 2405
2406 2406 @skip_doctest
2407 2407 def magic_edit(self,parameter_s='',last_call=['','']):
2408 2408 """Bring up an editor and execute the resulting code.
2409 2409
2410 2410 Usage:
2411 2411 %edit [options] [args]
2412 2412
2413 2413 %edit runs IPython's editor hook. The default version of this hook is
2414 2414 set to call the editor specified by your $EDITOR environment variable.
2415 2415 If this isn't found, it will default to vi under Linux/Unix and to
2416 2416 notepad under Windows. See the end of this docstring for how to change
2417 2417 the editor hook.
2418 2418
2419 2419 You can also set the value of this editor via the
2420 2420 ``TerminalInteractiveShell.editor`` option in your configuration file.
2421 2421 This is useful if you wish to use a different editor from your typical
2422 2422 default with IPython (and for Windows users who typically don't set
2423 2423 environment variables).
2424 2424
2425 2425 This command allows you to conveniently edit multi-line code right in
2426 2426 your IPython session.
2427 2427
2428 2428 If called without arguments, %edit opens up an empty editor with a
2429 2429 temporary file and will execute the contents of this file when you
2430 2430 close it (don't forget to save it!).
2431 2431
2432 2432
2433 2433 Options:
2434 2434
2435 2435 -n <number>: open the editor at a specified line number. By default,
2436 2436 the IPython editor hook uses the unix syntax 'editor +N filename', but
2437 2437 you can configure this by providing your own modified hook if your
2438 2438 favorite editor supports line-number specifications with a different
2439 2439 syntax.
2440 2440
2441 2441 -p: this will call the editor with the same data as the previous time
2442 2442 it was used, regardless of how long ago (in your current session) it
2443 2443 was.
2444 2444
2445 2445 -r: use 'raw' input. This option only applies to input taken from the
2446 2446 user's history. By default, the 'processed' history is used, so that
2447 2447 magics are loaded in their transformed version to valid Python. If
2448 2448 this option is given, the raw input as typed as the command line is
2449 2449 used instead. When you exit the editor, it will be executed by
2450 2450 IPython's own processor.
2451 2451
2452 2452 -x: do not execute the edited code immediately upon exit. This is
2453 2453 mainly useful if you are editing programs which need to be called with
2454 2454 command line arguments, which you can then do using %run.
2455 2455
2456 2456
2457 2457 Arguments:
2458 2458
2459 2459 If arguments are given, the following possibilities exist:
2460 2460
2461 2461 - If the argument is a filename, IPython will load that into the
2462 2462 editor. It will execute its contents with execfile() when you exit,
2463 2463 loading any code in the file into your interactive namespace.
2464 2464
2465 2465 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2466 2466 The syntax is the same as in the %history magic.
2467 2467
2468 2468 - If the argument is a string variable, its contents are loaded
2469 2469 into the editor. You can thus edit any string which contains
2470 2470 python code (including the result of previous edits).
2471 2471
2472 2472 - If the argument is the name of an object (other than a string),
2473 2473 IPython will try to locate the file where it was defined and open the
2474 2474 editor at the point where it is defined. You can use `%edit function`
2475 2475 to load an editor exactly at the point where 'function' is defined,
2476 2476 edit it and have the file be executed automatically.
2477 2477
2478 2478 - If the object is a macro (see %macro for details), this opens up your
2479 2479 specified editor with a temporary file containing the macro's data.
2480 2480 Upon exit, the macro is reloaded with the contents of the file.
2481 2481
2482 2482 Note: opening at an exact line is only supported under Unix, and some
2483 2483 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2484 2484 '+NUMBER' parameter necessary for this feature. Good editors like
2485 2485 (X)Emacs, vi, jed, pico and joe all do.
2486 2486
2487 2487 After executing your code, %edit will return as output the code you
2488 2488 typed in the editor (except when it was an existing file). This way
2489 2489 you can reload the code in further invocations of %edit as a variable,
2490 2490 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2491 2491 the output.
2492 2492
2493 2493 Note that %edit is also available through the alias %ed.
2494 2494
2495 2495 This is an example of creating a simple function inside the editor and
2496 2496 then modifying it. First, start up the editor::
2497 2497
2498 2498 In [1]: ed
2499 2499 Editing... done. Executing edited code...
2500 2500 Out[1]: 'def foo():\\n print "foo() was defined in an editing
2501 2501 session"\\n'
2502 2502
2503 2503 We can then call the function foo()::
2504 2504
2505 2505 In [2]: foo()
2506 2506 foo() was defined in an editing session
2507 2507
2508 2508 Now we edit foo. IPython automatically loads the editor with the
2509 2509 (temporary) file where foo() was previously defined::
2510 2510
2511 2511 In [3]: ed foo
2512 2512 Editing... done. Executing edited code...
2513 2513
2514 2514 And if we call foo() again we get the modified version::
2515 2515
2516 2516 In [4]: foo()
2517 2517 foo() has now been changed!
2518 2518
2519 2519 Here is an example of how to edit a code snippet successive
2520 2520 times. First we call the editor::
2521 2521
2522 2522 In [5]: ed
2523 2523 Editing... done. Executing edited code...
2524 2524 hello
2525 2525 Out[5]: "print 'hello'\\n"
2526 2526
2527 2527 Now we call it again with the previous output (stored in _)::
2528 2528
2529 2529 In [6]: ed _
2530 2530 Editing... done. Executing edited code...
2531 2531 hello world
2532 2532 Out[6]: "print 'hello world'\\n"
2533 2533
2534 2534 Now we call it with the output #8 (stored in _8, also as Out[8])::
2535 2535
2536 2536 In [7]: ed _8
2537 2537 Editing... done. Executing edited code...
2538 2538 hello again
2539 2539 Out[7]: "print 'hello again'\\n"
2540 2540
2541 2541
2542 2542 Changing the default editor hook:
2543 2543
2544 2544 If you wish to write your own editor hook, you can put it in a
2545 2545 configuration file which you load at startup time. The default hook
2546 2546 is defined in the IPython.core.hooks module, and you can use that as a
2547 2547 starting example for further modifications. That file also has
2548 2548 general instructions on how to set a new hook for use once you've
2549 2549 defined it."""
2550 2550 opts,args = self.parse_options(parameter_s,'prxn:')
2551 2551
2552 2552 try:
2553 2553 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2554 2554 except MacroToEdit as e:
2555 2555 self._edit_macro(args, e.args[0])
2556 2556 return
2557 2557
2558 2558 # do actual editing here
2559 2559 print 'Editing...',
2560 2560 sys.stdout.flush()
2561 2561 try:
2562 2562 # Quote filenames that may have spaces in them
2563 2563 if ' ' in filename:
2564 2564 filename = "'%s'" % filename
2565 2565 self.shell.hooks.editor(filename,lineno)
2566 2566 except TryNext:
2567 2567 warn('Could not open editor')
2568 2568 return
2569 2569
2570 2570 # XXX TODO: should this be generalized for all string vars?
2571 2571 # For now, this is special-cased to blocks created by cpaste
2572 2572 if args.strip() == 'pasted_block':
2573 2573 self.shell.user_ns['pasted_block'] = file_read(filename)
2574 2574
2575 2575 if 'x' in opts: # -x prevents actual execution
2576 2576 print
2577 2577 else:
2578 2578 print 'done. Executing edited code...'
2579 2579 if 'r' in opts: # Untranslated IPython code
2580 2580 self.shell.run_cell(file_read(filename),
2581 2581 store_history=False)
2582 2582 else:
2583 2583 self.shell.safe_execfile(filename,self.shell.user_ns,
2584 2584 self.shell.user_ns)
2585 2585
2586 2586 if is_temp:
2587 2587 try:
2588 2588 return open(filename).read()
2589 2589 except IOError,msg:
2590 2590 if msg.filename == filename:
2591 2591 warn('File not found. Did you forget to save?')
2592 2592 return
2593 2593 else:
2594 2594 self.shell.showtraceback()
2595 2595
2596 2596 def magic_xmode(self,parameter_s = ''):
2597 2597 """Switch modes for the exception handlers.
2598 2598
2599 2599 Valid modes: Plain, Context and Verbose.
2600 2600
2601 2601 If called without arguments, acts as a toggle."""
2602 2602
2603 2603 def xmode_switch_err(name):
2604 2604 warn('Error changing %s exception modes.\n%s' %
2605 2605 (name,sys.exc_info()[1]))
2606 2606
2607 2607 shell = self.shell
2608 2608 new_mode = parameter_s.strip().capitalize()
2609 2609 try:
2610 2610 shell.InteractiveTB.set_mode(mode=new_mode)
2611 2611 print 'Exception reporting mode:',shell.InteractiveTB.mode
2612 2612 except:
2613 2613 xmode_switch_err('user')
2614 2614
2615 2615 def magic_colors(self,parameter_s = ''):
2616 2616 """Switch color scheme for prompts, info system and exception handlers.
2617 2617
2618 2618 Currently implemented schemes: NoColor, Linux, LightBG.
2619 2619
2620 2620 Color scheme names are not case-sensitive.
2621 2621
2622 2622 Examples
2623 2623 --------
2624 2624 To get a plain black and white terminal::
2625 2625
2626 2626 %colors nocolor
2627 2627 """
2628 2628
2629 2629 def color_switch_err(name):
2630 2630 warn('Error changing %s color schemes.\n%s' %
2631 2631 (name,sys.exc_info()[1]))
2632 2632
2633 2633
2634 2634 new_scheme = parameter_s.strip()
2635 2635 if not new_scheme:
2636 2636 raise UsageError(
2637 2637 "%colors: you must specify a color scheme. See '%colors?'")
2638 2638 return
2639 2639 # local shortcut
2640 2640 shell = self.shell
2641 2641
2642 2642 import IPython.utils.rlineimpl as readline
2643 2643
2644 2644 if not shell.colors_force and \
2645 2645 not readline.have_readline and sys.platform == "win32":
2646 2646 msg = """\
2647 2647 Proper color support under MS Windows requires the pyreadline library.
2648 2648 You can find it at:
2649 2649 http://ipython.org/pyreadline.html
2650 2650 Gary's readline needs the ctypes module, from:
2651 2651 http://starship.python.net/crew/theller/ctypes
2652 2652 (Note that ctypes is already part of Python versions 2.5 and newer).
2653 2653
2654 2654 Defaulting color scheme to 'NoColor'"""
2655 2655 new_scheme = 'NoColor'
2656 2656 warn(msg)
2657 2657
2658 2658 # readline option is 0
2659 2659 if not shell.colors_force and not shell.has_readline:
2660 2660 new_scheme = 'NoColor'
2661 2661
2662 2662 # Set prompt colors
2663 2663 try:
2664 2664 shell.prompt_manager.color_scheme = new_scheme
2665 2665 except:
2666 2666 color_switch_err('prompt')
2667 2667 else:
2668 2668 shell.colors = \
2669 2669 shell.prompt_manager.color_scheme_table.active_scheme_name
2670 2670 # Set exception colors
2671 2671 try:
2672 2672 shell.InteractiveTB.set_colors(scheme = new_scheme)
2673 2673 shell.SyntaxTB.set_colors(scheme = new_scheme)
2674 2674 except:
2675 2675 color_switch_err('exception')
2676 2676
2677 2677 # Set info (for 'object?') colors
2678 2678 if shell.color_info:
2679 2679 try:
2680 2680 shell.inspector.set_active_scheme(new_scheme)
2681 2681 except:
2682 2682 color_switch_err('object inspector')
2683 2683 else:
2684 2684 shell.inspector.set_active_scheme('NoColor')
2685 2685
2686 2686 def magic_pprint(self, parameter_s=''):
2687 2687 """Toggle pretty printing on/off."""
2688 2688 ptformatter = self.shell.display_formatter.formatters['text/plain']
2689 2689 ptformatter.pprint = bool(1 - ptformatter.pprint)
2690 2690 print 'Pretty printing has been turned', \
2691 2691 ['OFF','ON'][ptformatter.pprint]
2692 2692
2693 2693 #......................................................................
2694 2694 # Functions to implement unix shell-type things
2695 2695
2696 2696 @skip_doctest
2697 2697 def magic_alias(self, parameter_s = ''):
2698 2698 """Define an alias for a system command.
2699 2699
2700 2700 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2701 2701
2702 2702 Then, typing 'alias_name params' will execute the system command 'cmd
2703 2703 params' (from your underlying operating system).
2704 2704
2705 2705 Aliases have lower precedence than magic functions and Python normal
2706 2706 variables, so if 'foo' is both a Python variable and an alias, the
2707 2707 alias can not be executed until 'del foo' removes the Python variable.
2708 2708
2709 2709 You can use the %l specifier in an alias definition to represent the
2710 2710 whole line when the alias is called. For example::
2711 2711
2712 2712 In [2]: alias bracket echo "Input in brackets: <%l>"
2713 2713 In [3]: bracket hello world
2714 2714 Input in brackets: <hello world>
2715 2715
2716 2716 You can also define aliases with parameters using %s specifiers (one
2717 2717 per parameter)::
2718 2718
2719 2719 In [1]: alias parts echo first %s second %s
2720 2720 In [2]: %parts A B
2721 2721 first A second B
2722 2722 In [3]: %parts A
2723 2723 Incorrect number of arguments: 2 expected.
2724 2724 parts is an alias to: 'echo first %s second %s'
2725 2725
2726 2726 Note that %l and %s are mutually exclusive. You can only use one or
2727 2727 the other in your aliases.
2728 2728
2729 2729 Aliases expand Python variables just like system calls using ! or !!
2730 2730 do: all expressions prefixed with '$' get expanded. For details of
2731 2731 the semantic rules, see PEP-215:
2732 2732 http://www.python.org/peps/pep-0215.html. This is the library used by
2733 2733 IPython for variable expansion. If you want to access a true shell
2734 2734 variable, an extra $ is necessary to prevent its expansion by
2735 2735 IPython::
2736 2736
2737 2737 In [6]: alias show echo
2738 2738 In [7]: PATH='A Python string'
2739 2739 In [8]: show $PATH
2740 2740 A Python string
2741 2741 In [9]: show $$PATH
2742 2742 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2743 2743
2744 2744 You can use the alias facility to acess all of $PATH. See the %rehash
2745 2745 and %rehashx functions, which automatically create aliases for the
2746 2746 contents of your $PATH.
2747 2747
2748 2748 If called with no parameters, %alias prints the current alias table."""
2749 2749
2750 2750 par = parameter_s.strip()
2751 2751 if not par:
2752 2752 stored = self.db.get('stored_aliases', {} )
2753 2753 aliases = sorted(self.shell.alias_manager.aliases)
2754 2754 # for k, v in stored:
2755 2755 # atab.append(k, v[0])
2756 2756
2757 2757 print "Total number of aliases:", len(aliases)
2758 2758 sys.stdout.flush()
2759 2759 return aliases
2760 2760
2761 2761 # Now try to define a new one
2762 2762 try:
2763 2763 alias,cmd = par.split(None, 1)
2764 2764 except:
2765 2765 print oinspect.getdoc(self.magic_alias)
2766 2766 else:
2767 2767 self.shell.alias_manager.soft_define_alias(alias, cmd)
2768 2768 # end magic_alias
2769 2769
2770 2770 def magic_unalias(self, parameter_s = ''):
2771 2771 """Remove an alias"""
2772 2772
2773 2773 aname = parameter_s.strip()
2774 2774 self.shell.alias_manager.undefine_alias(aname)
2775 2775 stored = self.db.get('stored_aliases', {} )
2776 2776 if aname in stored:
2777 2777 print "Removing %stored alias",aname
2778 2778 del stored[aname]
2779 2779 self.db['stored_aliases'] = stored
2780 2780
2781 2781 def magic_rehashx(self, parameter_s = ''):
2782 2782 """Update the alias table with all executable files in $PATH.
2783 2783
2784 2784 This version explicitly checks that every entry in $PATH is a file
2785 2785 with execute access (os.X_OK), so it is much slower than %rehash.
2786 2786
2787 2787 Under Windows, it checks executability as a match against a
2788 2788 '|'-separated string of extensions, stored in the IPython config
2789 2789 variable win_exec_ext. This defaults to 'exe|com|bat'.
2790 2790
2791 2791 This function also resets the root module cache of module completer,
2792 2792 used on slow filesystems.
2793 2793 """
2794 2794 from IPython.core.alias import InvalidAliasError
2795 2795
2796 2796 # for the benefit of module completer in ipy_completers.py
2797 2797 del self.shell.db['rootmodules']
2798 2798
2799 2799 path = [os.path.abspath(os.path.expanduser(p)) for p in
2800 2800 os.environ.get('PATH','').split(os.pathsep)]
2801 2801 path = filter(os.path.isdir,path)
2802 2802
2803 2803 syscmdlist = []
2804 2804 # Now define isexec in a cross platform manner.
2805 2805 if os.name == 'posix':
2806 2806 isexec = lambda fname:os.path.isfile(fname) and \
2807 2807 os.access(fname,os.X_OK)
2808 2808 else:
2809 2809 try:
2810 2810 winext = os.environ['pathext'].replace(';','|').replace('.','')
2811 2811 except KeyError:
2812 2812 winext = 'exe|com|bat|py'
2813 2813 if 'py' not in winext:
2814 2814 winext += '|py'
2815 2815 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2816 2816 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2817 2817 savedir = os.getcwdu()
2818 2818
2819 2819 # Now walk the paths looking for executables to alias.
2820 2820 try:
2821 2821 # write the whole loop for posix/Windows so we don't have an if in
2822 2822 # the innermost part
2823 2823 if os.name == 'posix':
2824 2824 for pdir in path:
2825 2825 os.chdir(pdir)
2826 2826 for ff in os.listdir(pdir):
2827 2827 if isexec(ff):
2828 2828 try:
2829 2829 # Removes dots from the name since ipython
2830 2830 # will assume names with dots to be python.
2831 2831 self.shell.alias_manager.define_alias(
2832 2832 ff.replace('.',''), ff)
2833 2833 except InvalidAliasError:
2834 2834 pass
2835 2835 else:
2836 2836 syscmdlist.append(ff)
2837 2837 else:
2838 2838 no_alias = self.shell.alias_manager.no_alias
2839 2839 for pdir in path:
2840 2840 os.chdir(pdir)
2841 2841 for ff in os.listdir(pdir):
2842 2842 base, ext = os.path.splitext(ff)
2843 2843 if isexec(ff) and base.lower() not in no_alias:
2844 2844 if ext.lower() == '.exe':
2845 2845 ff = base
2846 2846 try:
2847 2847 # Removes dots from the name since ipython
2848 2848 # will assume names with dots to be python.
2849 2849 self.shell.alias_manager.define_alias(
2850 2850 base.lower().replace('.',''), ff)
2851 2851 except InvalidAliasError:
2852 2852 pass
2853 2853 syscmdlist.append(ff)
2854 2854 self.shell.db['syscmdlist'] = syscmdlist
2855 2855 finally:
2856 2856 os.chdir(savedir)
2857 2857
2858 2858 @skip_doctest
2859 2859 def magic_pwd(self, parameter_s = ''):
2860 2860 """Return the current working directory path.
2861 2861
2862 2862 Examples
2863 2863 --------
2864 2864 ::
2865 2865
2866 2866 In [9]: pwd
2867 2867 Out[9]: '/home/tsuser/sprint/ipython'
2868 2868 """
2869 2869 return os.getcwdu()
2870 2870
2871 2871 @skip_doctest
2872 2872 def magic_cd(self, parameter_s=''):
2873 2873 """Change the current working directory.
2874 2874
2875 2875 This command automatically maintains an internal list of directories
2876 2876 you visit during your IPython session, in the variable _dh. The
2877 2877 command %dhist shows this history nicely formatted. You can also
2878 2878 do 'cd -<tab>' to see directory history conveniently.
2879 2879
2880 2880 Usage:
2881 2881
2882 2882 cd 'dir': changes to directory 'dir'.
2883 2883
2884 2884 cd -: changes to the last visited directory.
2885 2885
2886 2886 cd -<n>: changes to the n-th directory in the directory history.
2887 2887
2888 2888 cd --foo: change to directory that matches 'foo' in history
2889 2889
2890 2890 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2891 2891 (note: cd <bookmark_name> is enough if there is no
2892 2892 directory <bookmark_name>, but a bookmark with the name exists.)
2893 2893 'cd -b <tab>' allows you to tab-complete bookmark names.
2894 2894
2895 2895 Options:
2896 2896
2897 2897 -q: quiet. Do not print the working directory after the cd command is
2898 2898 executed. By default IPython's cd command does print this directory,
2899 2899 since the default prompts do not display path information.
2900 2900
2901 2901 Note that !cd doesn't work for this purpose because the shell where
2902 2902 !command runs is immediately discarded after executing 'command'.
2903 2903
2904 2904 Examples
2905 2905 --------
2906 2906 ::
2907 2907
2908 2908 In [10]: cd parent/child
2909 2909 /home/tsuser/parent/child
2910 2910 """
2911 2911
2912 2912 parameter_s = parameter_s.strip()
2913 2913 #bkms = self.shell.persist.get("bookmarks",{})
2914 2914
2915 2915 oldcwd = os.getcwdu()
2916 2916 numcd = re.match(r'(-)(\d+)$',parameter_s)
2917 2917 # jump in directory history by number
2918 2918 if numcd:
2919 2919 nn = int(numcd.group(2))
2920 2920 try:
2921 2921 ps = self.shell.user_ns['_dh'][nn]
2922 2922 except IndexError:
2923 2923 print 'The requested directory does not exist in history.'
2924 2924 return
2925 2925 else:
2926 2926 opts = {}
2927 2927 elif parameter_s.startswith('--'):
2928 2928 ps = None
2929 2929 fallback = None
2930 2930 pat = parameter_s[2:]
2931 2931 dh = self.shell.user_ns['_dh']
2932 2932 # first search only by basename (last component)
2933 2933 for ent in reversed(dh):
2934 2934 if pat in os.path.basename(ent) and os.path.isdir(ent):
2935 2935 ps = ent
2936 2936 break
2937 2937
2938 2938 if fallback is None and pat in ent and os.path.isdir(ent):
2939 2939 fallback = ent
2940 2940
2941 2941 # if we have no last part match, pick the first full path match
2942 2942 if ps is None:
2943 2943 ps = fallback
2944 2944
2945 2945 if ps is None:
2946 2946 print "No matching entry in directory history"
2947 2947 return
2948 2948 else:
2949 2949 opts = {}
2950 2950
2951 2951
2952 2952 else:
2953 2953 #turn all non-space-escaping backslashes to slashes,
2954 2954 # for c:\windows\directory\names\
2955 2955 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2956 2956 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2957 2957 # jump to previous
2958 2958 if ps == '-':
2959 2959 try:
2960 2960 ps = self.shell.user_ns['_dh'][-2]
2961 2961 except IndexError:
2962 2962 raise UsageError('%cd -: No previous directory to change to.')
2963 2963 # jump to bookmark if needed
2964 2964 else:
2965 2965 if not os.path.isdir(ps) or opts.has_key('b'):
2966 2966 bkms = self.db.get('bookmarks', {})
2967 2967
2968 2968 if bkms.has_key(ps):
2969 2969 target = bkms[ps]
2970 2970 print '(bookmark:%s) -> %s' % (ps,target)
2971 2971 ps = target
2972 2972 else:
2973 2973 if opts.has_key('b'):
2974 2974 raise UsageError("Bookmark '%s' not found. "
2975 2975 "Use '%%bookmark -l' to see your bookmarks." % ps)
2976 2976
2977 2977 # strip extra quotes on Windows, because os.chdir doesn't like them
2978 2978 ps = unquote_filename(ps)
2979 2979 # at this point ps should point to the target dir
2980 2980 if ps:
2981 2981 try:
2982 2982 os.chdir(os.path.expanduser(ps))
2983 2983 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2984 2984 set_term_title('IPython: ' + abbrev_cwd())
2985 2985 except OSError:
2986 2986 print sys.exc_info()[1]
2987 2987 else:
2988 2988 cwd = os.getcwdu()
2989 2989 dhist = self.shell.user_ns['_dh']
2990 2990 if oldcwd != cwd:
2991 2991 dhist.append(cwd)
2992 2992 self.db['dhist'] = compress_dhist(dhist)[-100:]
2993 2993
2994 2994 else:
2995 2995 os.chdir(self.shell.home_dir)
2996 2996 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2997 2997 set_term_title('IPython: ' + '~')
2998 2998 cwd = os.getcwdu()
2999 2999 dhist = self.shell.user_ns['_dh']
3000 3000
3001 3001 if oldcwd != cwd:
3002 3002 dhist.append(cwd)
3003 3003 self.db['dhist'] = compress_dhist(dhist)[-100:]
3004 3004 if not 'q' in opts and self.shell.user_ns['_dh']:
3005 3005 print self.shell.user_ns['_dh'][-1]
3006 3006
3007 3007
3008 3008 def magic_env(self, parameter_s=''):
3009 3009 """List environment variables."""
3010 3010
3011 3011 return dict(os.environ)
3012 3012
3013 3013 def magic_pushd(self, parameter_s=''):
3014 3014 """Place the current dir on stack and change directory.
3015 3015
3016 3016 Usage:\\
3017 3017 %pushd ['dirname']
3018 3018 """
3019 3019
3020 3020 dir_s = self.shell.dir_stack
3021 3021 tgt = os.path.expanduser(unquote_filename(parameter_s))
3022 3022 cwd = os.getcwdu().replace(self.home_dir,'~')
3023 3023 if tgt:
3024 3024 self.magic_cd(parameter_s)
3025 3025 dir_s.insert(0,cwd)
3026 3026 return self.magic_dirs()
3027 3027
3028 3028 def magic_popd(self, parameter_s=''):
3029 3029 """Change to directory popped off the top of the stack.
3030 3030 """
3031 3031 if not self.shell.dir_stack:
3032 3032 raise UsageError("%popd on empty stack")
3033 3033 top = self.shell.dir_stack.pop(0)
3034 3034 self.magic_cd(top)
3035 3035 print "popd ->",top
3036 3036
3037 3037 def magic_dirs(self, parameter_s=''):
3038 3038 """Return the current directory stack."""
3039 3039
3040 3040 return self.shell.dir_stack
3041 3041
3042 3042 def magic_dhist(self, parameter_s=''):
3043 3043 """Print your history of visited directories.
3044 3044
3045 3045 %dhist -> print full history\\
3046 3046 %dhist n -> print last n entries only\\
3047 3047 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
3048 3048
3049 3049 This history is automatically maintained by the %cd command, and
3050 3050 always available as the global list variable _dh. You can use %cd -<n>
3051 3051 to go to directory number <n>.
3052 3052
3053 3053 Note that most of time, you should view directory history by entering
3054 3054 cd -<TAB>.
3055 3055
3056 3056 """
3057 3057
3058 3058 dh = self.shell.user_ns['_dh']
3059 3059 if parameter_s:
3060 3060 try:
3061 3061 args = map(int,parameter_s.split())
3062 3062 except:
3063 3063 self.arg_err(Magic.magic_dhist)
3064 3064 return
3065 3065 if len(args) == 1:
3066 3066 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3067 3067 elif len(args) == 2:
3068 3068 ini,fin = args
3069 3069 else:
3070 3070 self.arg_err(Magic.magic_dhist)
3071 3071 return
3072 3072 else:
3073 3073 ini,fin = 0,len(dh)
3074 3074 nlprint(dh,
3075 3075 header = 'Directory history (kept in _dh)',
3076 3076 start=ini,stop=fin)
3077 3077
3078 3078 @skip_doctest
3079 3079 def magic_sc(self, parameter_s=''):
3080 3080 """Shell capture - execute a shell command and capture its output.
3081 3081
3082 3082 DEPRECATED. Suboptimal, retained for backwards compatibility.
3083 3083
3084 3084 You should use the form 'var = !command' instead. Example:
3085 3085
3086 3086 "%sc -l myfiles = ls ~" should now be written as
3087 3087
3088 3088 "myfiles = !ls ~"
3089 3089
3090 3090 myfiles.s, myfiles.l and myfiles.n still apply as documented
3091 3091 below.
3092 3092
3093 3093 --
3094 3094 %sc [options] varname=command
3095 3095
3096 3096 IPython will run the given command using commands.getoutput(), and
3097 3097 will then update the user's interactive namespace with a variable
3098 3098 called varname, containing the value of the call. Your command can
3099 3099 contain shell wildcards, pipes, etc.
3100 3100
3101 3101 The '=' sign in the syntax is mandatory, and the variable name you
3102 3102 supply must follow Python's standard conventions for valid names.
3103 3103
3104 3104 (A special format without variable name exists for internal use)
3105 3105
3106 3106 Options:
3107 3107
3108 3108 -l: list output. Split the output on newlines into a list before
3109 3109 assigning it to the given variable. By default the output is stored
3110 3110 as a single string.
3111 3111
3112 3112 -v: verbose. Print the contents of the variable.
3113 3113
3114 3114 In most cases you should not need to split as a list, because the
3115 3115 returned value is a special type of string which can automatically
3116 3116 provide its contents either as a list (split on newlines) or as a
3117 3117 space-separated string. These are convenient, respectively, either
3118 3118 for sequential processing or to be passed to a shell command.
3119 3119
3120 3120 For example::
3121 3121
3122 3122 # Capture into variable a
3123 3123 In [1]: sc a=ls *py
3124 3124
3125 3125 # a is a string with embedded newlines
3126 3126 In [2]: a
3127 3127 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3128 3128
3129 3129 # which can be seen as a list:
3130 3130 In [3]: a.l
3131 3131 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3132 3132
3133 3133 # or as a whitespace-separated string:
3134 3134 In [4]: a.s
3135 3135 Out[4]: 'setup.py win32_manual_post_install.py'
3136 3136
3137 3137 # a.s is useful to pass as a single command line:
3138 3138 In [5]: !wc -l $a.s
3139 3139 146 setup.py
3140 3140 130 win32_manual_post_install.py
3141 3141 276 total
3142 3142
3143 3143 # while the list form is useful to loop over:
3144 3144 In [6]: for f in a.l:
3145 3145 ...: !wc -l $f
3146 3146 ...:
3147 3147 146 setup.py
3148 3148 130 win32_manual_post_install.py
3149 3149
3150 3150 Similarly, the lists returned by the -l option are also special, in
3151 3151 the sense that you can equally invoke the .s attribute on them to
3152 3152 automatically get a whitespace-separated string from their contents::
3153 3153
3154 3154 In [7]: sc -l b=ls *py
3155 3155
3156 3156 In [8]: b
3157 3157 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3158 3158
3159 3159 In [9]: b.s
3160 3160 Out[9]: 'setup.py win32_manual_post_install.py'
3161 3161
3162 3162 In summary, both the lists and strings used for output capture have
3163 3163 the following special attributes::
3164 3164
3165 3165 .l (or .list) : value as list.
3166 3166 .n (or .nlstr): value as newline-separated string.
3167 3167 .s (or .spstr): value as space-separated string.
3168 3168 """
3169 3169
3170 3170 opts,args = self.parse_options(parameter_s,'lv')
3171 3171 # Try to get a variable name and command to run
3172 3172 try:
3173 3173 # the variable name must be obtained from the parse_options
3174 3174 # output, which uses shlex.split to strip options out.
3175 3175 var,_ = args.split('=',1)
3176 3176 var = var.strip()
3177 3177 # But the command has to be extracted from the original input
3178 3178 # parameter_s, not on what parse_options returns, to avoid the
3179 3179 # quote stripping which shlex.split performs on it.
3180 3180 _,cmd = parameter_s.split('=',1)
3181 3181 except ValueError:
3182 3182 var,cmd = '',''
3183 3183 # If all looks ok, proceed
3184 3184 split = 'l' in opts
3185 3185 out = self.shell.getoutput(cmd, split=split)
3186 3186 if opts.has_key('v'):
3187 3187 print '%s ==\n%s' % (var,pformat(out))
3188 3188 if var:
3189 3189 self.shell.user_ns.update({var:out})
3190 3190 else:
3191 3191 return out
3192 3192
3193 3193 def magic_sx(self, parameter_s=''):
3194 3194 """Shell execute - run a shell command and capture its output.
3195 3195
3196 3196 %sx command
3197 3197
3198 3198 IPython will run the given command using commands.getoutput(), and
3199 3199 return the result formatted as a list (split on '\\n'). Since the
3200 3200 output is _returned_, it will be stored in ipython's regular output
3201 3201 cache Out[N] and in the '_N' automatic variables.
3202 3202
3203 3203 Notes:
3204 3204
3205 3205 1) If an input line begins with '!!', then %sx is automatically
3206 3206 invoked. That is, while::
3207 3207
3208 3208 !ls
3209 3209
3210 3210 causes ipython to simply issue system('ls'), typing::
3211 3211
3212 3212 !!ls
3213 3213
3214 3214 is a shorthand equivalent to::
3215 3215
3216 3216 %sx ls
3217 3217
3218 3218 2) %sx differs from %sc in that %sx automatically splits into a list,
3219 3219 like '%sc -l'. The reason for this is to make it as easy as possible
3220 3220 to process line-oriented shell output via further python commands.
3221 3221 %sc is meant to provide much finer control, but requires more
3222 3222 typing.
3223 3223
3224 3224 3) Just like %sc -l, this is a list with special attributes:
3225 3225 ::
3226 3226
3227 3227 .l (or .list) : value as list.
3228 3228 .n (or .nlstr): value as newline-separated string.
3229 3229 .s (or .spstr): value as whitespace-separated string.
3230 3230
3231 3231 This is very useful when trying to use such lists as arguments to
3232 3232 system commands."""
3233 3233
3234 3234 if parameter_s:
3235 3235 return self.shell.getoutput(parameter_s)
3236 3236
3237 3237
3238 3238 def magic_bookmark(self, parameter_s=''):
3239 3239 """Manage IPython's bookmark system.
3240 3240
3241 3241 %bookmark <name> - set bookmark to current dir
3242 3242 %bookmark <name> <dir> - set bookmark to <dir>
3243 3243 %bookmark -l - list all bookmarks
3244 3244 %bookmark -d <name> - remove bookmark
3245 3245 %bookmark -r - remove all bookmarks
3246 3246
3247 3247 You can later on access a bookmarked folder with::
3248 3248
3249 3249 %cd -b <name>
3250 3250
3251 3251 or simply '%cd <name>' if there is no directory called <name> AND
3252 3252 there is such a bookmark defined.
3253 3253
3254 3254 Your bookmarks persist through IPython sessions, but they are
3255 3255 associated with each profile."""
3256 3256
3257 3257 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3258 3258 if len(args) > 2:
3259 3259 raise UsageError("%bookmark: too many arguments")
3260 3260
3261 3261 bkms = self.db.get('bookmarks',{})
3262 3262
3263 3263 if opts.has_key('d'):
3264 3264 try:
3265 3265 todel = args[0]
3266 3266 except IndexError:
3267 3267 raise UsageError(
3268 3268 "%bookmark -d: must provide a bookmark to delete")
3269 3269 else:
3270 3270 try:
3271 3271 del bkms[todel]
3272 3272 except KeyError:
3273 3273 raise UsageError(
3274 3274 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3275 3275
3276 3276 elif opts.has_key('r'):
3277 3277 bkms = {}
3278 3278 elif opts.has_key('l'):
3279 3279 bks = bkms.keys()
3280 3280 bks.sort()
3281 3281 if bks:
3282 3282 size = max(map(len,bks))
3283 3283 else:
3284 3284 size = 0
3285 3285 fmt = '%-'+str(size)+'s -> %s'
3286 3286 print 'Current bookmarks:'
3287 3287 for bk in bks:
3288 3288 print fmt % (bk,bkms[bk])
3289 3289 else:
3290 3290 if not args:
3291 3291 raise UsageError("%bookmark: You must specify the bookmark name")
3292 3292 elif len(args)==1:
3293 3293 bkms[args[0]] = os.getcwdu()
3294 3294 elif len(args)==2:
3295 3295 bkms[args[0]] = args[1]
3296 3296 self.db['bookmarks'] = bkms
3297 3297
3298 3298 def magic_pycat(self, parameter_s=''):
3299 3299 """Show a syntax-highlighted file through a pager.
3300 3300
3301 3301 This magic is similar to the cat utility, but it will assume the file
3302 3302 to be Python source and will show it with syntax highlighting. """
3303 3303
3304 3304 try:
3305 3305 filename = get_py_filename(parameter_s)
3306 3306 cont = file_read(filename)
3307 3307 except IOError:
3308 3308 try:
3309 3309 cont = eval(parameter_s,self.user_ns)
3310 3310 except NameError:
3311 3311 cont = None
3312 3312 if cont is None:
3313 3313 print "Error: no such file or variable"
3314 3314 return
3315 3315
3316 3316 page.page(self.shell.pycolorize(cont))
3317 3317
3318 3318 def magic_quickref(self,arg):
3319 3319 """ Show a quick reference sheet """
3320 3320 import IPython.core.usage
3321 3321 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3322 3322
3323 3323 page.page(qr)
3324 3324
3325 3325 def magic_doctest_mode(self,parameter_s=''):
3326 3326 """Toggle doctest mode on and off.
3327 3327
3328 3328 This mode is intended to make IPython behave as much as possible like a
3329 3329 plain Python shell, from the perspective of how its prompts, exceptions
3330 3330 and output look. This makes it easy to copy and paste parts of a
3331 3331 session into doctests. It does so by:
3332 3332
3333 3333 - Changing the prompts to the classic ``>>>`` ones.
3334 3334 - Changing the exception reporting mode to 'Plain'.
3335 3335 - Disabling pretty-printing of output.
3336 3336
3337 3337 Note that IPython also supports the pasting of code snippets that have
3338 3338 leading '>>>' and '...' prompts in them. This means that you can paste
3339 3339 doctests from files or docstrings (even if they have leading
3340 3340 whitespace), and the code will execute correctly. You can then use
3341 3341 '%history -t' to see the translated history; this will give you the
3342 3342 input after removal of all the leading prompts and whitespace, which
3343 3343 can be pasted back into an editor.
3344 3344
3345 3345 With these features, you can switch into this mode easily whenever you
3346 3346 need to do testing and changes to doctests, without having to leave
3347 3347 your existing IPython session.
3348 3348 """
3349 3349
3350 3350 from IPython.utils.ipstruct import Struct
3351 3351
3352 3352 # Shorthands
3353 3353 shell = self.shell
3354 3354 pm = shell.prompt_manager
3355 3355 meta = shell.meta
3356 3356 disp_formatter = self.shell.display_formatter
3357 3357 ptformatter = disp_formatter.formatters['text/plain']
3358 3358 # dstore is a data store kept in the instance metadata bag to track any
3359 3359 # changes we make, so we can undo them later.
3360 3360 dstore = meta.setdefault('doctest_mode',Struct())
3361 3361 save_dstore = dstore.setdefault
3362 3362
3363 3363 # save a few values we'll need to recover later
3364 3364 mode = save_dstore('mode',False)
3365 3365 save_dstore('rc_pprint',ptformatter.pprint)
3366 3366 save_dstore('xmode',shell.InteractiveTB.mode)
3367 3367 save_dstore('rc_separate_out',shell.separate_out)
3368 3368 save_dstore('rc_separate_out2',shell.separate_out2)
3369 3369 save_dstore('rc_prompts_pad_left',pm.justify)
3370 3370 save_dstore('rc_separate_in',shell.separate_in)
3371 3371 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3372 3372 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
3373 3373
3374 3374 if mode == False:
3375 3375 # turn on
3376 3376 pm.in_template = '>>> '
3377 3377 pm.in2_template = '... '
3378 3378 pm.out_template = ''
3379 3379
3380 3380 # Prompt separators like plain python
3381 3381 shell.separate_in = ''
3382 3382 shell.separate_out = ''
3383 3383 shell.separate_out2 = ''
3384 3384
3385 3385 pm.justify = False
3386 3386
3387 3387 ptformatter.pprint = False
3388 3388 disp_formatter.plain_text_only = True
3389 3389
3390 3390 shell.magic_xmode('Plain')
3391 3391 else:
3392 3392 # turn off
3393 3393 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
3394 3394
3395 3395 shell.separate_in = dstore.rc_separate_in
3396 3396
3397 3397 shell.separate_out = dstore.rc_separate_out
3398 3398 shell.separate_out2 = dstore.rc_separate_out2
3399 3399
3400 3400 pm.justify = dstore.rc_prompts_pad_left
3401 3401
3402 3402 ptformatter.pprint = dstore.rc_pprint
3403 3403 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3404 3404
3405 3405 shell.magic_xmode(dstore.xmode)
3406 3406
3407 3407 # Store new mode and inform
3408 3408 dstore.mode = bool(1-int(mode))
3409 3409 mode_label = ['OFF','ON'][dstore.mode]
3410 3410 print 'Doctest mode is:', mode_label
3411 3411
3412 3412 def magic_gui(self, parameter_s=''):
3413 3413 """Enable or disable IPython GUI event loop integration.
3414 3414
3415 3415 %gui [GUINAME]
3416 3416
3417 3417 This magic replaces IPython's threaded shells that were activated
3418 3418 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3419 3419 can now be enabled at runtime and keyboard
3420 3420 interrupts should work without any problems. The following toolkits
3421 3421 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
3422 3422
3423 3423 %gui wx # enable wxPython event loop integration
3424 3424 %gui qt4|qt # enable PyQt4 event loop integration
3425 3425 %gui gtk # enable PyGTK event loop integration
3426 3426 %gui gtk3 # enable Gtk3 event loop integration
3427 3427 %gui tk # enable Tk event loop integration
3428 3428 %gui OSX # enable Cocoa event loop integration
3429 3429 # (requires %matplotlib 1.1)
3430 3430 %gui # disable all event loop integration
3431 3431
3432 3432 WARNING: after any of these has been called you can simply create
3433 3433 an application object, but DO NOT start the event loop yourself, as
3434 3434 we have already handled that.
3435 3435 """
3436 3436 opts, arg = self.parse_options(parameter_s, '')
3437 3437 if arg=='': arg = None
3438 3438 try:
3439 3439 return self.enable_gui(arg)
3440 3440 except Exception as e:
3441 3441 # print simple error message, rather than traceback if we can't
3442 3442 # hook up the GUI
3443 3443 error(str(e))
3444 3444
3445 3445 def magic_install_ext(self, parameter_s):
3446 3446 """Download and install an extension from a URL, e.g.::
3447 3447
3448 3448 %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py
3449 3449
3450 3450 The URL should point to an importable Python module - either a .py file
3451 3451 or a .zip file.
3452 3452
3453 3453 Parameters:
3454 3454
3455 3455 -n filename : Specify a name for the file, rather than taking it from
3456 3456 the URL.
3457 3457 """
3458 3458 opts, args = self.parse_options(parameter_s, 'n:')
3459 3459 try:
3460 3460 filename = self.extension_manager.install_extension(args, opts.get('n'))
3461 3461 except ValueError as e:
3462 3462 print e
3463 3463 return
3464 3464
3465 3465 filename = os.path.basename(filename)
3466 3466 print "Installed %s. To use it, type:" % filename
3467 3467 print " %%load_ext %s" % os.path.splitext(filename)[0]
3468 3468
3469 3469
3470 3470 def magic_load_ext(self, module_str):
3471 3471 """Load an IPython extension by its module name."""
3472 3472 return self.extension_manager.load_extension(module_str)
3473 3473
3474 3474 def magic_unload_ext(self, module_str):
3475 3475 """Unload an IPython extension by its module name."""
3476 3476 self.extension_manager.unload_extension(module_str)
3477 3477
3478 3478 def magic_reload_ext(self, module_str):
3479 3479 """Reload an IPython extension by its module name."""
3480 3480 self.extension_manager.reload_extension(module_str)
3481 3481
3482 3482 def magic_install_profiles(self, s):
3483 3483 """%install_profiles has been deprecated."""
3484 3484 print '\n'.join([
3485 3485 "%install_profiles has been deprecated.",
3486 3486 "Use `ipython profile list` to view available profiles.",
3487 3487 "Requesting a profile with `ipython profile create <name>`",
3488 3488 "or `ipython --profile=<name>` will start with the bundled",
3489 3489 "profile of that name if it exists."
3490 3490 ])
3491 3491
3492 3492 def magic_install_default_config(self, s):
3493 3493 """%install_default_config has been deprecated."""
3494 3494 print '\n'.join([
3495 3495 "%install_default_config has been deprecated.",
3496 3496 "Use `ipython profile create <name>` to initialize a profile",
3497 3497 "with the default config files.",
3498 3498 "Add `--reset` to overwrite already existing config files with defaults."
3499 3499 ])
3500 3500
3501 3501 # Pylab support: simple wrappers that activate pylab, load gui input
3502 3502 # handling and modify slightly %run
3503 3503
3504 3504 @skip_doctest
3505 3505 def _pylab_magic_run(self, parameter_s=''):
3506 3506 Magic.magic_run(self, parameter_s,
3507 3507 runner=mpl_runner(self.shell.safe_execfile))
3508 3508
3509 3509 _pylab_magic_run.__doc__ = magic_run.__doc__
3510 3510
3511 3511 @skip_doctest
3512 3512 def magic_pylab(self, s):
3513 3513 """Load numpy and matplotlib to work interactively.
3514 3514
3515 3515 %pylab [GUINAME]
3516 3516
3517 3517 This function lets you activate pylab (matplotlib, numpy and
3518 3518 interactive support) at any point during an IPython session.
3519 3519
3520 3520 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3521 3521 pylab and mlab, as well as all names from numpy and pylab.
3522 3522
3523 3523 If you are using the inline matplotlib backend for embedded figures,
3524 3524 you can adjust its behavior via the %config magic::
3525 3525
3526 3526 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3527 3527 In [1]: %config InlineBackend.figure_format = 'svg'
3528 3528
3529 3529 # change the behavior of closing all figures at the end of each
3530 3530 # execution (cell), or allowing reuse of active figures across
3531 3531 # cells:
3532 3532 In [2]: %config InlineBackend.close_figures = False
3533 3533
3534 3534 Parameters
3535 3535 ----------
3536 3536 guiname : optional
3537 3537 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3538 3538 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3539 3539 used, otherwise matplotlib's default (which you can override in your
3540 3540 matplotlib config file) is used.
3541 3541
3542 3542 Examples
3543 3543 --------
3544 3544 In this case, where the MPL default is TkAgg::
3545 3545
3546 3546 In [2]: %pylab
3547 3547
3548 3548 Welcome to pylab, a matplotlib-based Python environment.
3549 3549 Backend in use: TkAgg
3550 3550 For more information, type 'help(pylab)'.
3551 3551
3552 3552 But you can explicitly request a different backend::
3553 3553
3554 3554 In [3]: %pylab qt
3555 3555
3556 3556 Welcome to pylab, a matplotlib-based Python environment.
3557 3557 Backend in use: Qt4Agg
3558 3558 For more information, type 'help(pylab)'.
3559 3559 """
3560 3560
3561 3561 if Application.initialized():
3562 3562 app = Application.instance()
3563 3563 try:
3564 3564 import_all_status = app.pylab_import_all
3565 3565 except AttributeError:
3566 3566 import_all_status = True
3567 3567 else:
3568 3568 import_all_status = True
3569 3569
3570 3570 self.shell.enable_pylab(s, import_all=import_all_status)
3571 3571
3572 3572 def magic_tb(self, s):
3573 3573 """Print the last traceback with the currently active exception mode.
3574 3574
3575 3575 See %xmode for changing exception reporting modes."""
3576 3576 self.shell.showtraceback()
3577 3577
3578 3578 @skip_doctest
3579 3579 def magic_precision(self, s=''):
3580 3580 """Set floating point precision for pretty printing.
3581 3581
3582 3582 Can set either integer precision or a format string.
3583 3583
3584 3584 If numpy has been imported and precision is an int,
3585 3585 numpy display precision will also be set, via ``numpy.set_printoptions``.
3586 3586
3587 3587 If no argument is given, defaults will be restored.
3588 3588
3589 3589 Examples
3590 3590 --------
3591 3591 ::
3592 3592
3593 3593 In [1]: from math import pi
3594 3594
3595 3595 In [2]: %precision 3
3596 3596 Out[2]: u'%.3f'
3597 3597
3598 3598 In [3]: pi
3599 3599 Out[3]: 3.142
3600 3600
3601 3601 In [4]: %precision %i
3602 3602 Out[4]: u'%i'
3603 3603
3604 3604 In [5]: pi
3605 3605 Out[5]: 3
3606 3606
3607 3607 In [6]: %precision %e
3608 3608 Out[6]: u'%e'
3609 3609
3610 3610 In [7]: pi**10
3611 3611 Out[7]: 9.364805e+04
3612 3612
3613 3613 In [8]: %precision
3614 3614 Out[8]: u'%r'
3615 3615
3616 3616 In [9]: pi**10
3617 3617 Out[9]: 93648.047476082982
3618 3618
3619 3619 """
3620 3620
3621 3621 ptformatter = self.shell.display_formatter.formatters['text/plain']
3622 3622 ptformatter.float_precision = s
3623 3623 return ptformatter.float_format
3624 3624
3625 3625
3626 3626 @magic_arguments.magic_arguments()
3627 3627 @magic_arguments.argument(
3628 3628 '-e', '--export', action='store_true', default=False,
3629 3629 help='Export IPython history as a notebook. The filename argument '
3630 3630 'is used to specify the notebook name and format. For example '
3631 3631 'a filename of notebook.ipynb will result in a notebook name '
3632 3632 'of "notebook" and a format of "xml". Likewise using a ".json" '
3633 3633 'or ".py" file extension will write the notebook in the json '
3634 3634 'or py formats.'
3635 3635 )
3636 3636 @magic_arguments.argument(
3637 3637 '-f', '--format',
3638 3638 help='Convert an existing IPython notebook to a new format. This option '
3639 3639 'specifies the new format and can have the values: xml, json, py. '
3640 3640 'The target filename is chosen automatically based on the new '
3641 3641 'format. The filename argument gives the name of the source file.'
3642 3642 )
3643 3643 @magic_arguments.argument(
3644 3644 'filename', type=unicode,
3645 3645 help='Notebook name or filename'
3646 3646 )
3647 3647 def magic_notebook(self, s):
3648 3648 """Export and convert IPython notebooks.
3649 3649
3650 3650 This function can export the current IPython history to a notebook file
3651 3651 or can convert an existing notebook file into a different format. For
3652 3652 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3653 3653 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3654 3654 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3655 3655 formats include (json/ipynb, py).
3656 3656 """
3657 3657 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3658 3658
3659 3659 from IPython.nbformat import current
3660 3660 args.filename = unquote_filename(args.filename)
3661 3661 if args.export:
3662 3662 fname, name, format = current.parse_filename(args.filename)
3663 3663 cells = []
3664 3664 hist = list(self.history_manager.get_range())
3665 3665 for session, prompt_number, input in hist[:-1]:
3666 3666 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3667 3667 worksheet = current.new_worksheet(cells=cells)
3668 3668 nb = current.new_notebook(name=name,worksheets=[worksheet])
3669 3669 with io.open(fname, 'w', encoding='utf-8') as f:
3670 3670 current.write(nb, f, format);
3671 3671 elif args.format is not None:
3672 3672 old_fname, old_name, old_format = current.parse_filename(args.filename)
3673 3673 new_format = args.format
3674 3674 if new_format == u'xml':
3675 3675 raise ValueError('Notebooks cannot be written as xml.')
3676 3676 elif new_format == u'ipynb' or new_format == u'json':
3677 3677 new_fname = old_name + u'.ipynb'
3678 3678 new_format = u'json'
3679 3679 elif new_format == u'py':
3680 3680 new_fname = old_name + u'.py'
3681 3681 else:
3682 3682 raise ValueError('Invalid notebook format: %s' % new_format)
3683 3683 with io.open(old_fname, 'r', encoding='utf-8') as f:
3684 3684 nb = current.read(f, old_format)
3685 3685 with io.open(new_fname, 'w', encoding='utf-8') as f:
3686 3686 current.write(nb, f, new_format)
3687 3687
3688 3688 def magic_config(self, s):
3689 3689 """configure IPython
3690 3690
3691 3691 %config Class[.trait=value]
3692 3692
3693 3693 This magic exposes most of the IPython config system. Any
3694 3694 Configurable class should be able to be configured with the simple
3695 3695 line::
3696 3696
3697 3697 %config Class.trait=value
3698 3698
3699 3699 Where `value` will be resolved in the user's namespace, if it is an
3700 3700 expression or variable name.
3701 3701
3702 3702 Examples
3703 3703 --------
3704 3704
3705 3705 To see what classes are available for config, pass no arguments::
3706 3706
3707 3707 In [1]: %config
3708 3708 Available objects for config:
3709 3709 TerminalInteractiveShell
3710 3710 HistoryManager
3711 3711 PrefilterManager
3712 3712 AliasManager
3713 3713 IPCompleter
3714 3714 PromptManager
3715 3715 DisplayFormatter
3716 3716
3717 3717 To view what is configurable on a given class, just pass the class
3718 3718 name::
3719 3719
3720 3720 In [2]: %config IPCompleter
3721 3721 IPCompleter options
3722 3722 -----------------
3723 3723 IPCompleter.omit__names=<Enum>
3724 3724 Current: 2
3725 3725 Choices: (0, 1, 2)
3726 3726 Instruct the completer to omit private method names
3727 3727 Specifically, when completing on ``object.<tab>``.
3728 3728 When 2 [default]: all names that start with '_' will be excluded.
3729 3729 When 1: all 'magic' names (``__foo__``) will be excluded.
3730 3730 When 0: nothing will be excluded.
3731 3731 IPCompleter.merge_completions=<CBool>
3732 3732 Current: True
3733 3733 Whether to merge completion results into a single list
3734 3734 If False, only the completion results from the first non-empty completer
3735 3735 will be returned.
3736 3736 IPCompleter.limit_to__all__=<CBool>
3737 3737 Current: False
3738 3738 Instruct the completer to use __all__ for the completion
3739 3739 Specifically, when completing on ``object.<tab>``.
3740 3740 When True: only those names in obj.__all__ will be included.
3741 3741 When False [default]: the __all__ attribute is ignored
3742 3742 IPCompleter.greedy=<CBool>
3743 3743 Current: False
3744 3744 Activate greedy completion
3745 3745 This will enable completion on elements of lists, results of function calls,
3746 3746 etc., but can be unsafe because the code is actually evaluated on TAB.
3747 3747
3748 3748 but the real use is in setting values::
3749 3749
3750 3750 In [3]: %config IPCompleter.greedy = True
3751 3751
3752 3752 and these values are read from the user_ns if they are variables::
3753 3753
3754 3754 In [4]: feeling_greedy=False
3755 3755
3756 3756 In [5]: %config IPCompleter.greedy = feeling_greedy
3757 3757
3758 3758 """
3759 3759 from IPython.config.loader import Config
3760 3760 # some IPython objects are Configurable, but do not yet have
3761 3761 # any configurable traits. Exclude them from the effects of
3762 3762 # this magic, as their presence is just noise:
3763 3763 configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ]
3764 3764 classnames = [ c.__class__.__name__ for c in configurables ]
3765 3765
3766 3766 line = s.strip()
3767 3767 if not line:
3768 3768 # print available configurable names
3769 3769 print "Available objects for config:"
3770 3770 for name in classnames:
3771 3771 print " ", name
3772 3772 return
3773 3773 elif line in classnames:
3774 3774 # `%config TerminalInteractiveShell` will print trait info for
3775 3775 # TerminalInteractiveShell
3776 3776 c = configurables[classnames.index(line)]
3777 3777 cls = c.__class__
3778 3778 help = cls.class_get_help(c)
3779 3779 # strip leading '--' from cl-args:
3780 3780 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
3781 3781 print help
3782 3782 return
3783 3783 elif '=' not in line:
3784 3784 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3785 3785
3786 3786
3787 3787 # otherwise, assume we are setting configurables.
3788 3788 # leave quotes on args when splitting, because we want
3789 3789 # unquoted args to eval in user_ns
3790 3790 cfg = Config()
3791 3791 exec "cfg."+line in locals(), self.user_ns
3792 3792
3793 3793 for configurable in configurables:
3794 3794 try:
3795 3795 configurable.update_config(cfg)
3796 3796 except Exception as e:
3797 3797 error(e)
3798 3798
3799 3799 # end Magic
@@ -1,392 +1,392 b''
1 1 """Generic testing tools.
2 2
3 3 In particular, this module exposes a set of top-level assert* functions that
4 4 can be used in place of nose.tools.assert* in method generators (the ones in
5 5 nose can not, at least as of nose 0.10.4).
6 6
7 7
8 8 Authors
9 9 -------
10 10 - Fernando Perez <Fernando.Perez@berkeley.edu>
11 11 """
12 12
13 13 from __future__ import absolute_import
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2009-2011 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 import os
27 27 import re
28 28 import sys
29 29 import tempfile
30 30
31 31 from contextlib import contextmanager
32 32 from io import StringIO
33 33
34 34 try:
35 35 # These tools are used by parts of the runtime, so we make the nose
36 36 # dependency optional at this point. Nose is a hard dependency to run the
37 37 # test suite, but NOT to use ipython itself.
38 38 import nose.tools as nt
39 39 has_nose = True
40 40 except ImportError:
41 41 has_nose = False
42 42
43 43 from IPython.config.loader import Config
44 44 from IPython.utils.process import find_cmd, getoutputerror
45 45 from IPython.utils.text import list_strings
46 46 from IPython.utils.io import temp_pyfile, Tee
47 47 from IPython.utils import py3compat
48 from IPython.utils.encoding import getdefaultencoding
48 from IPython.utils.encoding import DEFAULT_ENCODING
49 49
50 50 from . import decorators as dec
51 51 from . import skipdoctest
52 52
53 53 #-----------------------------------------------------------------------------
54 54 # Globals
55 55 #-----------------------------------------------------------------------------
56 56
57 57 # Make a bunch of nose.tools assert wrappers that can be used in test
58 58 # generators. This will expose an assert* function for each one in nose.tools.
59 59
60 60 _tpl = """
61 61 def %(name)s(*a,**kw):
62 62 return nt.%(name)s(*a,**kw)
63 63 """
64 64
65 65 if has_nose:
66 66 for _x in [a for a in dir(nt) if a.startswith('assert')]:
67 67 exec _tpl % dict(name=_x)
68 68
69 69 #-----------------------------------------------------------------------------
70 70 # Functions and classes
71 71 #-----------------------------------------------------------------------------
72 72
73 73 # The docstring for full_path doctests differently on win32 (different path
74 74 # separator) so just skip the doctest there. The example remains informative.
75 75 doctest_deco = skipdoctest.skip_doctest if sys.platform == 'win32' else dec.null_deco
76 76
77 77 @doctest_deco
78 78 def full_path(startPath,files):
79 79 """Make full paths for all the listed files, based on startPath.
80 80
81 81 Only the base part of startPath is kept, since this routine is typically
82 82 used with a script's __file__ variable as startPath. The base of startPath
83 83 is then prepended to all the listed files, forming the output list.
84 84
85 85 Parameters
86 86 ----------
87 87 startPath : string
88 88 Initial path to use as the base for the results. This path is split
89 89 using os.path.split() and only its first component is kept.
90 90
91 91 files : string or list
92 92 One or more files.
93 93
94 94 Examples
95 95 --------
96 96
97 97 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
98 98 ['/foo/a.txt', '/foo/b.txt']
99 99
100 100 >>> full_path('/foo',['a.txt','b.txt'])
101 101 ['/a.txt', '/b.txt']
102 102
103 103 If a single file is given, the output is still a list:
104 104 >>> full_path('/foo','a.txt')
105 105 ['/a.txt']
106 106 """
107 107
108 108 files = list_strings(files)
109 109 base = os.path.split(startPath)[0]
110 110 return [ os.path.join(base,f) for f in files ]
111 111
112 112
113 113 def parse_test_output(txt):
114 114 """Parse the output of a test run and return errors, failures.
115 115
116 116 Parameters
117 117 ----------
118 118 txt : str
119 119 Text output of a test run, assumed to contain a line of one of the
120 120 following forms::
121 121 'FAILED (errors=1)'
122 122 'FAILED (failures=1)'
123 123 'FAILED (errors=1, failures=1)'
124 124
125 125 Returns
126 126 -------
127 127 nerr, nfail: number of errors and failures.
128 128 """
129 129
130 130 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
131 131 if err_m:
132 132 nerr = int(err_m.group(1))
133 133 nfail = 0
134 134 return nerr, nfail
135 135
136 136 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
137 137 if fail_m:
138 138 nerr = 0
139 139 nfail = int(fail_m.group(1))
140 140 return nerr, nfail
141 141
142 142 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
143 143 re.MULTILINE)
144 144 if both_m:
145 145 nerr = int(both_m.group(1))
146 146 nfail = int(both_m.group(2))
147 147 return nerr, nfail
148 148
149 149 # If the input didn't match any of these forms, assume no error/failures
150 150 return 0, 0
151 151
152 152
153 153 # So nose doesn't think this is a test
154 154 parse_test_output.__test__ = False
155 155
156 156
157 157 def default_argv():
158 158 """Return a valid default argv for creating testing instances of ipython"""
159 159
160 160 return ['--quick', # so no config file is loaded
161 161 # Other defaults to minimize side effects on stdout
162 162 '--colors=NoColor', '--no-term-title','--no-banner',
163 163 '--autocall=0']
164 164
165 165
166 166 def default_config():
167 167 """Return a config object with good defaults for testing."""
168 168 config = Config()
169 169 config.TerminalInteractiveShell.colors = 'NoColor'
170 170 config.TerminalTerminalInteractiveShell.term_title = False,
171 171 config.TerminalInteractiveShell.autocall = 0
172 172 config.HistoryManager.hist_file = tempfile.mktemp(u'test_hist.sqlite')
173 173 config.HistoryManager.db_cache_size = 10000
174 174 return config
175 175
176 176
177 177 def ipexec(fname, options=None):
178 178 """Utility to call 'ipython filename'.
179 179
180 180 Starts IPython witha minimal and safe configuration to make startup as fast
181 181 as possible.
182 182
183 183 Note that this starts IPython in a subprocess!
184 184
185 185 Parameters
186 186 ----------
187 187 fname : str
188 188 Name of file to be executed (should have .py or .ipy extension).
189 189
190 190 options : optional, list
191 191 Extra command-line flags to be passed to IPython.
192 192
193 193 Returns
194 194 -------
195 195 (stdout, stderr) of ipython subprocess.
196 196 """
197 197 if options is None: options = []
198 198
199 199 # For these subprocess calls, eliminate all prompt printing so we only see
200 200 # output from script execution
201 201 prompt_opts = [ '--PromptManager.in_template=""',
202 202 '--PromptManager.in2_template=""',
203 203 '--PromptManager.out_template=""'
204 204 ]
205 205 cmdargs = ' '.join(default_argv() + prompt_opts + options)
206 206
207 207 _ip = get_ipython()
208 208 test_dir = os.path.dirname(__file__)
209 209
210 210 ipython_cmd = find_cmd('ipython3' if py3compat.PY3 else 'ipython')
211 211 # Absolute path for filename
212 212 full_fname = os.path.join(test_dir, fname)
213 213 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
214 214 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
215 215 out, err = getoutputerror(full_cmd)
216 216 # `import readline` causes 'ESC[?1034h' to be output sometimes,
217 217 # so strip that out before doing comparisons
218 218 if out:
219 219 out = re.sub(r'\x1b\[[^h]+h', '', out)
220 220 return out, err
221 221
222 222
223 223 def ipexec_validate(fname, expected_out, expected_err='',
224 224 options=None):
225 225 """Utility to call 'ipython filename' and validate output/error.
226 226
227 227 This function raises an AssertionError if the validation fails.
228 228
229 229 Note that this starts IPython in a subprocess!
230 230
231 231 Parameters
232 232 ----------
233 233 fname : str
234 234 Name of the file to be executed (should have .py or .ipy extension).
235 235
236 236 expected_out : str
237 237 Expected stdout of the process.
238 238
239 239 expected_err : optional, str
240 240 Expected stderr of the process.
241 241
242 242 options : optional, list
243 243 Extra command-line flags to be passed to IPython.
244 244
245 245 Returns
246 246 -------
247 247 None
248 248 """
249 249
250 250 import nose.tools as nt
251 251
252 252 out, err = ipexec(fname, options)
253 253 #print 'OUT', out # dbg
254 254 #print 'ERR', err # dbg
255 255 # If there are any errors, we must check those befor stdout, as they may be
256 256 # more informative than simply having an empty stdout.
257 257 if err:
258 258 if expected_err:
259 259 nt.assert_equals(err.strip(), expected_err.strip())
260 260 else:
261 261 raise ValueError('Running file %r produced error: %r' %
262 262 (fname, err))
263 263 # If no errors or output on stderr was expected, match stdout
264 264 nt.assert_equals(out.strip(), expected_out.strip())
265 265
266 266
267 267 class TempFileMixin(object):
268 268 """Utility class to create temporary Python/IPython files.
269 269
270 270 Meant as a mixin class for test cases."""
271 271
272 272 def mktmp(self, src, ext='.py'):
273 273 """Make a valid python temp file."""
274 274 fname, f = temp_pyfile(src, ext)
275 275 self.tmpfile = f
276 276 self.fname = fname
277 277
278 278 def tearDown(self):
279 279 if hasattr(self, 'tmpfile'):
280 280 # If the tmpfile wasn't made because of skipped tests, like in
281 281 # win32, there's nothing to cleanup.
282 282 self.tmpfile.close()
283 283 try:
284 284 os.unlink(self.fname)
285 285 except:
286 286 # On Windows, even though we close the file, we still can't
287 287 # delete it. I have no clue why
288 288 pass
289 289
290 290 pair_fail_msg = ("Testing {0}\n\n"
291 291 "In:\n"
292 292 " {1!r}\n"
293 293 "Expected:\n"
294 294 " {2!r}\n"
295 295 "Got:\n"
296 296 " {3!r}\n")
297 297 def check_pairs(func, pairs):
298 298 """Utility function for the common case of checking a function with a
299 299 sequence of input/output pairs.
300 300
301 301 Parameters
302 302 ----------
303 303 func : callable
304 304 The function to be tested. Should accept a single argument.
305 305 pairs : iterable
306 306 A list of (input, expected_output) tuples.
307 307
308 308 Returns
309 309 -------
310 310 None. Raises an AssertionError if any output does not match the expected
311 311 value.
312 312 """
313 313 name = getattr(func, "func_name", getattr(func, "__name__", "<unknown>"))
314 314 for inp, expected in pairs:
315 315 out = func(inp)
316 316 assert out == expected, pair_fail_msg.format(name, inp, expected, out)
317 317
318 318
319 319 if py3compat.PY3:
320 320 MyStringIO = StringIO
321 321 else:
322 322 # In Python 2, stdout/stderr can have either bytes or unicode written to them,
323 323 # so we need a class that can handle both.
324 324 class MyStringIO(StringIO):
325 325 def write(self, s):
326 s = py3compat.cast_unicode(s, encoding=getdefaultencoding())
326 s = py3compat.cast_unicode(s, encoding=DEFAULT_ENCODING)
327 327 super(MyStringIO, self).write(s)
328 328
329 329 notprinted_msg = """Did not find {0!r} in printed output (on {1}):
330 330 {2!r}"""
331 331
332 332 class AssertPrints(object):
333 333 """Context manager for testing that code prints certain text.
334 334
335 335 Examples
336 336 --------
337 337 >>> with AssertPrints("abc", suppress=False):
338 338 ... print "abcd"
339 339 ... print "def"
340 340 ...
341 341 abcd
342 342 def
343 343 """
344 344 def __init__(self, s, channel='stdout', suppress=True):
345 345 self.s = s
346 346 self.channel = channel
347 347 self.suppress = suppress
348 348
349 349 def __enter__(self):
350 350 self.orig_stream = getattr(sys, self.channel)
351 351 self.buffer = MyStringIO()
352 352 self.tee = Tee(self.buffer, channel=self.channel)
353 353 setattr(sys, self.channel, self.buffer if self.suppress else self.tee)
354 354
355 355 def __exit__(self, etype, value, traceback):
356 356 self.tee.flush()
357 357 setattr(sys, self.channel, self.orig_stream)
358 358 printed = self.buffer.getvalue()
359 359 assert self.s in printed, notprinted_msg.format(self.s, self.channel, printed)
360 360 return False
361 361
362 362 class AssertNotPrints(AssertPrints):
363 363 """Context manager for checking that certain output *isn't* produced.
364 364
365 365 Counterpart of AssertPrints"""
366 366 def __exit__(self, etype, value, traceback):
367 367 self.tee.flush()
368 368 setattr(sys, self.channel, self.orig_stream)
369 369 printed = self.buffer.getvalue()
370 370 assert self.s not in printed, notprinted_msg.format(self.s, self.channel, printed)
371 371 return False
372 372
373 373 @contextmanager
374 374 def mute_warn():
375 375 from IPython.utils import warn
376 376 save_warn = warn.warn
377 377 warn.warn = lambda *a, **kw: None
378 378 try:
379 379 yield
380 380 finally:
381 381 warn.warn = save_warn
382 382
383 383 @contextmanager
384 384 def make_tempfile(name):
385 385 """ Create an empty, named, temporary file for the duration of the context.
386 386 """
387 387 f = open(name, 'w')
388 388 f.close()
389 389 try:
390 390 yield
391 391 finally:
392 392 os.unlink(name)
@@ -1,198 +1,198 b''
1 1 """Posix-specific implementation of process utilities.
2 2
3 3 This file is only meant to be imported by process.py, not by end-users.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010-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 from __future__ import print_function
17 17
18 18 # Stdlib
19 19 import subprocess as sp
20 20 import sys
21 21
22 22 from IPython.external import pexpect
23 23
24 24 # Our own
25 25 from .autoattr import auto_attr
26 26 from ._process_common import getoutput, arg_split
27 27 from IPython.utils import text
28 28 from IPython.utils import py3compat
29 from IPython.utils.encoding import getdefaultencoding
29 from IPython.utils.encoding import DEFAULT_ENCODING
30 30
31 31 #-----------------------------------------------------------------------------
32 32 # Function definitions
33 33 #-----------------------------------------------------------------------------
34 34
35 35 def _find_cmd(cmd):
36 36 """Find the full path to a command using which."""
37 37
38 38 path = sp.Popen(['/usr/bin/env', 'which', cmd],
39 39 stdout=sp.PIPE).communicate()[0]
40 40 return py3compat.bytes_to_str(path)
41 41
42 42
43 43 class ProcessHandler(object):
44 44 """Execute subprocesses under the control of pexpect.
45 45 """
46 46 # Timeout in seconds to wait on each reading of the subprocess' output.
47 47 # This should not be set too low to avoid cpu overusage from our side,
48 48 # since we read in a loop whose period is controlled by this timeout.
49 49 read_timeout = 0.05
50 50
51 51 # Timeout to give a process if we receive SIGINT, between sending the
52 52 # SIGINT to the process and forcefully terminating it.
53 53 terminate_timeout = 0.2
54 54
55 55 # File object where stdout and stderr of the subprocess will be written
56 56 logfile = None
57 57
58 58 # Shell to call for subprocesses to execute
59 59 sh = None
60 60
61 61 @auto_attr
62 62 def sh(self):
63 63 sh = pexpect.which('sh')
64 64 if sh is None:
65 65 raise OSError('"sh" shell not found')
66 66 return sh
67 67
68 68 def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
69 69 """Arguments are used for pexpect calls."""
70 70 self.read_timeout = (ProcessHandler.read_timeout if read_timeout is
71 71 None else read_timeout)
72 72 self.terminate_timeout = (ProcessHandler.terminate_timeout if
73 73 terminate_timeout is None else
74 74 terminate_timeout)
75 75 self.logfile = sys.stdout if logfile is None else logfile
76 76
77 77 def getoutput(self, cmd):
78 78 """Run a command and return its stdout/stderr as a string.
79 79
80 80 Parameters
81 81 ----------
82 82 cmd : str
83 83 A command to be executed in the system shell.
84 84
85 85 Returns
86 86 -------
87 87 output : str
88 88 A string containing the combination of stdout and stderr from the
89 89 subprocess, in whatever order the subprocess originally wrote to its
90 90 file descriptors (so the order of the information in this string is the
91 91 correct order as would be seen if running the command in a terminal).
92 92 """
93 93 try:
94 94 return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
95 95 except KeyboardInterrupt:
96 96 print('^C', file=sys.stderr, end='')
97 97
98 98 def getoutput_pexpect(self, cmd):
99 99 """Run a command and return its stdout/stderr as a string.
100 100
101 101 Parameters
102 102 ----------
103 103 cmd : str
104 104 A command to be executed in the system shell.
105 105
106 106 Returns
107 107 -------
108 108 output : str
109 109 A string containing the combination of stdout and stderr from the
110 110 subprocess, in whatever order the subprocess originally wrote to its
111 111 file descriptors (so the order of the information in this string is the
112 112 correct order as would be seen if running the command in a terminal).
113 113 """
114 114 try:
115 115 return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
116 116 except KeyboardInterrupt:
117 117 print('^C', file=sys.stderr, end='')
118 118
119 119 def system(self, cmd):
120 120 """Execute a command in a subshell.
121 121
122 122 Parameters
123 123 ----------
124 124 cmd : str
125 125 A command to be executed in the system shell.
126 126
127 127 Returns
128 128 -------
129 129 int : child's exitstatus
130 130 """
131 131 # Get likely encoding for the output.
132 enc = getdefaultencoding()
132 enc = DEFAULT_ENCODING
133 133
134 134 # Patterns to match on the output, for pexpect. We read input and
135 135 # allow either a short timeout or EOF
136 136 patterns = [pexpect.TIMEOUT, pexpect.EOF]
137 137 # the index of the EOF pattern in the list.
138 138 # even though we know it's 1, this call means we don't have to worry if
139 139 # we change the above list, and forget to change this value:
140 140 EOF_index = patterns.index(pexpect.EOF)
141 141 # The size of the output stored so far in the process output buffer.
142 142 # Since pexpect only appends to this buffer, each time we print we
143 143 # record how far we've printed, so that next time we only print *new*
144 144 # content from the buffer.
145 145 out_size = 0
146 146 try:
147 147 # Since we're not really searching the buffer for text patterns, we
148 148 # can set pexpect's search window to be tiny and it won't matter.
149 149 # We only search for the 'patterns' timeout or EOF, which aren't in
150 150 # the text itself.
151 151 #child = pexpect.spawn(pcmd, searchwindowsize=1)
152 152 if hasattr(pexpect, 'spawnb'):
153 153 child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U
154 154 else:
155 155 child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect
156 156 flush = sys.stdout.flush
157 157 while True:
158 158 # res is the index of the pattern that caused the match, so we
159 159 # know whether we've finished (if we matched EOF) or not
160 160 res_idx = child.expect_list(patterns, self.read_timeout)
161 161 print(child.before[out_size:].decode(enc, 'replace'), end='')
162 162 flush()
163 163 if res_idx==EOF_index:
164 164 break
165 165 # Update the pointer to what we've already printed
166 166 out_size = len(child.before)
167 167 except KeyboardInterrupt:
168 168 # We need to send ^C to the process. The ascii code for '^C' is 3
169 169 # (the character is known as ETX for 'End of Text', see
170 170 # curses.ascii.ETX).
171 171 child.sendline(chr(3))
172 172 # Read and print any more output the program might produce on its
173 173 # way out.
174 174 try:
175 175 out_size = len(child.before)
176 176 child.expect_list(patterns, self.terminate_timeout)
177 177 print(child.before[out_size:].decode(enc, 'replace'), end='')
178 178 sys.stdout.flush()
179 179 except KeyboardInterrupt:
180 180 # Impatient users tend to type it multiple times
181 181 pass
182 182 finally:
183 183 # Ensure the subprocess really is terminated
184 184 child.terminate(force=True)
185 185 # add isalive check, to ensure exitstatus is set:
186 186 child.isalive()
187 187 return child.exitstatus
188 188
189 189
190 190 # Make system() with a functional interface for outside use. Note that we use
191 191 # getoutput() from the _common utils, which is built on top of popen(). Using
192 192 # pexpect to get subprocess output produces difficult to parse output, since
193 193 # programs think they are talking to a tty and produce highly formatted output
194 194 # (ls is a good example) that makes them hard.
195 195 system = ProcessHandler().system
196 196
197 197
198 198
@@ -1,185 +1,185 b''
1 1 """Windows-specific implementation of process utilities.
2 2
3 3 This file is only meant to be imported by process.py, not by end-users.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010-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 from __future__ import print_function
17 17
18 18 # stdlib
19 19 import os
20 20 import sys
21 21 import ctypes
22 22 import msvcrt
23 23
24 24 from ctypes import c_int, POINTER
25 25 from ctypes.wintypes import LPCWSTR, HLOCAL
26 26 from subprocess import STDOUT
27 27
28 28 # our own imports
29 29 from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
30 30 from . import py3compat
31 31 from . import text
32 from .encoding import getdefaultencoding
32 from .encoding import DEFAULT_ENCODING
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Function definitions
36 36 #-----------------------------------------------------------------------------
37 37
38 38 class AvoidUNCPath(object):
39 39 """A context manager to protect command execution from UNC paths.
40 40
41 41 In the Win32 API, commands can't be invoked with the cwd being a UNC path.
42 42 This context manager temporarily changes directory to the 'C:' drive on
43 43 entering, and restores the original working directory on exit.
44 44
45 45 The context manager returns the starting working directory *if* it made a
46 46 change and None otherwise, so that users can apply the necessary adjustment
47 47 to their system calls in the event of a change.
48 48
49 49 Example
50 50 -------
51 51 ::
52 52 cmd = 'dir'
53 53 with AvoidUNCPath() as path:
54 54 if path is not None:
55 55 cmd = '"pushd %s &&"%s' % (path, cmd)
56 56 os.system(cmd)
57 57 """
58 58 def __enter__(self):
59 59 self.path = os.getcwdu()
60 60 self.is_unc_path = self.path.startswith(r"\\")
61 61 if self.is_unc_path:
62 62 # change to c drive (as cmd.exe cannot handle UNC addresses)
63 63 os.chdir("C:")
64 64 return self.path
65 65 else:
66 66 # We return None to signal that there was no change in the working
67 67 # directory
68 68 return None
69 69
70 70 def __exit__(self, exc_type, exc_value, traceback):
71 71 if self.is_unc_path:
72 72 os.chdir(self.path)
73 73
74 74
75 75 def _find_cmd(cmd):
76 76 """Find the full path to a .bat or .exe using the win32api module."""
77 77 try:
78 78 from win32api import SearchPath
79 79 except ImportError:
80 80 raise ImportError('you need to have pywin32 installed for this to work')
81 81 else:
82 82 PATH = os.environ['PATH']
83 83 extensions = ['.exe', '.com', '.bat', '.py']
84 84 path = None
85 85 for ext in extensions:
86 86 try:
87 87 path = SearchPath(PATH, cmd + ext)[0]
88 88 except:
89 89 pass
90 90 if path is None:
91 91 raise OSError("command %r not found" % cmd)
92 92 else:
93 93 return path
94 94
95 95
96 96 def _system_body(p):
97 97 """Callback for _system."""
98 enc = getdefaultencoding()
98 enc = DEFAULT_ENCODING
99 99 for line in read_no_interrupt(p.stdout).splitlines():
100 100 line = line.decode(enc, 'replace')
101 101 print(line, file=sys.stdout)
102 102 for line in read_no_interrupt(p.stderr).splitlines():
103 103 line = line.decode(enc, 'replace')
104 104 print(line, file=sys.stderr)
105 105
106 106 # Wait to finish for returncode
107 107 return p.wait()
108 108
109 109
110 110 def system(cmd):
111 111 """Win32 version of os.system() that works with network shares.
112 112
113 113 Note that this implementation returns None, as meant for use in IPython.
114 114
115 115 Parameters
116 116 ----------
117 117 cmd : str
118 118 A command to be executed in the system shell.
119 119
120 120 Returns
121 121 -------
122 122 None : we explicitly do NOT return the subprocess status code, as this
123 123 utility is meant to be used extensively in IPython, where any return value
124 124 would trigger :func:`sys.displayhook` calls.
125 125 """
126 126 # The controller provides interactivity with both
127 127 # stdin and stdout
128 128 import _process_win32_controller
129 129 _process_win32_controller.system(cmd)
130 130
131 131
132 132 def getoutput(cmd):
133 133 """Return standard output of executing cmd in a shell.
134 134
135 135 Accepts the same arguments as os.system().
136 136
137 137 Parameters
138 138 ----------
139 139 cmd : str
140 140 A command to be executed in the system shell.
141 141
142 142 Returns
143 143 -------
144 144 stdout : str
145 145 """
146 146
147 147 with AvoidUNCPath() as path:
148 148 if path is not None:
149 149 cmd = '"pushd %s &&"%s' % (path, cmd)
150 150 out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
151 151
152 152 if out is None:
153 153 out = ''
154 154 return out
155 155
156 156 try:
157 157 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
158 158 CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
159 159 CommandLineToArgvW.res_types = [POINTER(LPCWSTR)]
160 160 LocalFree = ctypes.windll.kernel32.LocalFree
161 161 LocalFree.res_type = HLOCAL
162 162 LocalFree.arg_types = [HLOCAL]
163 163
164 164 def arg_split(commandline, posix=False, strict=True):
165 165 """Split a command line's arguments in a shell-like manner.
166 166
167 167 This is a special version for windows that use a ctypes call to CommandLineToArgvW
168 168 to do the argv splitting. The posix paramter is ignored.
169 169
170 170 If strict=False, process_common.arg_split(...strict=False) is used instead.
171 171 """
172 172 #CommandLineToArgvW returns path to executable if called with empty string.
173 173 if commandline.strip() == "":
174 174 return []
175 175 if not strict:
176 176 # not really a cl-arg, fallback on _process_common
177 177 return py_arg_split(commandline, posix=posix, strict=strict)
178 178 argvn = c_int()
179 179 result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
180 180 result_array_type = LPCWSTR * argvn.value
181 181 result = [arg for arg in result_array_type.from_address(result_pointer)]
182 182 retval = LocalFree(result_pointer)
183 183 return result
184 184 except AttributeError:
185 185 arg_split = py_arg_split
@@ -1,54 +1,56 b''
1 1 # coding: utf-8
2 2 """
3 3 Utilities for dealing with text encodings
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2012 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 import sys
17 17 import locale
18 18
19 19 # to deal with the possibility of sys.std* not being a stream at all
20 20 def get_stream_enc(stream, default=None):
21 21 """Return the given stream's encoding or a default.
22 22
23 23 There are cases where sys.std* might not actually be a stream, so
24 24 check for the encoding attribute prior to returning it, and return
25 25 a default if it doesn't exist or evaluates as False. `default'
26 26 is None if not provided.
27 27 """
28 28 if not hasattr(stream, 'encoding') or not stream.encoding:
29 29 return default
30 30 else:
31 31 return stream.encoding
32 32
33 33 # Less conservative replacement for sys.getdefaultencoding, that will try
34 34 # to match the environment.
35 35 # Defined here as central function, so if we find better choices, we
36 36 # won't need to make changes all over IPython.
37 37 def getdefaultencoding():
38 38 """Return IPython's guess for the default encoding for bytes as text.
39 39
40 40 Asks for stdin.encoding first, to match the calling Terminal, but that
41 41 is often None for subprocesses. Fall back on locale.getpreferredencoding()
42 42 which should be a sensible platform default (that respects LANG environment),
43 43 and finally to sys.getdefaultencoding() which is the most conservative option,
44 44 and usually ASCII.
45 45 """
46 46 enc = get_stream_enc(sys.stdin)
47 47 if not enc or enc=='ascii':
48 48 try:
49 49 # There are reports of getpreferredencoding raising errors
50 50 # in some cases, which may well be fixed, but let's be conservative here.
51 51 enc = locale.getpreferredencoding()
52 52 except Exception:
53 53 pass
54 54 return enc or sys.getdefaultencoding()
55
56 DEFAULT_ENCODING = getdefaultencoding()
@@ -1,166 +1,166 b''
1 1 """Utilities to manipulate JSON objects.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (C) 2010-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.txt, distributed as part of this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13 # stdlib
14 14 import re
15 15 import sys
16 16 import types
17 17 from datetime import datetime
18 18
19 19 from IPython.utils import py3compat
20 from IPython.utils.encoding import getdefaultencoding
20 from IPython.utils.encoding import DEFAULT_ENCODING
21 21 from IPython.utils import text
22 22 next_attr_name = '__next__' if py3compat.PY3 else 'next'
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Globals and constants
26 26 #-----------------------------------------------------------------------------
27 27
28 28 # timestamp formats
29 29 ISO8601="%Y-%m-%dT%H:%M:%S.%f"
30 30 ISO8601_PAT=re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+$")
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Classes and functions
34 34 #-----------------------------------------------------------------------------
35 35
36 36 def rekey(dikt):
37 37 """Rekey a dict that has been forced to use str keys where there should be
38 38 ints by json."""
39 39 for k in dikt.iterkeys():
40 40 if isinstance(k, basestring):
41 41 ik=fk=None
42 42 try:
43 43 ik = int(k)
44 44 except ValueError:
45 45 try:
46 46 fk = float(k)
47 47 except ValueError:
48 48 continue
49 49 if ik is not None:
50 50 nk = ik
51 51 else:
52 52 nk = fk
53 53 if nk in dikt:
54 54 raise KeyError("already have key %r"%nk)
55 55 dikt[nk] = dikt.pop(k)
56 56 return dikt
57 57
58 58
59 59 def extract_dates(obj):
60 60 """extract ISO8601 dates from unpacked JSON"""
61 61 if isinstance(obj, dict):
62 62 obj = dict(obj) # don't clobber
63 63 for k,v in obj.iteritems():
64 64 obj[k] = extract_dates(v)
65 65 elif isinstance(obj, (list, tuple)):
66 66 obj = [ extract_dates(o) for o in obj ]
67 67 elif isinstance(obj, basestring):
68 68 if ISO8601_PAT.match(obj):
69 69 obj = datetime.strptime(obj, ISO8601)
70 70 return obj
71 71
72 72 def squash_dates(obj):
73 73 """squash datetime objects into ISO8601 strings"""
74 74 if isinstance(obj, dict):
75 75 obj = dict(obj) # don't clobber
76 76 for k,v in obj.iteritems():
77 77 obj[k] = squash_dates(v)
78 78 elif isinstance(obj, (list, tuple)):
79 79 obj = [ squash_dates(o) for o in obj ]
80 80 elif isinstance(obj, datetime):
81 81 obj = obj.strftime(ISO8601)
82 82 return obj
83 83
84 84 def date_default(obj):
85 85 """default function for packing datetime objects in JSON."""
86 86 if isinstance(obj, datetime):
87 87 return obj.strftime(ISO8601)
88 88 else:
89 89 raise TypeError("%r is not JSON serializable"%obj)
90 90
91 91
92 92
93 93 def json_clean(obj):
94 94 """Clean an object to ensure it's safe to encode in JSON.
95 95
96 96 Atomic, immutable objects are returned unmodified. Sets and tuples are
97 97 converted to lists, lists are copied and dicts are also copied.
98 98
99 99 Note: dicts whose keys could cause collisions upon encoding (such as a dict
100 100 with both the number 1 and the string '1' as keys) will cause a ValueError
101 101 to be raised.
102 102
103 103 Parameters
104 104 ----------
105 105 obj : any python object
106 106
107 107 Returns
108 108 -------
109 109 out : object
110 110
111 111 A version of the input which will not cause an encoding error when
112 112 encoded as JSON. Note that this function does not *encode* its inputs,
113 113 it simply sanitizes it so that there will be no encoding errors later.
114 114
115 115 Examples
116 116 --------
117 117 >>> json_clean(4)
118 118 4
119 119 >>> json_clean(range(10))
120 120 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
121 121 >>> json_clean(dict(x=1, y=2))
122 122 {'y': 2, 'x': 1}
123 123 >>> json_clean(dict(x=1, y=2, z=[1,2,3]))
124 124 {'y': 2, 'x': 1, 'z': [1, 2, 3]}
125 125 >>> json_clean(True)
126 126 True
127 127 """
128 128 # types that are 'atomic' and ok in json as-is. bool doesn't need to be
129 129 # listed explicitly because bools pass as int instances
130 130 atomic_ok = (unicode, int, float, types.NoneType)
131 131
132 132 # containers that we need to convert into lists
133 133 container_to_list = (tuple, set, types.GeneratorType)
134 134
135 135 if isinstance(obj, atomic_ok):
136 136 return obj
137 137
138 138 if isinstance(obj, bytes):
139 return obj.decode(getdefaultencoding(), 'replace')
139 return obj.decode(DEFAULT_ENCODING, 'replace')
140 140
141 141 if isinstance(obj, container_to_list) or (
142 142 hasattr(obj, '__iter__') and hasattr(obj, next_attr_name)):
143 143 obj = list(obj)
144 144
145 145 if isinstance(obj, list):
146 146 return [json_clean(x) for x in obj]
147 147
148 148 if isinstance(obj, dict):
149 149 # First, validate that the dict won't lose data in conversion due to
150 150 # key collisions after stringification. This can happen with keys like
151 151 # True and 'true' or 1 and '1', which collide in JSON.
152 152 nkeys = len(obj)
153 153 nkeys_collapsed = len(set(map(str, obj)))
154 154 if nkeys != nkeys_collapsed:
155 155 raise ValueError('dict can not be safely converted to JSON: '
156 156 'key collision would lead to dropped values')
157 157 # If all OK, proceed by making the new dict that will be json-safe
158 158 out = {}
159 159 for k,v in obj.iteritems():
160 160 out[str(k)] = json_clean(v)
161 161 return out
162 162
163 163 # If we get here, we don't know how to handle the object, so we just get
164 164 # its repr and return that. This will catch lambdas, open sockets, class
165 165 # objects, and any other complicated contraption that json can't encode
166 166 return repr(obj)
@@ -1,180 +1,178 b''
1 1 # coding: utf-8
2 2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 3 import __builtin__
4 4 import functools
5 5 import sys
6 6 import re
7 7 import types
8 8
9 from .encoding import getdefaultencoding
10
11 default_encoding = getdefaultencoding()
9 from .encoding import DEFAULT_ENCODING
12 10
13 11 orig_open = open
14 12
15 13 def no_code(x, encoding=None):
16 14 return x
17 15
18 16 def decode(s, encoding=None):
19 encoding = encoding or default_encoding
17 encoding = encoding or DEFAULT_ENCODING
20 18 return s.decode(encoding, "replace")
21 19
22 20 def encode(u, encoding=None):
23 encoding = encoding or default_encoding
21 encoding = encoding or DEFAULT_ENCODING
24 22 return u.encode(encoding, "replace")
25 23
26 24
27 25 def cast_unicode(s, encoding=None):
28 26 if isinstance(s, bytes):
29 27 return decode(s, encoding)
30 28 return s
31 29
32 30 def cast_bytes(s, encoding=None):
33 31 if not isinstance(s, bytes):
34 32 return encode(s, encoding)
35 33 return s
36 34
37 35 def _modify_str_or_docstring(str_change_func):
38 36 @functools.wraps(str_change_func)
39 37 def wrapper(func_or_str):
40 38 if isinstance(func_or_str, basestring):
41 39 func = None
42 40 doc = func_or_str
43 41 else:
44 42 func = func_or_str
45 43 doc = func.__doc__
46 44
47 45 doc = str_change_func(doc)
48 46
49 47 if func:
50 48 func.__doc__ = doc
51 49 return func
52 50 return doc
53 51 return wrapper
54 52
55 53 if sys.version_info[0] >= 3:
56 54 PY3 = True
57 55
58 56 input = input
59 57 builtin_mod_name = "builtins"
60 58
61 59 str_to_unicode = no_code
62 60 unicode_to_str = no_code
63 61 str_to_bytes = encode
64 62 bytes_to_str = decode
65 63 cast_bytes_py2 = no_code
66 64
67 65 def isidentifier(s, dotted=False):
68 66 if dotted:
69 67 return all(isidentifier(a) for a in s.split("."))
70 68 return s.isidentifier()
71 69
72 70 open = orig_open
73 71
74 72 MethodType = types.MethodType
75 73
76 74 def execfile(fname, glob, loc=None):
77 75 loc = loc if (loc is not None) else glob
78 76 exec compile(open(fname, 'rb').read(), fname, 'exec') in glob, loc
79 77
80 78 # Refactor print statements in doctests.
81 79 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
82 80 def _print_statement_sub(match):
83 81 expr = match.groups('expr')
84 82 return "print(%s)" % expr
85 83
86 84 @_modify_str_or_docstring
87 85 def doctest_refactor_print(doc):
88 86 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
89 87 unfortunately doesn't pick up on our doctests.
90 88
91 89 Can accept a string or a function, so it can be used as a decorator."""
92 90 return _print_statement_re.sub(_print_statement_sub, doc)
93 91
94 92 # Abstract u'abc' syntax:
95 93 @_modify_str_or_docstring
96 94 def u_format(s):
97 95 """"{u}'abc'" --> "'abc'" (Python 3)
98 96
99 97 Accepts a string or a function, so it can be used as a decorator."""
100 98 return s.format(u='')
101 99
102 100 else:
103 101 PY3 = False
104 102
105 103 input = raw_input
106 104 builtin_mod_name = "__builtin__"
107 105
108 106 str_to_unicode = decode
109 107 unicode_to_str = encode
110 108 str_to_bytes = no_code
111 109 bytes_to_str = no_code
112 110 cast_bytes_py2 = cast_bytes
113 111
114 112 import re
115 113 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
116 114 def isidentifier(s, dotted=False):
117 115 if dotted:
118 116 return all(isidentifier(a) for a in s.split("."))
119 117 return bool(_name_re.match(s))
120 118
121 119 class open(object):
122 120 """Wrapper providing key part of Python 3 open() interface."""
123 121 def __init__(self, fname, mode="r", encoding="utf-8"):
124 122 self.f = orig_open(fname, mode)
125 123 self.enc = encoding
126 124
127 125 def write(self, s):
128 126 return self.f.write(s.encode(self.enc))
129 127
130 128 def read(self, size=-1):
131 129 return self.f.read(size).decode(self.enc)
132 130
133 131 def close(self):
134 132 return self.f.close()
135 133
136 134 def __enter__(self):
137 135 return self
138 136
139 137 def __exit__(self, etype, value, traceback):
140 138 self.f.close()
141 139
142 140 def MethodType(func, instance):
143 141 return types.MethodType(func, instance, type(instance))
144 142
145 143 # don't override system execfile on 2.x:
146 144 execfile = execfile
147 145
148 146 def doctest_refactor_print(func_or_str):
149 147 return func_or_str
150 148
151 149
152 150 # Abstract u'abc' syntax:
153 151 @_modify_str_or_docstring
154 152 def u_format(s):
155 153 """"{u}'abc'" --> "u'abc'" (Python 2)
156 154
157 155 Accepts a string or a function, so it can be used as a decorator."""
158 156 return s.format(u='u')
159 157
160 158 if sys.platform == 'win32':
161 159 def execfile(fname, glob=None, loc=None):
162 160 loc = loc if (loc is not None) else glob
163 161 # The rstrip() is necessary b/c trailing whitespace in files will
164 162 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
165 163 # but we still support 2.6). See issue 1027.
166 164 scripttext = __builtin__.open(fname).read().rstrip() + '\n'
167 165 # compile converts unicode filename to str assuming
168 166 # ascii. Let's do the conversion before calling compile
169 167 if isinstance(fname, unicode):
170 168 filename = unicode_to_str(fname)
171 169 else:
172 170 filename = fname
173 171 exec compile(scripttext, filename, 'exec') in glob, loc
174 172 else:
175 173 def execfile(fname, *where):
176 174 if isinstance(fname, unicode):
177 175 filename = fname.encode(sys.getfilesystemencoding())
178 176 else:
179 177 filename = fname
180 178 __builtin__.execfile(filename, *where)
General Comments 0
You need to be logged in to leave comments. Login now