##// END OF EJS Templates
Merge with trunk
Gael Varoquaux -
r1823:8e1e827f merge
parent child Browse files
Show More

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

This diff has been collapsed as it changes many lines, (1867 lines changed) Show them Hide them
@@ -0,0 +1,1867 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright � 2006 Steven J. Bethard <steven.bethard@gmail.com>.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted under the terms of the 3-clause BSD
7 # license. No warranty expressed or implied.
8 # For details, see the accompanying file LICENSE.txt.
9
10 """Command-line parsing library
11
12 This module is an optparse-inspired command-line parsing library that:
13
14 * handles both optional and positional arguments
15 * produces highly informative usage messages
16 * supports parsers that dispatch to sub-parsers
17
18 The following is a simple usage example that sums integers from the
19 command-line and writes the result to a file:
20
21 parser = argparse.ArgumentParser(
22 description='sum the integers at the command line')
23 parser.add_argument(
24 'integers', metavar='int', nargs='+', type=int,
25 help='an integer to be summed')
26 parser.add_argument(
27 '--log', default=sys.stdout, type=argparse.FileType('w'),
28 help='the file where the sum should be written')
29 args = parser.parse_args()
30 args.log.write('%s' % sum(args.integers))
31 args.log.close()
32
33 The module contains the following public classes:
34
35 ArgumentParser -- The main entry point for command-line parsing. As the
36 example above shows, the add_argument() method is used to populate
37 the parser with actions for optional and positional arguments. Then
38 the parse_args() method is invoked to convert the args at the
39 command-line into an object with attributes.
40
41 ArgumentError -- The exception raised by ArgumentParser objects when
42 there are errors with the parser's actions. Errors raised while
43 parsing the command-line are caught by ArgumentParser and emitted
44 as command-line messages.
45
46 FileType -- A factory for defining types of files to be created. As the
47 example above shows, instances of FileType are typically passed as
48 the type= argument of add_argument() calls.
49
50 Action -- The base class for parser actions. Typically actions are
51 selected by passing strings like 'store_true' or 'append_const' to
52 the action= argument of add_argument(). However, for greater
53 customization of ArgumentParser actions, subclasses of Action may
54 be defined and passed as the action= argument.
55
56 HelpFormatter, RawDescriptionHelpFormatter -- Formatter classes which
57 may be passed as the formatter_class= argument to the
58 ArgumentParser constructor. HelpFormatter is the default, while
59 RawDescriptionHelpFormatter tells the parser not to perform any
60 line-wrapping on description text.
61
62 All other classes in this module are considered implementation details.
63 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
64 considered public as object names -- the API of the formatter objects is
65 still considered an implementation detail.)
66 """
67
68 __version__ = '0.8.0'
69
70 import os as _os
71 import re as _re
72 import sys as _sys
73 import textwrap as _textwrap
74
75 from gettext import gettext as _
76
77 SUPPRESS = '==SUPPRESS=='
78
79 OPTIONAL = '?'
80 ZERO_OR_MORE = '*'
81 ONE_OR_MORE = '+'
82 PARSER = '==PARSER=='
83
84 # =============================
85 # Utility functions and classes
86 # =============================
87
88 class _AttributeHolder(object):
89 """Abstract base class that provides __repr__.
90
91 The __repr__ method returns a string in the format:
92 ClassName(attr=name, attr=name, ...)
93 The attributes are determined either by a class-level attribute,
94 '_kwarg_names', or by inspecting the instance __dict__.
95 """
96
97 def __repr__(self):
98 type_name = type(self).__name__
99 arg_strings = []
100 for arg in self._get_args():
101 arg_strings.append(repr(arg))
102 for name, value in self._get_kwargs():
103 arg_strings.append('%s=%r' % (name, value))
104 return '%s(%s)' % (type_name, ', '.join(arg_strings))
105
106 def _get_kwargs(self):
107 return sorted(self.__dict__.items())
108
109 def _get_args(self):
110 return []
111
112 def _ensure_value(namespace, name, value):
113 if getattr(namespace, name, None) is None:
114 setattr(namespace, name, value)
115 return getattr(namespace, name)
116
117
118
119 # ===============
120 # Formatting Help
121 # ===============
122
123 class HelpFormatter(object):
124
125 def __init__(self,
126 prog,
127 indent_increment=2,
128 max_help_position=24,
129 width=None):
130
131 # default setting for width
132 if width is None:
133 try:
134 width = int(_os.environ['COLUMNS'])
135 except (KeyError, ValueError):
136 width = 80
137 width -= 2
138
139 self._prog = prog
140 self._indent_increment = indent_increment
141 self._max_help_position = max_help_position
142 self._width = width
143
144 self._current_indent = 0
145 self._level = 0
146 self._action_max_length = 0
147
148 self._root_section = self._Section(self, None)
149 self._current_section = self._root_section
150
151 self._whitespace_matcher = _re.compile(r'\s+')
152 self._long_break_matcher = _re.compile(r'\n\n\n+')
153
154 # ===============================
155 # Section and indentation methods
156 # ===============================
157
158 def _indent(self):
159 self._current_indent += self._indent_increment
160 self._level += 1
161
162 def _dedent(self):
163 self._current_indent -= self._indent_increment
164 assert self._current_indent >= 0, 'Indent decreased below 0.'
165 self._level -= 1
166
167 class _Section(object):
168 def __init__(self, formatter, parent, heading=None):
169 self.formatter = formatter
170 self.parent = parent
171 self.heading = heading
172 self.items = []
173
174 def format_help(self):
175 # format the indented section
176 if self.parent is not None:
177 self.formatter._indent()
178 join = self.formatter._join_parts
179 for func, args in self.items:
180 func(*args)
181 item_help = join(func(*args) for func, args in self.items)
182 if self.parent is not None:
183 self.formatter._dedent()
184
185 # return nothing if the section was empty
186 if not item_help:
187 return ''
188
189 # add the heading if the section was non-empty
190 if self.heading is not SUPPRESS and self.heading is not None:
191 current_indent = self.formatter._current_indent
192 heading = '%*s%s:\n' % (current_indent, '', self.heading)
193 else:
194 heading = ''
195
196 # join the section-initial newline, the heading and the help
197 return join(['\n', heading, item_help, '\n'])
198
199 def _add_item(self, func, args):
200 self._current_section.items.append((func, args))
201
202 # ========================
203 # Message building methods
204 # ========================
205
206 def start_section(self, heading):
207 self._indent()
208 section = self._Section(self, self._current_section, heading)
209 self._add_item(section.format_help, [])
210 self._current_section = section
211
212 def end_section(self):
213 self._current_section = self._current_section.parent
214 self._dedent()
215
216 def add_text(self, text):
217 if text is not SUPPRESS and text is not None:
218 self._add_item(self._format_text, [text])
219
220 def add_usage(self, usage, optionals, positionals, prefix=None):
221 if usage is not SUPPRESS:
222 args = usage, optionals, positionals, prefix
223 self._add_item(self._format_usage, args)
224
225 def add_argument(self, action):
226 if action.help is not SUPPRESS:
227
228 # find all invocations
229 get_invocation = self._format_action_invocation
230 invocations = [get_invocation(action)]
231 for subaction in self._iter_indented_subactions(action):
232 invocations.append(get_invocation(subaction))
233
234 # update the maximum item length
235 invocation_length = max(len(s) for s in invocations)
236 action_length = invocation_length + self._current_indent
237 self._action_max_length = max(self._action_max_length,
238 action_length)
239
240 # add the item to the list
241 self._add_item(self._format_action, [action])
242
243 def add_arguments(self, actions):
244 for action in actions:
245 self.add_argument(action)
246
247 # =======================
248 # Help-formatting methods
249 # =======================
250
251 def format_help(self):
252 help = self._root_section.format_help() % dict(prog=self._prog)
253 if help:
254 help = self._long_break_matcher.sub('\n\n', help)
255 help = help.strip('\n') + '\n'
256 return help
257
258 def _join_parts(self, part_strings):
259 return ''.join(part
260 for part in part_strings
261 if part and part is not SUPPRESS)
262
263 def _format_usage(self, usage, optionals, positionals, prefix):
264 if prefix is None:
265 prefix = _('usage: ')
266
267 # if no optionals or positionals are available, usage is just prog
268 if usage is None and not optionals and not positionals:
269 usage = '%(prog)s'
270
271 # if optionals and positionals are available, calculate usage
272 elif usage is None:
273 usage = '%(prog)s' % dict(prog=self._prog)
274
275 # determine width of "usage: PROG" and width of text
276 prefix_width = len(prefix) + len(usage) + 1
277 prefix_indent = self._current_indent + prefix_width
278 text_width = self._width - self._current_indent
279
280 # put them on one line if they're short enough
281 format = self._format_actions_usage
282 action_usage = format(optionals + positionals)
283 if prefix_width + len(action_usage) + 1 < text_width:
284 usage = '%s %s' % (usage, action_usage)
285
286 # if they're long, wrap optionals and positionals individually
287 else:
288 optional_usage = format(optionals)
289 positional_usage = format(positionals)
290 indent = ' ' * prefix_indent
291
292 # usage is made of PROG, optionals and positionals
293 parts = [usage, ' ']
294
295 # options always get added right after PROG
296 if optional_usage:
297 parts.append(_textwrap.fill(
298 optional_usage, text_width,
299 initial_indent=indent,
300 subsequent_indent=indent).lstrip())
301
302 # if there were options, put arguments on the next line
303 # otherwise, start them right after PROG
304 if positional_usage:
305 part = _textwrap.fill(
306 positional_usage, text_width,
307 initial_indent=indent,
308 subsequent_indent=indent).lstrip()
309 if optional_usage:
310 part = '\n' + indent + part
311 parts.append(part)
312 usage = ''.join(parts)
313
314 # prefix with 'usage:'
315 return '%s%s\n\n' % (prefix, usage)
316
317 def _format_actions_usage(self, actions):
318 parts = []
319 for action in actions:
320 if action.help is SUPPRESS:
321 continue
322
323 # produce all arg strings
324 if not action.option_strings:
325 parts.append(self._format_args(action, action.dest))
326
327 # produce the first way to invoke the option in brackets
328 else:
329 option_string = action.option_strings[0]
330
331 # if the Optional doesn't take a value, format is:
332 # -s or --long
333 if action.nargs == 0:
334 part = '%s' % option_string
335
336 # if the Optional takes a value, format is:
337 # -s ARGS or --long ARGS
338 else:
339 default = action.dest.upper()
340 args_string = self._format_args(action, default)
341 part = '%s %s' % (option_string, args_string)
342
343 # make it look optional if it's not required
344 if not action.required:
345 part = '[%s]' % part
346 parts.append(part)
347
348 return ' '.join(parts)
349
350 def _format_text(self, text):
351 text_width = self._width - self._current_indent
352 indent = ' ' * self._current_indent
353 return self._fill_text(text, text_width, indent) + '\n\n'
354
355 def _format_action(self, action):
356 # determine the required width and the entry label
357 help_position = min(self._action_max_length + 2,
358 self._max_help_position)
359 help_width = self._width - help_position
360 action_width = help_position - self._current_indent - 2
361 action_header = self._format_action_invocation(action)
362
363 # ho nelp; start on same line and add a final newline
364 if not action.help:
365 tup = self._current_indent, '', action_header
366 action_header = '%*s%s\n' % tup
367
368 # short action name; start on the same line and pad two spaces
369 elif len(action_header) <= action_width:
370 tup = self._current_indent, '', action_width, action_header
371 action_header = '%*s%-*s ' % tup
372 indent_first = 0
373
374 # long action name; start on the next line
375 else:
376 tup = self._current_indent, '', action_header
377 action_header = '%*s%s\n' % tup
378 indent_first = help_position
379
380 # collect the pieces of the action help
381 parts = [action_header]
382
383 # if there was help for the action, add lines of help text
384 if action.help:
385 help_text = self._expand_help(action)
386 help_lines = self._split_lines(help_text, help_width)
387 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
388 for line in help_lines[1:]:
389 parts.append('%*s%s\n' % (help_position, '', line))
390
391 # or add a newline if the description doesn't end with one
392 elif not action_header.endswith('\n'):
393 parts.append('\n')
394
395 # if there are any sub-actions, add their help as well
396 for subaction in self._iter_indented_subactions(action):
397 parts.append(self._format_action(subaction))
398
399 # return a single string
400 return self._join_parts(parts)
401
402 def _format_action_invocation(self, action):
403 if not action.option_strings:
404 return self._format_metavar(action, action.dest)
405
406 else:
407 parts = []
408
409 # if the Optional doesn't take a value, format is:
410 # -s, --long
411 if action.nargs == 0:
412 parts.extend(action.option_strings)
413
414 # if the Optional takes a value, format is:
415 # -s ARGS, --long ARGS
416 else:
417 default = action.dest.upper()
418 args_string = self._format_args(action, default)
419 for option_string in action.option_strings:
420 parts.append('%s %s' % (option_string, args_string))
421
422 return ', '.join(parts)
423
424 def _format_metavar(self, action, default_metavar):
425 if action.metavar is not None:
426 name = action.metavar
427 elif action.choices is not None:
428 choice_strs = (str(choice) for choice in action.choices)
429 name = '{%s}' % ','.join(choice_strs)
430 else:
431 name = default_metavar
432 return name
433
434 def _format_args(self, action, default_metavar):
435 name = self._format_metavar(action, default_metavar)
436 if action.nargs is None:
437 result = name
438 elif action.nargs == OPTIONAL:
439 result = '[%s]' % name
440 elif action.nargs == ZERO_OR_MORE:
441 result = '[%s [%s ...]]' % (name, name)
442 elif action.nargs == ONE_OR_MORE:
443 result = '%s [%s ...]' % (name, name)
444 elif action.nargs is PARSER:
445 result = '%s ...' % name
446 else:
447 result = ' '.join([name] * action.nargs)
448 return result
449
450 def _expand_help(self, action):
451 params = dict(vars(action), prog=self._prog)
452 for name, value in params.items():
453 if value is SUPPRESS:
454 del params[name]
455 if params.get('choices') is not None:
456 choices_str = ', '.join(str(c) for c in params['choices'])
457 params['choices'] = choices_str
458 return action.help % params
459
460 def _iter_indented_subactions(self, action):
461 try:
462 get_subactions = action._get_subactions
463 except AttributeError:
464 pass
465 else:
466 self._indent()
467 for subaction in get_subactions():
468 yield subaction
469 self._dedent()
470
471 def _split_lines(self, text, width):
472 text = self._whitespace_matcher.sub(' ', text).strip()
473 return _textwrap.wrap(text, width)
474
475 def _fill_text(self, text, width, indent):
476 text = self._whitespace_matcher.sub(' ', text).strip()
477 return _textwrap.fill(text, width, initial_indent=indent,
478 subsequent_indent=indent)
479
480 class RawDescriptionHelpFormatter(HelpFormatter):
481
482 def _fill_text(self, text, width, indent):
483 return ''.join(indent + line for line in text.splitlines(True))
484
485 class RawTextHelpFormatter(RawDescriptionHelpFormatter):
486
487 def _split_lines(self, text, width):
488 return text.splitlines()
489
490 # =====================
491 # Options and Arguments
492 # =====================
493
494 class ArgumentError(Exception):
495 """ArgumentError(message, argument)
496
497 Raised whenever there was an error creating or using an argument
498 (optional or positional).
499
500 The string value of this exception is the message, augmented with
501 information about the argument that caused it.
502 """
503
504 def __init__(self, argument, message):
505 if argument.option_strings:
506 self.argument_name = '/'.join(argument.option_strings)
507 elif argument.metavar not in (None, SUPPRESS):
508 self.argument_name = argument.metavar
509 elif argument.dest not in (None, SUPPRESS):
510 self.argument_name = argument.dest
511 else:
512 self.argument_name = None
513 self.message = message
514
515 def __str__(self):
516 if self.argument_name is None:
517 format = '%(message)s'
518 else:
519 format = 'argument %(argument_name)s: %(message)s'
520 return format % dict(message=self.message,
521 argument_name=self.argument_name)
522
523 # ==============
524 # Action classes
525 # ==============
526
527 class Action(_AttributeHolder):
528 """Action(*strings, **options)
529
530 Action objects hold the information necessary to convert a
531 set of command-line arguments (possibly including an initial option
532 string) into the desired Python object(s).
533
534 Keyword Arguments:
535
536 option_strings -- A list of command-line option strings which
537 should be associated with this action.
538
539 dest -- The name of the attribute to hold the created object(s)
540
541 nargs -- The number of command-line arguments that should be consumed.
542 By default, one argument will be consumed and a single value will
543 be produced. Other values include:
544 * N (an integer) consumes N arguments (and produces a list)
545 * '?' consumes zero or one arguments
546 * '*' consumes zero or more arguments (and produces a list)
547 * '+' consumes one or more arguments (and produces a list)
548 Note that the difference between the default and nargs=1 is that
549 with the default, a single value will be produced, while with
550 nargs=1, a list containing a single value will be produced.
551
552 const -- The value to be produced if the option is specified and the
553 option uses an action that takes no values.
554
555 default -- The value to be produced if the option is not specified.
556
557 type -- The type which the command-line arguments should be converted
558 to, should be one of 'string', 'int', 'float', 'complex' or a
559 callable object that accepts a single string argument. If None,
560 'string' is assumed.
561
562 choices -- A container of values that should be allowed. If not None,
563 after a command-line argument has been converted to the appropriate
564 type, an exception will be raised if it is not a member of this
565 collection.
566
567 required -- True if the action must always be specified at the command
568 line. This is only meaningful for optional command-line arguments.
569
570 help -- The help string describing the argument.
571
572 metavar -- The name to be used for the option's argument with the help
573 string. If None, the 'dest' value will be used as the name.
574 """
575
576
577 def __init__(self,
578 option_strings,
579 dest,
580 nargs=None,
581 const=None,
582 default=None,
583 type=None,
584 choices=None,
585 required=False,
586 help=None,
587 metavar=None):
588 self.option_strings = option_strings
589 self.dest = dest
590 self.nargs = nargs
591 self.const = const
592 self.default = default
593 self.type = type
594 self.choices = choices
595 self.required = required
596 self.help = help
597 self.metavar = metavar
598
599 def _get_kwargs(self):
600 names = [
601 'option_strings',
602 'dest',
603 'nargs',
604 'const',
605 'default',
606 'type',
607 'choices',
608 'help',
609 'metavar'
610 ]
611 return [(name, getattr(self, name)) for name in names]
612
613 def __call__(self, parser, namespace, values, option_string=None):
614 raise NotImplementedError(_('.__call__() not defined'))
615
616 class _StoreAction(Action):
617 def __init__(self,
618 option_strings,
619 dest,
620 nargs=None,
621 const=None,
622 default=None,
623 type=None,
624 choices=None,
625 required=False,
626 help=None,
627 metavar=None):
628 if nargs == 0:
629 raise ValueError('nargs must be > 0')
630 if const is not None and nargs != OPTIONAL:
631 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
632 super(_StoreAction, self).__init__(
633 option_strings=option_strings,
634 dest=dest,
635 nargs=nargs,
636 const=const,
637 default=default,
638 type=type,
639 choices=choices,
640 required=required,
641 help=help,
642 metavar=metavar)
643
644 def __call__(self, parser, namespace, values, option_string=None):
645 setattr(namespace, self.dest, values)
646
647 class _StoreConstAction(Action):
648 def __init__(self,
649 option_strings,
650 dest,
651 const,
652 default=None,
653 required=False,
654 help=None,
655 metavar=None):
656 super(_StoreConstAction, self).__init__(
657 option_strings=option_strings,
658 dest=dest,
659 nargs=0,
660 const=const,
661 default=default,
662 required=required,
663 help=help)
664
665 def __call__(self, parser, namespace, values, option_string=None):
666 setattr(namespace, self.dest, self.const)
667
668 class _StoreTrueAction(_StoreConstAction):
669 def __init__(self,
670 option_strings,
671 dest,
672 default=False,
673 required=False,
674 help=None):
675 super(_StoreTrueAction, self).__init__(
676 option_strings=option_strings,
677 dest=dest,
678 const=True,
679 default=default,
680 required=required,
681 help=help)
682
683 class _StoreFalseAction(_StoreConstAction):
684 def __init__(self,
685 option_strings,
686 dest,
687 default=True,
688 required=False,
689 help=None):
690 super(_StoreFalseAction, self).__init__(
691 option_strings=option_strings,
692 dest=dest,
693 const=False,
694 default=default,
695 required=required,
696 help=help)
697
698 class _AppendAction(Action):
699 def __init__(self,
700 option_strings,
701 dest,
702 nargs=None,
703 const=None,
704 default=None,
705 type=None,
706 choices=None,
707 required=False,
708 help=None,
709 metavar=None):
710 if nargs == 0:
711 raise ValueError('nargs must be > 0')
712 if const is not None and nargs != OPTIONAL:
713 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
714 super(_AppendAction, self).__init__(
715 option_strings=option_strings,
716 dest=dest,
717 nargs=nargs,
718 const=const,
719 default=default,
720 type=type,
721 choices=choices,
722 required=required,
723 help=help,
724 metavar=metavar)
725
726 def __call__(self, parser, namespace, values, option_string=None):
727 _ensure_value(namespace, self.dest, []).append(values)
728
729 class _AppendConstAction(Action):
730 def __init__(self,
731 option_strings,
732 dest,
733 const,
734 default=None,
735 required=False,
736 help=None,
737 metavar=None):
738 super(_AppendConstAction, self).__init__(
739 option_strings=option_strings,
740 dest=dest,
741 nargs=0,
742 const=const,
743 default=default,
744 required=required,
745 help=help,
746 metavar=metavar)
747
748 def __call__(self, parser, namespace, values, option_string=None):
749 _ensure_value(namespace, self.dest, []).append(self.const)
750
751 class _CountAction(Action):
752 def __init__(self,
753 option_strings,
754 dest,
755 default=None,
756 required=False,
757 help=None):
758 super(_CountAction, self).__init__(
759 option_strings=option_strings,
760 dest=dest,
761 nargs=0,
762 default=default,
763 required=required,
764 help=help)
765
766 def __call__(self, parser, namespace, values, option_string=None):
767 new_count = _ensure_value(namespace, self.dest, 0) + 1
768 setattr(namespace, self.dest, new_count)
769
770 class _HelpAction(Action):
771 def __init__(self,
772 option_strings,
773 dest=SUPPRESS,
774 default=SUPPRESS,
775 help=None):
776 super(_HelpAction, self).__init__(
777 option_strings=option_strings,
778 dest=dest,
779 default=default,
780 nargs=0,
781 help=help)
782
783 def __call__(self, parser, namespace, values, option_string=None):
784 parser.print_help()
785 parser.exit()
786
787 class _VersionAction(Action):
788 def __init__(self,
789 option_strings,
790 dest=SUPPRESS,
791 default=SUPPRESS,
792 help=None):
793 super(_VersionAction, self).__init__(
794 option_strings=option_strings,
795 dest=dest,
796 default=default,
797 nargs=0,
798 help=help)
799
800 def __call__(self, parser, namespace, values, option_string=None):
801 parser.print_version()
802 parser.exit()
803
804 class _SubParsersAction(Action):
805
806 class _ChoicesPseudoAction(Action):
807 def __init__(self, name, help):
808 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
809 sup.__init__(option_strings=[], dest=name, help=help)
810
811
812 def __init__(self,
813 option_strings,
814 prog,
815 parser_class,
816 dest=SUPPRESS,
817 help=None,
818 metavar=None):
819
820 self._prog_prefix = prog
821 self._parser_class = parser_class
822 self._name_parser_map = {}
823 self._choices_actions = []
824
825 super(_SubParsersAction, self).__init__(
826 option_strings=option_strings,
827 dest=dest,
828 nargs=PARSER,
829 choices=self._name_parser_map,
830 help=help,
831 metavar=metavar)
832
833 def add_parser(self, name, **kwargs):
834 # set prog from the existing prefix
835 if kwargs.get('prog') is None:
836 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
837
838 # create a pseudo-action to hold the choice help
839 if 'help' in kwargs:
840 help = kwargs.pop('help')
841 choice_action = self._ChoicesPseudoAction(name, help)
842 self._choices_actions.append(choice_action)
843
844 # create the parser and add it to the map
845 parser = self._parser_class(**kwargs)
846 self._name_parser_map[name] = parser
847 return parser
848
849 def _get_subactions(self):
850 return self._choices_actions
851
852 def __call__(self, parser, namespace, values, option_string=None):
853 parser_name = values[0]
854 arg_strings = values[1:]
855
856 # set the parser name if requested
857 if self.dest is not SUPPRESS:
858 setattr(namespace, self.dest, parser_name)
859
860 # select the parser
861 try:
862 parser = self._name_parser_map[parser_name]
863 except KeyError:
864 tup = parser_name, ', '.join(self._name_parser_map)
865 msg = _('unknown parser %r (choices: %s)' % tup)
866 raise ArgumentError(self, msg)
867
868 # parse all the remaining options into the namespace
869 parser.parse_args(arg_strings, namespace)
870
871
872 # ==============
873 # Type classes
874 # ==============
875
876 class FileType(object):
877 """Factory for creating file object types
878
879 Instances of FileType are typically passed as type= arguments to the
880 ArgumentParser add_argument() method.
881
882 Keyword Arguments:
883 mode -- A string indicating how the file is to be opened. Accepts the
884 same values as the builtin open() function.
885 bufsize -- The file's desired buffer size. Accepts the same values as
886 the builtin open() function.
887 """
888 def __init__(self, mode='r', bufsize=None):
889 self._mode = mode
890 self._bufsize = bufsize
891
892 def __call__(self, string):
893 # the special argument "-" means sys.std{in,out}
894 if string == '-':
895 if self._mode == 'r':
896 return _sys.stdin
897 elif self._mode == 'w':
898 return _sys.stdout
899 else:
900 msg = _('argument "-" with mode %r' % self._mode)
901 raise ValueError(msg)
902
903 # all other arguments are used as file names
904 if self._bufsize:
905 return open(string, self._mode, self._bufsize)
906 else:
907 return open(string, self._mode)
908
909
910 # ===========================
911 # Optional and Positional Parsing
912 # ===========================
913
914 class Namespace(_AttributeHolder):
915
916 def __init__(self, **kwargs):
917 for name, value in kwargs.iteritems():
918 setattr(self, name, value)
919
920 def __eq__(self, other):
921 return vars(self) == vars(other)
922
923 def __ne__(self, other):
924 return not (self == other)
925
926
927 class _ActionsContainer(object):
928 def __init__(self,
929 description,
930 prefix_chars,
931 argument_default,
932 conflict_handler):
933 super(_ActionsContainer, self).__init__()
934
935 self.description = description
936 self.argument_default = argument_default
937 self.prefix_chars = prefix_chars
938 self.conflict_handler = conflict_handler
939
940 # set up registries
941 self._registries = {}
942
943 # register actions
944 self.register('action', None, _StoreAction)
945 self.register('action', 'store', _StoreAction)
946 self.register('action', 'store_const', _StoreConstAction)
947 self.register('action', 'store_true', _StoreTrueAction)
948 self.register('action', 'store_false', _StoreFalseAction)
949 self.register('action', 'append', _AppendAction)
950 self.register('action', 'append_const', _AppendConstAction)
951 self.register('action', 'count', _CountAction)
952 self.register('action', 'help', _HelpAction)
953 self.register('action', 'version', _VersionAction)
954 self.register('action', 'parsers', _SubParsersAction)
955
956 # raise an exception if the conflict handler is invalid
957 self._get_handler()
958
959 # action storage
960 self._optional_actions_list = []
961 self._positional_actions_list = []
962 self._positional_actions_full_list = []
963 self._option_strings = {}
964
965 # defaults storage
966 self._defaults = {}
967
968 # ====================
969 # Registration methods
970 # ====================
971
972 def register(self, registry_name, value, object):
973 registry = self._registries.setdefault(registry_name, {})
974 registry[value] = object
975
976 def _registry_get(self, registry_name, value, default=None):
977 return self._registries[registry_name].get(value, default)
978
979 # ==================================
980 # Namespace default settings methods
981 # ==================================
982
983 def set_defaults(self, **kwargs):
984 self._defaults.update(kwargs)
985
986 # if these defaults match any existing arguments, replace
987 # the previous default on the object with the new one
988 for action_list in [self._option_strings.values(),
989 self._positional_actions_full_list]:
990 for action in action_list:
991 if action.dest in kwargs:
992 action.default = kwargs[action.dest]
993
994 # =======================
995 # Adding argument actions
996 # =======================
997
998 def add_argument(self, *args, **kwargs):
999 """
1000 add_argument(dest, ..., name=value, ...)
1001 add_argument(option_string, option_string, ..., name=value, ...)
1002 """
1003
1004 # if no positional args are supplied or only one is supplied and
1005 # it doesn't look like an option string, parse a positional
1006 # argument
1007 chars = self.prefix_chars
1008 if not args or len(args) == 1 and args[0][0] not in chars:
1009 kwargs = self._get_positional_kwargs(*args, **kwargs)
1010
1011 # otherwise, we're adding an optional argument
1012 else:
1013 kwargs = self._get_optional_kwargs(*args, **kwargs)
1014
1015 # if no default was supplied, use the parser-level default
1016 if 'default' not in kwargs:
1017 dest = kwargs['dest']
1018 if dest in self._defaults:
1019 kwargs['default'] = self._defaults[dest]
1020 elif self.argument_default is not None:
1021 kwargs['default'] = self.argument_default
1022
1023 # create the action object, and add it to the parser
1024 action_class = self._pop_action_class(kwargs)
1025 action = action_class(**kwargs)
1026 return self._add_action(action)
1027
1028 def _add_action(self, action):
1029 # resolve any conflicts
1030 self._check_conflict(action)
1031
1032 # add to optional or positional list
1033 if action.option_strings:
1034 self._optional_actions_list.append(action)
1035 else:
1036 self._positional_actions_list.append(action)
1037 self._positional_actions_full_list.append(action)
1038 action.container = self
1039
1040 # index the action by any option strings it has
1041 for option_string in action.option_strings:
1042 self._option_strings[option_string] = action
1043
1044 # return the created action
1045 return action
1046
1047 def _add_container_actions(self, container):
1048 for action in container._optional_actions_list:
1049 self._add_action(action)
1050 for action in container._positional_actions_list:
1051 self._add_action(action)
1052
1053 def _get_positional_kwargs(self, dest, **kwargs):
1054 # make sure required is not specified
1055 if 'required' in kwargs:
1056 msg = _("'required' is an invalid argument for positionals")
1057 raise TypeError(msg)
1058
1059 # return the keyword arguments with no option strings
1060 return dict(kwargs, dest=dest, option_strings=[])
1061
1062 def _get_optional_kwargs(self, *args, **kwargs):
1063 # determine short and long option strings
1064 option_strings = []
1065 long_option_strings = []
1066 for option_string in args:
1067 # error on one-or-fewer-character option strings
1068 if len(option_string) < 2:
1069 msg = _('invalid option string %r: '
1070 'must be at least two characters long')
1071 raise ValueError(msg % option_string)
1072
1073 # error on strings that don't start with an appropriate prefix
1074 if not option_string[0] in self.prefix_chars:
1075 msg = _('invalid option string %r: '
1076 'must start with a character %r')
1077 tup = option_string, self.prefix_chars
1078 raise ValueError(msg % tup)
1079
1080 # error on strings that are all prefix characters
1081 if not (set(option_string) - set(self.prefix_chars)):
1082 msg = _('invalid option string %r: '
1083 'must contain characters other than %r')
1084 tup = option_string, self.prefix_chars
1085 raise ValueError(msg % tup)
1086
1087 # strings starting with two prefix characters are long options
1088 option_strings.append(option_string)
1089 if option_string[0] in self.prefix_chars:
1090 if option_string[1] in self.prefix_chars:
1091 long_option_strings.append(option_string)
1092
1093 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1094 dest = kwargs.pop('dest', None)
1095 if dest is None:
1096 if long_option_strings:
1097 dest_option_string = long_option_strings[0]
1098 else:
1099 dest_option_string = option_strings[0]
1100 dest = dest_option_string.lstrip(self.prefix_chars)
1101 dest = dest.replace('-', '_')
1102
1103 # return the updated keyword arguments
1104 return dict(kwargs, dest=dest, option_strings=option_strings)
1105
1106 def _pop_action_class(self, kwargs, default=None):
1107 action = kwargs.pop('action', default)
1108 return self._registry_get('action', action, action)
1109
1110 def _get_handler(self):
1111 # determine function from conflict handler string
1112 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1113 try:
1114 return getattr(self, handler_func_name)
1115 except AttributeError:
1116 msg = _('invalid conflict_resolution value: %r')
1117 raise ValueError(msg % self.conflict_handler)
1118
1119 def _check_conflict(self, action):
1120
1121 # find all options that conflict with this option
1122 confl_optionals = []
1123 for option_string in action.option_strings:
1124 if option_string in self._option_strings:
1125 confl_optional = self._option_strings[option_string]
1126 confl_optionals.append((option_string, confl_optional))
1127
1128 # resolve any conflicts
1129 if confl_optionals:
1130 conflict_handler = self._get_handler()
1131 conflict_handler(action, confl_optionals)
1132
1133 def _handle_conflict_error(self, action, conflicting_actions):
1134 message = _('conflicting option string(s): %s')
1135 conflict_string = ', '.join(option_string
1136 for option_string, action
1137 in conflicting_actions)
1138 raise ArgumentError(action, message % conflict_string)
1139
1140 def _handle_conflict_resolve(self, action, conflicting_actions):
1141
1142 # remove all conflicting options
1143 for option_string, action in conflicting_actions:
1144
1145 # remove the conflicting option
1146 action.option_strings.remove(option_string)
1147 self._option_strings.pop(option_string, None)
1148
1149 # if the option now has no option string, remove it from the
1150 # container holding it
1151 if not action.option_strings:
1152 action.container._optional_actions_list.remove(action)
1153
1154
1155 class _ArgumentGroup(_ActionsContainer):
1156
1157 def __init__(self, container, title=None, description=None, **kwargs):
1158 # add any missing keyword arguments by checking the container
1159 update = kwargs.setdefault
1160 update('conflict_handler', container.conflict_handler)
1161 update('prefix_chars', container.prefix_chars)
1162 update('argument_default', container.argument_default)
1163 super_init = super(_ArgumentGroup, self).__init__
1164 super_init(description=description, **kwargs)
1165
1166 self.title = title
1167 self._registries = container._registries
1168 self._positional_actions_full_list = container._positional_actions_full_list
1169 self._option_strings = container._option_strings
1170 self._defaults = container._defaults
1171
1172
1173 class ArgumentParser(_AttributeHolder, _ActionsContainer):
1174
1175 def __init__(self,
1176 prog=None,
1177 usage=None,
1178 description=None,
1179 epilog=None,
1180 version=None,
1181 parents=[],
1182 formatter_class=HelpFormatter,
1183 prefix_chars='-',
1184 argument_default=None,
1185 conflict_handler='error',
1186 add_help=True):
1187
1188 superinit = super(ArgumentParser, self).__init__
1189 superinit(description=description,
1190 prefix_chars=prefix_chars,
1191 argument_default=argument_default,
1192 conflict_handler=conflict_handler)
1193
1194 # default setting for prog
1195 if prog is None:
1196 prog = _os.path.basename(_sys.argv[0])
1197
1198 self.prog = prog
1199 self.usage = usage
1200 self.epilog = epilog
1201 self.version = version
1202 self.formatter_class = formatter_class
1203 self.add_help = add_help
1204
1205 self._argument_group_class = _ArgumentGroup
1206 self._has_subparsers = False
1207 self._argument_groups = []
1208
1209 # register types
1210 def identity(string):
1211 return string
1212 self.register('type', None, identity)
1213
1214 # add help and version arguments if necessary
1215 # (using explicit default to override global argument_default)
1216 if self.add_help:
1217 self.add_argument(
1218 '-h', '--help', action='help', default=SUPPRESS,
1219 help=_('show this help message and exit'))
1220 if self.version:
1221 self.add_argument(
1222 '-v', '--version', action='version', default=SUPPRESS,
1223 help=_("show program's version number and exit"))
1224
1225 # add parent arguments and defaults
1226 for parent in parents:
1227 self._add_container_actions(parent)
1228 try:
1229 defaults = parent._defaults
1230 except AttributeError:
1231 pass
1232 else:
1233 self._defaults.update(defaults)
1234
1235 # determines whether an "option" looks like a negative number
1236 self._negative_number_matcher = _re.compile(r'^-\d+|-\d*.\d+$')
1237
1238
1239 # =======================
1240 # Pretty __repr__ methods
1241 # =======================
1242
1243 def _get_kwargs(self):
1244 names = [
1245 'prog',
1246 'usage',
1247 'description',
1248 'version',
1249 'formatter_class',
1250 'conflict_handler',
1251 'add_help',
1252 ]
1253 return [(name, getattr(self, name)) for name in names]
1254
1255 # ==================================
1256 # Optional/Positional adding methods
1257 # ==================================
1258
1259 def add_argument_group(self, *args, **kwargs):
1260 group = self._argument_group_class(self, *args, **kwargs)
1261 self._argument_groups.append(group)
1262 return group
1263
1264 def add_subparsers(self, **kwargs):
1265 if self._has_subparsers:
1266 self.error(_('cannot have multiple subparser arguments'))
1267
1268 # add the parser class to the arguments if it's not present
1269 kwargs.setdefault('parser_class', type(self))
1270
1271 # prog defaults to the usage message of this parser, skipping
1272 # optional arguments and with no "usage:" prefix
1273 if kwargs.get('prog') is None:
1274 formatter = self._get_formatter()
1275 formatter.add_usage(self.usage, [],
1276 self._get_positional_actions(), '')
1277 kwargs['prog'] = formatter.format_help().strip()
1278
1279 # create the parsers action and add it to the positionals list
1280 parsers_class = self._pop_action_class(kwargs, 'parsers')
1281 action = parsers_class(option_strings=[], **kwargs)
1282 self._positional_actions_list.append(action)
1283 self._positional_actions_full_list.append(action)
1284 self._has_subparsers = True
1285
1286 # return the created parsers action
1287 return action
1288
1289 def _add_container_actions(self, container):
1290 super(ArgumentParser, self)._add_container_actions(container)
1291 try:
1292 groups = container._argument_groups
1293 except AttributeError:
1294 pass
1295 else:
1296 for group in groups:
1297 new_group = self.add_argument_group(
1298 title=group.title,
1299 description=group.description,
1300 conflict_handler=group.conflict_handler)
1301 new_group._add_container_actions(group)
1302
1303 def _get_optional_actions(self):
1304 actions = []
1305 actions.extend(self._optional_actions_list)
1306 for argument_group in self._argument_groups:
1307 actions.extend(argument_group._optional_actions_list)
1308 return actions
1309
1310 def _get_positional_actions(self):
1311 return list(self._positional_actions_full_list)
1312
1313
1314 # =====================================
1315 # Command line argument parsing methods
1316 # =====================================
1317
1318 def parse_args(self, args=None, namespace=None):
1319 # args default to the system args
1320 if args is None:
1321 args = _sys.argv[1:]
1322
1323 # default Namespace built from parser defaults
1324 if namespace is None:
1325 namespace = Namespace()
1326
1327 # add any action defaults that aren't present
1328 optional_actions = self._get_optional_actions()
1329 positional_actions = self._get_positional_actions()
1330 for action in optional_actions + positional_actions:
1331 if action.dest is not SUPPRESS:
1332 if not hasattr(namespace, action.dest):
1333 if action.default is not SUPPRESS:
1334 default = action.default
1335 if isinstance(action.default, basestring):
1336 default = self._get_value(action, default)
1337 setattr(namespace, action.dest, default)
1338
1339 # add any parser defaults that aren't present
1340 for dest, value in self._defaults.iteritems():
1341 if not hasattr(namespace, dest):
1342 setattr(namespace, dest, value)
1343
1344 # parse the arguments and exit if there are any errors
1345 try:
1346 result = self._parse_args(args, namespace)
1347 except ArgumentError, err:
1348 self.error(str(err))
1349
1350 # make sure all required optionals are present
1351 for action in self._get_optional_actions():
1352 if action.required:
1353 if getattr(result, action.dest, None) is None:
1354 opt_strs = '/'.join(action.option_strings)
1355 msg = _('option %s is required' % opt_strs)
1356 self.error(msg)
1357
1358 # return the parsed arguments
1359 return result
1360
1361 def _parse_args(self, arg_strings, namespace):
1362
1363 # find all option indices, and determine the arg_string_pattern
1364 # which has an 'O' if there is an option at an index,
1365 # an 'A' if there is an argument, or a '-' if there is a '--'
1366 option_string_indices = {}
1367 arg_string_pattern_parts = []
1368 arg_strings_iter = iter(arg_strings)
1369 for i, arg_string in enumerate(arg_strings_iter):
1370
1371 # all args after -- are non-options
1372 if arg_string == '--':
1373 arg_string_pattern_parts.append('-')
1374 for arg_string in arg_strings_iter:
1375 arg_string_pattern_parts.append('A')
1376
1377 # otherwise, add the arg to the arg strings
1378 # and note the index if it was an option
1379 else:
1380 option_tuple = self._parse_optional(arg_string)
1381 if option_tuple is None:
1382 pattern = 'A'
1383 else:
1384 option_string_indices[i] = option_tuple
1385 pattern = 'O'
1386 arg_string_pattern_parts.append(pattern)
1387
1388 # join the pieces together to form the pattern
1389 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1390
1391 # converts arg strings to the appropriate and then takes the action
1392 def take_action(action, argument_strings, option_string=None):
1393 argument_values = self._get_values(action, argument_strings)
1394 # take the action if we didn't receive a SUPPRESS value
1395 # (e.g. from a default)
1396 if argument_values is not SUPPRESS:
1397 action(self, namespace, argument_values, option_string)
1398
1399 # function to convert arg_strings into an optional action
1400 def consume_optional(start_index):
1401
1402 # determine the optional action and parse any explicit
1403 # argument out of the option string
1404 option_tuple = option_string_indices[start_index]
1405 action, option_string, explicit_arg = option_tuple
1406
1407 # loop because single-dash options can be chained
1408 # (e.g. -xyz is the same as -x -y -z if no args are required)
1409 match_argument = self._match_argument
1410 action_tuples = []
1411 while True:
1412
1413 # if we found no optional action, raise an error
1414 if action is None:
1415 self.error(_('no such option: %s') % option_string)
1416
1417 # if there is an explicit argument, try to match the
1418 # optional's string arguments to only this
1419 if explicit_arg is not None:
1420 arg_count = match_argument(action, 'A')
1421
1422 # if the action is a single-dash option and takes no
1423 # arguments, try to parse more single-dash options out
1424 # of the tail of the option string
1425 chars = self.prefix_chars
1426 if arg_count == 0 and option_string[1] not in chars:
1427 action_tuples.append((action, [], option_string))
1428 parse_optional = self._parse_optional
1429 for char in self.prefix_chars:
1430 option_string = char + explicit_arg
1431 option_tuple = parse_optional(option_string)
1432 if option_tuple[0] is not None:
1433 break
1434 else:
1435 msg = _('ignored explicit argument %r')
1436 raise ArgumentError(action, msg % explicit_arg)
1437
1438 # set the action, etc. for the next loop iteration
1439 action, option_string, explicit_arg = option_tuple
1440
1441 # if the action expect exactly one argument, we've
1442 # successfully matched the option; exit the loop
1443 elif arg_count == 1:
1444 stop = start_index + 1
1445 args = [explicit_arg]
1446 action_tuples.append((action, args, option_string))
1447 break
1448
1449 # error if a double-dash option did not use the
1450 # explicit argument
1451 else:
1452 msg = _('ignored explicit argument %r')
1453 raise ArgumentError(action, msg % explicit_arg)
1454
1455 # if there is no explicit argument, try to match the
1456 # optional's string arguments with the following strings
1457 # if successful, exit the loop
1458 else:
1459 start = start_index + 1
1460 selected_patterns = arg_strings_pattern[start:]
1461 arg_count = match_argument(action, selected_patterns)
1462 stop = start + arg_count
1463 args = arg_strings[start:stop]
1464 action_tuples.append((action, args, option_string))
1465 break
1466
1467 # add the Optional to the list and return the index at which
1468 # the Optional's string args stopped
1469 assert action_tuples
1470 for action, args, option_string in action_tuples:
1471 take_action(action, args, option_string)
1472 return stop
1473
1474 # the list of Positionals left to be parsed; this is modified
1475 # by consume_positionals()
1476 positionals = self._get_positional_actions()
1477
1478 # function to convert arg_strings into positional actions
1479 def consume_positionals(start_index):
1480 # match as many Positionals as possible
1481 match_partial = self._match_arguments_partial
1482 selected_pattern = arg_strings_pattern[start_index:]
1483 arg_counts = match_partial(positionals, selected_pattern)
1484
1485 # slice off the appropriate arg strings for each Positional
1486 # and add the Positional and its args to the list
1487 for action, arg_count in zip(positionals, arg_counts):
1488 args = arg_strings[start_index: start_index + arg_count]
1489 start_index += arg_count
1490 take_action(action, args)
1491
1492 # slice off the Positionals that we just parsed and return the
1493 # index at which the Positionals' string args stopped
1494 positionals[:] = positionals[len(arg_counts):]
1495 return start_index
1496
1497 # consume Positionals and Optionals alternately, until we have
1498 # passed the last option string
1499 start_index = 0
1500 if option_string_indices:
1501 max_option_string_index = max(option_string_indices)
1502 else:
1503 max_option_string_index = -1
1504 while start_index <= max_option_string_index:
1505
1506 # consume any Positionals preceding the next option
1507 next_option_string_index = min(
1508 index
1509 for index in option_string_indices
1510 if index >= start_index)
1511 if start_index != next_option_string_index:
1512 positionals_end_index = consume_positionals(start_index)
1513
1514 # only try to parse the next optional if we didn't consume
1515 # the option string during the positionals parsing
1516 if positionals_end_index > start_index:
1517 start_index = positionals_end_index
1518 continue
1519 else:
1520 start_index = positionals_end_index
1521
1522 # if we consumed all the positionals we could and we're not
1523 # at the index of an option string, there were unparseable
1524 # arguments
1525 if start_index not in option_string_indices:
1526 msg = _('extra arguments found: %s')
1527 extras = arg_strings[start_index:next_option_string_index]
1528 self.error(msg % ' '.join(extras))
1529
1530 # consume the next optional and any arguments for it
1531 start_index = consume_optional(start_index)
1532
1533 # consume any positionals following the last Optional
1534 stop_index = consume_positionals(start_index)
1535
1536 # if we didn't consume all the argument strings, there were too
1537 # many supplied
1538 if stop_index != len(arg_strings):
1539 extras = arg_strings[stop_index:]
1540 self.error(_('extra arguments found: %s') % ' '.join(extras))
1541
1542 # if we didn't use all the Positional objects, there were too few
1543 # arg strings supplied.
1544 if positionals:
1545 self.error(_('too few arguments'))
1546
1547 # return the updated namespace
1548 return namespace
1549
1550 def _match_argument(self, action, arg_strings_pattern):
1551 # match the pattern for this action to the arg strings
1552 nargs_pattern = self._get_nargs_pattern(action)
1553 match = _re.match(nargs_pattern, arg_strings_pattern)
1554
1555 # raise an exception if we weren't able to find a match
1556 if match is None:
1557 nargs_errors = {
1558 None:_('expected one argument'),
1559 OPTIONAL:_('expected at most one argument'),
1560 ONE_OR_MORE:_('expected at least one argument')
1561 }
1562 default = _('expected %s argument(s)') % action.nargs
1563 msg = nargs_errors.get(action.nargs, default)
1564 raise ArgumentError(action, msg)
1565
1566 # return the number of arguments matched
1567 return len(match.group(1))
1568
1569 def _match_arguments_partial(self, actions, arg_strings_pattern):
1570 # progressively shorten the actions list by slicing off the
1571 # final actions until we find a match
1572 result = []
1573 for i in xrange(len(actions), 0, -1):
1574 actions_slice = actions[:i]
1575 pattern = ''.join(self._get_nargs_pattern(action)
1576 for action in actions_slice)
1577 match = _re.match(pattern, arg_strings_pattern)
1578 if match is not None:
1579 result.extend(len(string) for string in match.groups())
1580 break
1581
1582 # return the list of arg string counts
1583 return result
1584
1585 def _parse_optional(self, arg_string):
1586 # if it doesn't start with a prefix, it was meant to be positional
1587 if not arg_string[0] in self.prefix_chars:
1588 return None
1589
1590 # if it's just dashes, it was meant to be positional
1591 if not arg_string.strip('-'):
1592 return None
1593
1594 # if the option string is present in the parser, return the action
1595 if arg_string in self._option_strings:
1596 action = self._option_strings[arg_string]
1597 return action, arg_string, None
1598
1599 # search through all possible prefixes of the option string
1600 # and all actions in the parser for possible interpretations
1601 option_tuples = []
1602 prefix_tuples = self._get_option_prefix_tuples(arg_string)
1603 for option_string in self._option_strings:
1604 for option_prefix, explicit_arg in prefix_tuples:
1605 if option_string.startswith(option_prefix):
1606 action = self._option_strings[option_string]
1607 tup = action, option_string, explicit_arg
1608 option_tuples.append(tup)
1609 break
1610
1611 # if multiple actions match, the option string was ambiguous
1612 if len(option_tuples) > 1:
1613 options = ', '.join(opt_str for _, opt_str, _ in option_tuples)
1614 tup = arg_string, options
1615 self.error(_('ambiguous option: %s could match %s') % tup)
1616
1617 # if exactly one action matched, this segmentation is good,
1618 # so return the parsed action
1619 elif len(option_tuples) == 1:
1620 option_tuple, = option_tuples
1621 return option_tuple
1622
1623 # if it was not found as an option, but it looks like a negative
1624 # number, it was meant to be positional
1625 if self._negative_number_matcher.match(arg_string):
1626 return None
1627
1628 # it was meant to be an optional but there is no such option
1629 # in this parser (though it might be a valid option in a subparser)
1630 return None, arg_string, None
1631
1632 def _get_option_prefix_tuples(self, option_string):
1633 result = []
1634
1635 # option strings starting with two prefix characters are only
1636 # split at the '='
1637 chars = self.prefix_chars
1638 if option_string[0] in chars and option_string[1] in chars:
1639 if '=' in option_string:
1640 option_prefix, explicit_arg = option_string.split('=', 1)
1641 else:
1642 option_prefix = option_string
1643 explicit_arg = None
1644 tup = option_prefix, explicit_arg
1645 result.append(tup)
1646
1647 # option strings starting with a single prefix character are
1648 # split at all indices
1649 else:
1650 for first_index, char in enumerate(option_string):
1651 if char not in self.prefix_chars:
1652 break
1653 for i in xrange(len(option_string), first_index, -1):
1654 tup = option_string[:i], option_string[i:] or None
1655 result.append(tup)
1656
1657 # return the collected prefix tuples
1658 return result
1659
1660 def _get_nargs_pattern(self, action):
1661 # in all examples below, we have to allow for '--' args
1662 # which are represented as '-' in the pattern
1663 nargs = action.nargs
1664
1665 # the default (None) is assumed to be a single argument
1666 if nargs is None:
1667 nargs_pattern = '(-*A-*)'
1668
1669 # allow zero or one arguments
1670 elif nargs == OPTIONAL:
1671 nargs_pattern = '(-*A?-*)'
1672
1673 # allow zero or more arguments
1674 elif nargs == ZERO_OR_MORE:
1675 nargs_pattern = '(-*[A-]*)'
1676
1677 # allow one or more arguments
1678 elif nargs == ONE_OR_MORE:
1679 nargs_pattern = '(-*A[A-]*)'
1680
1681 # allow one argument followed by any number of options or arguments
1682 elif nargs is PARSER:
1683 nargs_pattern = '(-*A[-AO]*)'
1684
1685 # all others should be integers
1686 else:
1687 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
1688
1689 # if this is an optional action, -- is not allowed
1690 if action.option_strings:
1691 nargs_pattern = nargs_pattern.replace('-*', '')
1692 nargs_pattern = nargs_pattern.replace('-', '')
1693
1694 # return the pattern
1695 return nargs_pattern
1696
1697 # ========================
1698 # Value conversion methods
1699 # ========================
1700
1701 def _get_values(self, action, arg_strings):
1702 # for everything but PARSER args, strip out '--'
1703 if action.nargs is not PARSER:
1704 arg_strings = [s for s in arg_strings if s != '--']
1705
1706 # optional argument produces a default when not present
1707 if not arg_strings and action.nargs == OPTIONAL:
1708 if action.option_strings:
1709 value = action.const
1710 else:
1711 value = action.default
1712 if isinstance(value, basestring):
1713 value = self._get_value(action, value)
1714 self._check_value(action, value)
1715
1716 # when nargs='*' on a positional, if there were no command-line
1717 # args, use the default if it is anything other than None
1718 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
1719 not action.option_strings):
1720 if action.default is not None:
1721 value = action.default
1722 else:
1723 value = arg_strings
1724 self._check_value(action, value)
1725
1726 # single argument or optional argument produces a single value
1727 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
1728 arg_string, = arg_strings
1729 value = self._get_value(action, arg_string)
1730 self._check_value(action, value)
1731
1732 # PARSER arguments convert all values, but check only the first
1733 elif action.nargs is PARSER:
1734 value = list(self._get_value(action, v) for v in arg_strings)
1735 self._check_value(action, value[0])
1736
1737 # all other types of nargs produce a list
1738 else:
1739 value = list(self._get_value(action, v) for v in arg_strings)
1740 for v in value:
1741 self._check_value(action, v)
1742
1743 # return the converted value
1744 return value
1745
1746 def _get_value(self, action, arg_string):
1747 type_func = self._registry_get('type', action.type, action.type)
1748 if not callable(type_func):
1749 msg = _('%r is not callable')
1750 raise ArgumentError(action, msg % type_func)
1751
1752 # convert the value to the appropriate type
1753 try:
1754 result = type_func(arg_string)
1755
1756 # TypeErrors or ValueErrors indicate errors
1757 except (TypeError, ValueError):
1758 name = getattr(action.type, '__name__', repr(action.type))
1759 msg = _('invalid %s value: %r')
1760 raise ArgumentError(action, msg % (name, arg_string))
1761
1762 # return the converted value
1763 return result
1764
1765 def _check_value(self, action, value):
1766 # converted value must be one of the choices (if specified)
1767 if action.choices is not None and value not in action.choices:
1768 tup = value, ', '.join(map(repr, action.choices))
1769 msg = _('invalid choice: %r (choose from %s)') % tup
1770 raise ArgumentError(action, msg)
1771
1772
1773
1774 # =======================
1775 # Help-formatting methods
1776 # =======================
1777
1778 def format_usage(self):
1779 formatter = self._get_formatter()
1780 formatter.add_usage(self.usage,
1781 self._get_optional_actions(),
1782 self._get_positional_actions())
1783 return formatter.format_help()
1784
1785 def format_help(self):
1786 formatter = self._get_formatter()
1787
1788 # usage
1789 formatter.add_usage(self.usage,
1790 self._get_optional_actions(),
1791 self._get_positional_actions())
1792
1793 # description
1794 formatter.add_text(self.description)
1795
1796 # positionals
1797 formatter.start_section(_('positional arguments'))
1798 formatter.add_arguments(self._positional_actions_list)
1799 formatter.end_section()
1800
1801 # optionals
1802 formatter.start_section(_('optional arguments'))
1803 formatter.add_arguments(self._optional_actions_list)
1804 formatter.end_section()
1805
1806 # user-defined groups
1807 for argument_group in self._argument_groups:
1808 formatter.start_section(argument_group.title)
1809 formatter.add_text(argument_group.description)
1810 formatter.add_arguments(argument_group._positional_actions_list)
1811 formatter.add_arguments(argument_group._optional_actions_list)
1812 formatter.end_section()
1813
1814 # epilog
1815 formatter.add_text(self.epilog)
1816
1817 # determine help from format above
1818 return formatter.format_help()
1819
1820 def format_version(self):
1821 formatter = self._get_formatter()
1822 formatter.add_text(self.version)
1823 return formatter.format_help()
1824
1825 def _get_formatter(self):
1826 return self.formatter_class(prog=self.prog)
1827
1828 # =====================
1829 # Help-printing methods
1830 # =====================
1831
1832 def print_usage(self, file=None):
1833 self._print_message(self.format_usage(), file)
1834
1835 def print_help(self, file=None):
1836 self._print_message(self.format_help(), file)
1837
1838 def print_version(self, file=None):
1839 self._print_message(self.format_version(), file)
1840
1841 def _print_message(self, message, file=None):
1842 if message:
1843 if file is None:
1844 file = _sys.stderr
1845 file.write(message)
1846
1847
1848 # ===============
1849 # Exiting methods
1850 # ===============
1851
1852 def exit(self, status=0, message=None):
1853 if message:
1854 _sys.stderr.write(message)
1855 _sys.exit(status)
1856
1857 def error(self, message):
1858 """error(message: string)
1859
1860 Prints a usage message incorporating the message to stderr and
1861 exits.
1862
1863 If you override this in a subclass, it should not return -- it
1864 should either exit or raise an exception.
1865 """
1866 self.print_usage(_sys.stderr)
1867 self.exit(2, _('%s: error: %s\n') % (self.prog, message))
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,394 +1,400 b''
1 1
2 2 """ Implementations for various useful completers
3 3
4 4 See Extensions/ipy_stock_completers.py on examples of how to enable a completer,
5 5 but the basic idea is to do:
6 6
7 7 ip.set_hook('complete_command', svn_completer, str_key = 'svn')
8 8
9 9 """
10 10 import IPython.ipapi
11 11 import glob,os,shlex,sys
12 12 import inspect
13 13 from time import time
14 14 from zipimport import zipimporter
15 15 ip = IPython.ipapi.get()
16 16
17 17 try:
18 18 set
19 19 except:
20 20 from sets import Set as set
21 21
22 22 TIMEOUT_STORAGE = 3 #Time in seconds after which the rootmodules will be stored
23 23 TIMEOUT_GIVEUP = 20 #Time in seconds after which we give up
24 24
25 25 def quick_completer(cmd, completions):
26 26 """ Easily create a trivial completer for a command.
27 27
28 28 Takes either a list of completions, or all completions in string
29 29 (that will be split on whitespace)
30 30
31 31 Example::
32 32
33 33 [d:\ipython]|1> import ipy_completers
34 34 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
35 35 [d:\ipython]|3> foo b<TAB>
36 36 bar baz
37 37 [d:\ipython]|3> foo ba
38 38 """
39 39 if isinstance(completions, basestring):
40 40
41 41 completions = completions.split()
42 42 def do_complete(self,event):
43 43 return completions
44 44
45 45 ip.set_hook('complete_command',do_complete, str_key = cmd)
46 46
47 47 def getRootModules():
48 48 """
49 49 Returns a list containing the names of all the modules available in the
50 50 folders of the pythonpath.
51 51 """
52 52 modules = []
53 53 if ip.db.has_key('rootmodules'):
54 54 return ip.db['rootmodules']
55 55 t = time()
56 56 store = False
57 57 for path in sys.path:
58 58 modules += moduleList(path)
59 59 if time() - t >= TIMEOUT_STORAGE and not store:
60 60 store = True
61 61 print "\nCaching the list of root modules, please wait!"
62 62 print "(This will only be done once - type '%rehashx' to " + \
63 63 "reset cache!)"
64 64 print
65 65 if time() - t > TIMEOUT_GIVEUP:
66 66 print "This is taking too long, we give up."
67 67 print
68 68 ip.db['rootmodules'] = []
69 69 return []
70 70
71 71 modules += sys.builtin_module_names
72 72
73 73 modules = list(set(modules))
74 74 if '__init__' in modules:
75 75 modules.remove('__init__')
76 76 modules = list(set(modules))
77 77 if store:
78 78 ip.db['rootmodules'] = modules
79 79 return modules
80 80
81 81 def moduleList(path):
82 82 """
83 83 Return the list containing the names of the modules available in the given
84 84 folder.
85 85 """
86 86
87 87 if os.path.isdir(path):
88 88 folder_list = os.listdir(path)
89 89 elif path.endswith('.egg'):
90 90 try:
91 91 folder_list = [f for f in zipimporter(path)._files]
92 92 except:
93 93 folder_list = []
94 94 else:
95 95 folder_list = []
96 96 #folder_list = glob.glob(os.path.join(path,'*'))
97 97 folder_list = [p for p in folder_list \
98 98 if os.path.exists(os.path.join(path, p,'__init__.py'))\
99 99 or p[-3:] in ('.py','.so')\
100 100 or p[-4:] in ('.pyc','.pyo','.pyd')]
101 101
102 102 folder_list = [os.path.basename(p).split('.')[0] for p in folder_list]
103 103 return folder_list
104 104
105 105 def moduleCompletion(line):
106 106 """
107 107 Returns a list containing the completion possibilities for an import line.
108 108 The line looks like this :
109 109 'import xml.d'
110 110 'from xml.dom import'
111 111 """
112 112 def tryImport(mod, only_modules=False):
113 113 def isImportable(module, attr):
114 114 if only_modules:
115 115 return inspect.ismodule(getattr(module, attr))
116 116 else:
117 117 return not(attr[:2] == '__' and attr[-2:] == '__')
118 118 try:
119 119 m = __import__(mod)
120 120 except:
121 121 return []
122 122 mods = mod.split('.')
123 123 for module in mods[1:]:
124 124 m = getattr(m,module)
125 125 if (not hasattr(m, '__file__')) or (not only_modules) or\
126 126 (hasattr(m, '__file__') and '__init__' in m.__file__):
127 127 completion_list = [attr for attr in dir(m) if isImportable(m, attr)]
128 128 completion_list.extend(getattr(m,'__all__',[]))
129 129 if hasattr(m, '__file__') and '__init__' in m.__file__:
130 130 completion_list.extend(moduleList(os.path.dirname(m.__file__)))
131 131 completion_list = list(set(completion_list))
132 132 if '__init__' in completion_list:
133 133 completion_list.remove('__init__')
134 134 return completion_list
135 135
136 136 words = line.split(' ')
137 137 if len(words) == 3 and words[0] == 'from':
138 138 return ['import ']
139 139 if len(words) < 3 and (words[0] in ['import','from']) :
140 140 if len(words) == 1:
141 141 return getRootModules()
142 142 mod = words[1].split('.')
143 143 if len(mod) < 2:
144 144 return getRootModules()
145 145 completion_list = tryImport('.'.join(mod[:-1]), True)
146 146 completion_list = ['.'.join(mod[:-1] + [el]) for el in completion_list]
147 147 return completion_list
148 148 if len(words) >= 3 and words[0] == 'from':
149 149 mod = words[1]
150 150 return tryImport(mod)
151 151
152 152 def vcs_completer(commands, event):
153 153 """ utility to make writing typical version control app completers easier
154 154
155 155 VCS command line apps typically have the format:
156 156
157 157 [sudo ]PROGNAME [help] [command] file file...
158 158
159 159 """
160 160
161 161
162 162 cmd_param = event.line.split()
163 163 if event.line.endswith(' '):
164 164 cmd_param.append('')
165 165
166 166 if cmd_param[0] == 'sudo':
167 167 cmd_param = cmd_param[1:]
168 168
169 169 if len(cmd_param) == 2 or 'help' in cmd_param:
170 170 return commands.split()
171 171
172 172 return ip.IP.Completer.file_matches(event.symbol)
173 173
174 174
175 175 pkg_cache = None
176 176
177 177 def module_completer(self,event):
178 178 """ Give completions after user has typed 'import ...' or 'from ...'"""
179 179
180 180 # This works in all versions of python. While 2.5 has
181 181 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
182 182 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
183 183 # of possibly problematic side effects.
184 184 # This search the folders in the sys.path for available modules.
185 185
186 186 return moduleCompletion(event.line)
187 187
188 188
189 189 svn_commands = """\
190 190 add blame praise annotate ann cat checkout co cleanup commit ci copy
191 191 cp delete del remove rm diff di export help ? h import info list ls
192 192 lock log merge mkdir move mv rename ren propdel pdel pd propedit pedit
193 193 pe propget pget pg proplist plist pl propset pset ps resolved revert
194 194 status stat st switch sw unlock update
195 195 """
196 196
197 197 def svn_completer(self,event):
198 198 return vcs_completer(svn_commands, event)
199 199
200 200
201 201 hg_commands = """
202 202 add addremove annotate archive backout branch branches bundle cat
203 203 clone commit copy diff export grep heads help identify import incoming
204 204 init locate log manifest merge outgoing parents paths pull push
205 205 qapplied qclone qcommit qdelete qdiff qfold qguard qheader qimport
206 206 qinit qnew qnext qpop qprev qpush qrefresh qrename qrestore qsave
207 207 qselect qseries qtop qunapplied recover remove rename revert rollback
208 208 root serve showconfig status strip tag tags tip unbundle update verify
209 209 version
210 210 """
211 211
212 212 def hg_completer(self,event):
213 213 """ Completer for mercurial commands """
214 214
215 215 return vcs_completer(hg_commands, event)
216 216
217 217
218 218
219 219 __bzr_commands = None
220 220
221 221 def bzr_commands():
222 222 global __bzr_commands
223 223 if __bzr_commands is not None:
224 224 return __bzr_commands
225 225 out = os.popen('bzr help commands')
226 226 __bzr_commands = [l.split()[0] for l in out]
227 227 return __bzr_commands
228 228
229 229 def bzr_completer(self,event):
230 230 """ Completer for bazaar commands """
231 231 cmd_param = event.line.split()
232 232 if event.line.endswith(' '):
233 233 cmd_param.append('')
234 234
235 235 if len(cmd_param) > 2:
236 236 cmd = cmd_param[1]
237 237 param = cmd_param[-1]
238 238 output_file = (param == '--output=')
239 239 if cmd == 'help':
240 240 return bzr_commands()
241 241 elif cmd in ['bundle-revisions','conflicts',
242 242 'deleted','nick','register-branch',
243 243 'serve','unbind','upgrade','version',
244 244 'whoami'] and not output_file:
245 245 return []
246 246 else:
247 247 # the rest are probably file names
248 248 return ip.IP.Completer.file_matches(event.symbol)
249 249
250 250 return bzr_commands()
251 251
252 252
253 253 def shlex_split(x):
254 254 """Helper function to split lines into segments."""
255 255 #shlex.split raise exception if syntax error in sh syntax
256 256 #for example if no closing " is found. This function keeps dropping
257 257 #the last character of the line until shlex.split does not raise
258 258 #exception. Adds end of the line to the result of shlex.split
259 259 #example: %run "c:/python -> ['%run','"c:/python']
260 260 endofline=[]
261 261 while x!="":
262 262 try:
263 263 comps=shlex.split(x)
264 264 if len(endofline)>=1:
265 265 comps.append("".join(endofline))
266 266 return comps
267 267 except ValueError:
268 268 endofline=[x[-1:]]+endofline
269 269 x=x[:-1]
270 270 return ["".join(endofline)]
271 271
272 272 def runlistpy(self, event):
273 273 comps = shlex_split(event.line)
274 274 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
275 275
276 276 #print "\nev=",event # dbg
277 277 #print "rp=",relpath # dbg
278 278 #print 'comps=',comps # dbg
279 279
280 280 lglob = glob.glob
281 281 isdir = os.path.isdir
282 282 if relpath.startswith('~'):
283 283 relpath = os.path.expanduser(relpath)
284 284 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*')
285 285 if isdir(f)]
286 286
287 287 # Find if the user has already typed the first filename, after which we
288 288 # should complete on all files, since after the first one other files may
289 289 # be arguments to the input script.
290 290 #filter(
291 291 if filter(lambda f: f.endswith('.py') or f.endswith('.ipy') or
292 292 f.endswith('.pyw'),comps):
293 293 pys = [f.replace('\\','/') for f in lglob('*')]
294 294 else:
295 295 pys = [f.replace('\\','/')
296 296 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
297 297 lglob(relpath + '*.pyw')]
298 298 return dirs + pys
299 299
300 300
301 301 greedy_cd_completer = False
302 302
303 303 def cd_completer(self, event):
304 304 relpath = event.symbol
305 305 #print event # dbg
306 306 if '-b' in event.line:
307 307 # return only bookmark completions
308 308 bkms = self.db.get('bookmarks',{})
309 309 return bkms.keys()
310 310
311 311
312 312 if event.symbol == '-':
313 313 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
314 314 # jump in directory history by number
315 315 fmt = '-%0' + width_dh +'d [%s]'
316 316 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
317 317 if len(ents) > 1:
318 318 return ents
319 319 return []
320 320
321 321 if event.symbol.startswith('--'):
322 322 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
323 323
324 324 if relpath.startswith('~'):
325 325 relpath = os.path.expanduser(relpath).replace('\\','/')
326 326 found = []
327 327 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
328 328 if os.path.isdir(f)]:
329 329 if ' ' in d:
330 330 # we don't want to deal with any of that, complex code
331 331 # for this is elsewhere
332 332 raise IPython.ipapi.TryNext
333 333 found.append( d )
334 334
335 335 if not found:
336 336 if os.path.isdir(relpath):
337 337 return [relpath]
338 # if no completions so far, try bookmarks
339 bks = self.db.get('bookmarks',{}).keys()
340 bkmatches = [s for s in bks if s.startswith(event.symbol)]
341 if bkmatches:
342 return bkmatches
343
338 344 raise IPython.ipapi.TryNext
339 345
340 346
341 347 def single_dir_expand(matches):
342 348 "Recursively expand match lists containing a single dir."
343 349
344 350 if len(matches) == 1 and os.path.isdir(matches[0]):
345 351 # Takes care of links to directories also. Use '/'
346 352 # explicitly, even under Windows, so that name completions
347 353 # don't end up escaped.
348 354 d = matches[0]
349 355 if d[-1] in ['/','\\']:
350 356 d = d[:-1]
351 357
352 358 subdirs = [p for p in os.listdir(d) if os.path.isdir( d + '/' + p) and not p.startswith('.')]
353 359 if subdirs:
354 360 matches = [ (d + '/' + p) for p in subdirs ]
355 361 return single_dir_expand(matches)
356 362 else:
357 363 return matches
358 364 else:
359 365 return matches
360 366
361 367 if greedy_cd_completer:
362 368 return single_dir_expand(found)
363 369 else:
364 370 return found
365 371
366 372 def apt_get_packages(prefix):
367 373 out = os.popen('apt-cache pkgnames')
368 374 for p in out:
369 375 if p.startswith(prefix):
370 376 yield p.rstrip()
371 377
372 378
373 379 apt_commands = """\
374 380 update upgrade install remove purge source build-dep dist-upgrade
375 381 dselect-upgrade clean autoclean check"""
376 382
377 383 def apt_completer(self, event):
378 384 """ Completer for apt-get (uses apt-cache internally)
379 385
380 386 """
381 387
382 388
383 389 cmd_param = event.line.split()
384 390 if event.line.endswith(' '):
385 391 cmd_param.append('')
386 392
387 393 if cmd_param[0] == 'sudo':
388 394 cmd_param = cmd_param[1:]
389 395
390 396 if len(cmd_param) == 2 or 'help' in cmd_param:
391 397 return apt_commands.split()
392 398
393 399 return list(apt_get_packages(event.symbol))
394 400
@@ -1,84 +1,88 b''
1 1 """ 'editor' hooks for common editors that work well with ipython
2 2
3 3 They should honor the line number argument, at least.
4 4
5 5 Contributions are *very* welcome.
6 6 """
7 7
8 8 import IPython.ipapi
9 9 ip = IPython.ipapi.get()
10 10
11 11 from IPython.Itpl import itplns
12 12 import os
13 13
14 14 def install_editor(run_template, wait = False):
15 15 """ Gets a template in format "myeditor bah bah $file bah bah $line"
16 16
17 17 $file will be replaced by file name, $line by line number (or 0).
18 18 Installs the editor that is called by IPython, instead of the default
19 19 notepad or vi.
20 20
21 21 If wait is true, wait until the user presses enter before returning,
22 22 to facilitate non-blocking editors that exit immediately after
23 23 the call.
24 24 """
25 25
26 26 def call_editor(self, file, line=0):
27 27 if line is None:
28 28 line = 0
29 29 cmd = itplns(run_template, locals())
30 30 print ">",cmd
31 os.system(cmd)
31 if os.system(cmd) != 0:
32 raise IPython.ipapi.TryNext()
32 33 if wait:
33 34 raw_input("Press Enter when done editing:")
34 35
35 36 ip.set_hook('editor',call_editor)
36 37
37 38
38 39 # in these, exe is always the path/name of the executable. Useful
39 40 # if you don't have the editor directory in your path
40 41
41 42 def komodo(exe = 'komodo'):
42 43 """ Activestate Komodo [Edit] """
43 44 install_editor(exe + ' -l $line "$file"', wait = True)
44 45
45 46 def scite(exe = "scite"):
46 47 """ SciTE or Sc1 """
47 48 install_editor(exe + ' "$file" -goto:$line')
48 49
49 50 def notepadplusplus(exe = 'notepad++'):
50 51 """ Notepad++ http://notepad-plus.sourceforge.net """
51 52 install_editor(exe + ' -n$line "$file"')
52 53
53 54 def jed(exe = 'jed'):
54 55 """ JED, the lightweight emacsish editor """
55 56 install_editor(exe + ' +$line "$file"')
56 57
57 58 def idle(exe = None):
58 59 """ Idle, the editor bundled with python
59 60
60 61 Should be pretty smart about finding the executable.
61 62 """
62 63 if exe is None:
63 64 import idlelib
64 65 p = os.path.dirname(idlelib.__file__)
65 66 exe = p + '/idle.py'
66 67 install_editor(exe + ' "$file"')
67
68
69 def mate(exe = 'mate'):
70 """ TextMate, the missing editor"""
71 install_editor(exe + ' -w -l $line "$file"')
68 72
69 73 # these are untested, report any problems
70 74
71 75 def emacs(exe = 'emacs'):
72 76 install_editor(exe + ' +$line "$file"')
73 77
74 78 def gnuclient(exe= 'gnuclient'):
75 79 install_editor(exe + ' -nw +$line "$file"')
76 80
77 81 def crimson_editor(exe = 'cedt.exe'):
78 82 install_editor(exe + ' /L:$line "$file"')
79 83
80 84 def kate(exe = 'kate'):
81 85 install_editor(exe + ' -u -l $line "$file"')
82 86
83 87
84 88 No newline at end of file
@@ -1,258 +1,270 b''
1 1 """Shell mode for IPython.
2 2
3 3 Start ipython in shell mode by invoking "ipython -p sh"
4 4
5 5 (the old version, "ipython -p pysh" still works but this is the more "modern"
6 6 shell mode and is recommended for users who don't care about pysh-mode
7 7 compatibility)
8 8 """
9 9
10 10 from IPython import ipapi
11 import os,textwrap
11 import os,re,textwrap
12 12
13 13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
14 14 # so consider yourself warned!
15 15
16 16 import ipy_defaults
17 17
18 18 def main():
19 19 ip = ipapi.get()
20 20 o = ip.options
21 21 # autocall to "full" mode (smart mode is default, I like full mode)
22 22
23 23 o.autocall = 2
24 24
25 25 # Jason Orendorff's path class is handy to have in user namespace
26 26 # if you are doing shell-like stuff
27 27 try:
28 28 ip.ex("from IPython.external.path import path" )
29 29 except ImportError:
30 30 pass
31 31
32 32 # beefed up %env is handy in shell mode
33 33 import envpersist
34 34
35 35 # To see where mycmd resides (in path/aliases), do %which mycmd
36 36 import ipy_which
37 37
38 38 # tab completers for hg, svn, ...
39 39 import ipy_app_completers
40 40
41 41 # To make executables foo and bar in mybin usable without PATH change, do:
42 42 # %rehashdir c:/mybin
43 43 # %store foo
44 44 # %store bar
45 45 import ipy_rehashdir
46 46
47 47 # does not work without subprocess module!
48 48 #import ipy_signals
49 49
50 50 ip.ex('import os')
51 51 ip.ex("def up(): os.chdir('..')")
52 52 ip.user_ns['LA'] = LastArgFinder()
53 # Nice prompt
54 53
55 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
54 # You can assign to _prompt_title variable
55 # to provide some extra information for prompt
56 # (e.g. the current mode, host/username...)
57
58 ip.user_ns['_prompt_title'] = ''
59
60 # Nice prompt
61 o.prompt_in1= r'\C_Green${_prompt_title}\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
56 62 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> '
57 63 o.prompt_out= '<\#> '
58 64
59 65 from IPython import Release
60 66
61 67 import sys
62 68 # Non-chatty banner
63 69 o.banner = "IPython %s [on Py %s]\n" % (Release.version,sys.version.split(None,1)[0])
64 70
65 71
66 72 ip.IP.default_option('cd','-q')
67 73 ip.IP.default_option('macro', '-r')
68 74 # If you only rarely want to execute the things you %edit...
69 75 #ip.IP.default_option('edit','-x')
70 76
71 77
72 78 o.prompts_pad_left="1"
73 79 # Remove all blank lines in between prompts, like a normal shell.
74 80 o.separate_in="0"
75 81 o.separate_out="0"
76 82 o.separate_out2="0"
77 83
78 84 # now alias all syscommands
79 85
80 86 db = ip.db
81 87
82 88 syscmds = db.get("syscmdlist",[] )
83 89 if not syscmds:
84 90 print textwrap.dedent("""
85 91 System command list not initialized, probably the first run...
86 92 running %rehashx to refresh the command list. Run %rehashx
87 93 again to refresh command list (after installing new software etc.)
88 94 """)
89 95 ip.magic('rehashx')
90 96 syscmds = db.get("syscmdlist")
91 97
92 98 # lowcase aliases on win32 only
93 99 if os.name == 'posix':
94 100 mapper = lambda s:s
95 101 else:
96 102 def mapper(s): return s.lower()
97 103
98 104 for cmd in syscmds:
99 105 # print "sys",cmd #dbg
100 106 noext, ext = os.path.splitext(cmd)
101 key = mapper(noext)
107 if ext.lower() == '.exe':
108 cmd = noext
109
110 key = mapper(cmd)
102 111 if key not in ip.IP.alias_table:
103 ip.defalias(key, cmd)
112 # Dots will be removed from alias names, since ipython
113 # assumes names with dots to be python code
114
115 ip.defalias(key.replace('.',''), cmd)
104 116
105 117 # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more
106 118 ip.load("IPython.external.mglob")
107 119
108 120 # win32 is crippled w/o cygwin, try to help it a little bit
109 121 if sys.platform == 'win32':
110 122 if 'cygwin' in os.environ['PATH'].lower():
111 123 # use the colors of cygwin ls (recommended)
112 124 ip.defalias('d', 'ls -F --color=auto')
113 125 else:
114 126 # get icp, imv, imkdir, igrep, irm,...
115 127 ip.load('ipy_fsops')
116 128
117 129 # and the next best thing to real 'ls -F'
118 130 ip.defalias('d','dir /w /og /on')
119 131
120 ip.set_hook('input_prefilter', dotslash_prefilter_f)
132 ip.set_hook('input_prefilter', slash_prefilter_f)
121 133 extend_shell_behavior(ip)
122 134
123 135 class LastArgFinder:
124 136 """ Allow $LA to work as "last argument of previous command", like $! in bash
125 137
126 138 To call this in normal IPython code, do LA()
127 139 """
128 140 def __call__(self, hist_idx = None):
129 141 ip = ipapi.get()
130 142 if hist_idx is None:
131 143 return str(self)
132 144 return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
133 145 def __str__(self):
134 146 ip = ipapi.get()
135 147 for cmd in reversed(ip.IP.input_hist_raw):
136 148 parts = cmd.strip().split()
137 149 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
138 150 continue
139 151 return parts[-1]
140 152 return ""
141 153
142 def dotslash_prefilter_f(self,line):
143 """ ./foo now runs foo as system command
154 def slash_prefilter_f(self,line):
155 """ ./foo, ~/foo and /bin/foo now run foo as system command
144 156
145 Removes the need for doing !./foo
157 Removes the need for doing !./foo, !~/foo or !/bin/foo
146 158 """
147 159 import IPython.genutils
148 if line.startswith("./"):
160 if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line):
149 161 return "_ip.system(" + IPython.genutils.make_quoted_expr(line)+")"
150 162 raise ipapi.TryNext
151 163
152 164 # XXX You do not need to understand the next function!
153 165 # This should probably be moved out of profile
154 166
155 167 def extend_shell_behavior(ip):
156 168
157 169 # Instead of making signature a global variable tie it to IPSHELL.
158 170 # In future if it is required to distinguish between different
159 171 # shells we can assign a signature per shell basis
160 172 ip.IP.__sig__ = 0xa005
161 173 # mark the IPSHELL with this signature
162 174 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
163 175
164 176 from IPython.Itpl import ItplNS
165 177 from IPython.genutils import shell
166 178 # utility to expand user variables via Itpl
167 179 # xxx do something sensible with depth?
168 180 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
169 181 str(ItplNS(cmd, ip.IP.user_ns, get_locals()))
170 182
171 183 def get_locals():
172 184 """ Substituting a variable through Itpl deep inside the IPSHELL stack
173 185 requires the knowledge of all the variables in scope upto the last
174 186 IPSHELL frame. This routine simply merges all the local variables
175 187 on the IPSHELL stack without worrying about their scope rules
176 188 """
177 189 import sys
178 190 # note lambda expression constitues a function call
179 191 # hence fno should be incremented by one
180 192 getsig = lambda fno: sys._getframe(fno+1).f_globals \
181 193 ['__builtins__'].__dict__['__sig__']
182 194 getlvars = lambda fno: sys._getframe(fno+1).f_locals
183 195 # trackback until we enter the IPSHELL
184 196 frame_no = 1
185 197 sig = ip.IP.__sig__
186 198 fsig = ~sig
187 199 while fsig != sig :
188 200 try:
189 201 fsig = getsig(frame_no)
190 202 except (AttributeError, KeyError):
191 203 frame_no += 1
192 204 except ValueError:
193 205 # stack is depleted
194 206 # call did not originate from IPSHELL
195 207 return {}
196 208 first_frame = frame_no
197 209 # walk further back until we exit from IPSHELL or deplete stack
198 210 try:
199 211 while(sig == getsig(frame_no+1)):
200 212 frame_no += 1
201 213 except (AttributeError, KeyError, ValueError):
202 214 pass
203 215 # merge the locals from top down hence overriding
204 216 # any re-definitions of variables, functions etc.
205 217 lvars = {}
206 218 for fno in range(frame_no, first_frame-1, -1):
207 219 lvars.update(getlvars(fno))
208 220 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
209 221 return lvars
210 222
211 223 def _runlines(lines):
212 224 """Run a string of one or more lines of source.
213 225
214 226 This method is capable of running a string containing multiple source
215 227 lines, as if they had been entered at the IPython prompt. Since it
216 228 exposes IPython's processing machinery, the given strings can contain
217 229 magic calls (%magic), special shell access (!cmd), etc."""
218 230
219 231 # We must start with a clean buffer, in case this is run from an
220 232 # interactive IPython session (via a magic, for example).
221 233 ip.IP.resetbuffer()
222 234 lines = lines.split('\n')
223 235 more = 0
224 236 command = ''
225 237 for line in lines:
226 238 # skip blank lines so we don't mess up the prompt counter, but do
227 239 # NOT skip even a blank line if we are in a code block (more is
228 240 # true)
229 241 # if command is not empty trim the line
230 242 if command != '' :
231 243 line = line.strip()
232 244 # add the broken line to the command
233 245 if line and line[-1] == '\\' :
234 246 command += line[0:-1] + ' '
235 247 more = True
236 248 continue
237 249 else :
238 250 # add the last (current) line to the command
239 251 command += line
240 252 if command or more:
241 253 # push to raw history, so hist line numbers stay in sync
242 254 ip.IP.input_hist_raw.append("# " + command + "\n")
243 255
244 256 more = ip.IP.push(ip.IP.prefilter(command,more))
245 257 command = ''
246 258 # IPython's runsource returns None if there was an error
247 259 # compiling the code. This allows us to stop processing right
248 260 # away, so the user gets the error message at the right place.
249 261 if more is None:
250 262 break
251 263 # final newline in case the input didn't have it, so that the code
252 264 # actually does get executed
253 265 if more:
254 266 ip.IP.push('\n')
255 267
256 268 ip.IP.runlines = _runlines
257 269
258 270 main()
@@ -1,3377 +1,3405 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 4 $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 import textwrap
35 35 from cStringIO import StringIO
36 36 from getopt import getopt,GetoptError
37 37 from pprint import pprint, pformat
38 38 from sets import Set
39 39
40 40 # cProfile was added in Python2.5
41 41 try:
42 42 import cProfile as profile
43 43 import pstats
44 44 except ImportError:
45 45 # profile isn't bundled by default in Debian for license reasons
46 46 try:
47 47 import profile,pstats
48 48 except ImportError:
49 49 profile = pstats = None
50 50
51 51 # Homebrewed
52 52 import IPython
53 53 from IPython import Debugger, OInspect, wildcard
54 54 from IPython.FakeModule import FakeModule
55 55 from IPython.Itpl import Itpl, itpl, printpl,itplns
56 56 from IPython.PyColorize import Parser
57 57 from IPython.ipstruct import Struct
58 58 from IPython.macro import Macro
59 59 from IPython.genutils import *
60 60 from IPython import platutils
61 61 import IPython.generics
62 62 import IPython.ipapi
63 63 from IPython.ipapi import UsageError
64 64 from IPython.testing import decorators as testdec
65 65
66 66 #***************************************************************************
67 67 # Utility functions
68 68 def on_off(tag):
69 69 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 70 return ['OFF','ON'][tag]
71 71
72 72 class Bunch: pass
73 73
74 74 def compress_dhist(dh):
75 75 head, tail = dh[:-10], dh[-10:]
76 76
77 77 newhead = []
78 78 done = Set()
79 79 for h in head:
80 80 if h in done:
81 81 continue
82 82 newhead.append(h)
83 83 done.add(h)
84 84
85 85 return newhead + tail
86 86
87 87
88 88 #***************************************************************************
89 89 # Main class implementing Magic functionality
90 90 class Magic:
91 91 """Magic functions for InteractiveShell.
92 92
93 93 Shell functions which can be reached as %function_name. All magic
94 94 functions should accept a string, which they can parse for their own
95 95 needs. This can make some functions easier to type, eg `%cd ../`
96 96 vs. `%cd("../")`
97 97
98 98 ALL definitions MUST begin with the prefix magic_. The user won't need it
99 99 at the command line, but it is is needed in the definition. """
100 100
101 101 # class globals
102 102 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
103 103 'Automagic is ON, % prefix NOT needed for magic functions.']
104 104
105 105 #......................................................................
106 106 # some utility functions
107 107
108 108 def __init__(self,shell):
109 109
110 110 self.options_table = {}
111 111 if profile is None:
112 112 self.magic_prun = self.profile_missing_notice
113 113 self.shell = shell
114 114
115 115 # namespace for holding state we may need
116 116 self._magic_state = Bunch()
117 117
118 118 def profile_missing_notice(self, *args, **kwargs):
119 119 error("""\
120 120 The profile module could not be found. It has been removed from the standard
121 121 python packages because of its non-free license. To use profiling, install the
122 122 python-profiler package from non-free.""")
123 123
124 124 def default_option(self,fn,optstr):
125 125 """Make an entry in the options_table for fn, with value optstr"""
126 126
127 127 if fn not in self.lsmagic():
128 128 error("%s is not a magic function" % fn)
129 129 self.options_table[fn] = optstr
130 130
131 131 def lsmagic(self):
132 132 """Return a list of currently available magic functions.
133 133
134 134 Gives a list of the bare names after mangling (['ls','cd', ...], not
135 135 ['magic_ls','magic_cd',...]"""
136 136
137 137 # FIXME. This needs a cleanup, in the way the magics list is built.
138 138
139 139 # magics in class definition
140 140 class_magic = lambda fn: fn.startswith('magic_') and \
141 141 callable(Magic.__dict__[fn])
142 142 # in instance namespace (run-time user additions)
143 143 inst_magic = lambda fn: fn.startswith('magic_') and \
144 144 callable(self.__dict__[fn])
145 145 # and bound magics by user (so they can access self):
146 146 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
147 147 callable(self.__class__.__dict__[fn])
148 148 magics = filter(class_magic,Magic.__dict__.keys()) + \
149 149 filter(inst_magic,self.__dict__.keys()) + \
150 150 filter(inst_bound_magic,self.__class__.__dict__.keys())
151 151 out = []
152 152 for fn in Set(magics):
153 153 out.append(fn.replace('magic_','',1))
154 154 out.sort()
155 155 return out
156 156
157 157 def extract_input_slices(self,slices,raw=False):
158 158 """Return as a string a set of input history slices.
159 159
160 160 Inputs:
161 161
162 162 - slices: the set of slices is given as a list of strings (like
163 163 ['1','4:8','9'], since this function is for use by magic functions
164 164 which get their arguments as strings.
165 165
166 166 Optional inputs:
167 167
168 168 - raw(False): by default, the processed input is used. If this is
169 169 true, the raw input history is used instead.
170 170
171 171 Note that slices can be called with two notations:
172 172
173 173 N:M -> standard python form, means including items N...(M-1).
174 174
175 175 N-M -> include items N..M (closed endpoint)."""
176 176
177 177 if raw:
178 178 hist = self.shell.input_hist_raw
179 179 else:
180 180 hist = self.shell.input_hist
181 181
182 182 cmds = []
183 183 for chunk in slices:
184 184 if ':' in chunk:
185 185 ini,fin = map(int,chunk.split(':'))
186 186 elif '-' in chunk:
187 187 ini,fin = map(int,chunk.split('-'))
188 188 fin += 1
189 189 else:
190 190 ini = int(chunk)
191 191 fin = ini+1
192 192 cmds.append(hist[ini:fin])
193 193 return cmds
194 194
195 195 def _ofind(self, oname, namespaces=None):
196 196 """Find an object in the available namespaces.
197 197
198 198 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
199 199
200 200 Has special code to detect magic functions.
201 201 """
202 202
203 203 oname = oname.strip()
204 204
205 205 alias_ns = None
206 206 if namespaces is None:
207 207 # Namespaces to search in:
208 208 # Put them in a list. The order is important so that we
209 209 # find things in the same order that Python finds them.
210 210 namespaces = [ ('Interactive', self.shell.user_ns),
211 211 ('IPython internal', self.shell.internal_ns),
212 212 ('Python builtin', __builtin__.__dict__),
213 213 ('Alias', self.shell.alias_table),
214 214 ]
215 215 alias_ns = self.shell.alias_table
216 216
217 217 # initialize results to 'null'
218 218 found = 0; obj = None; ospace = None; ds = None;
219 219 ismagic = 0; isalias = 0; parent = None
220 220
221 221 # Look for the given name by splitting it in parts. If the head is
222 222 # found, then we look for all the remaining parts as members, and only
223 223 # declare success if we can find them all.
224 224 oname_parts = oname.split('.')
225 225 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
226 226 for nsname,ns in namespaces:
227 227 try:
228 228 obj = ns[oname_head]
229 229 except KeyError:
230 230 continue
231 231 else:
232 232 #print 'oname_rest:', oname_rest # dbg
233 233 for part in oname_rest:
234 234 try:
235 235 parent = obj
236 236 obj = getattr(obj,part)
237 237 except:
238 238 # Blanket except b/c some badly implemented objects
239 239 # allow __getattr__ to raise exceptions other than
240 240 # AttributeError, which then crashes IPython.
241 241 break
242 242 else:
243 243 # If we finish the for loop (no break), we got all members
244 244 found = 1
245 245 ospace = nsname
246 246 if ns == alias_ns:
247 247 isalias = 1
248 248 break # namespace loop
249 249
250 250 # Try to see if it's magic
251 251 if not found:
252 252 if oname.startswith(self.shell.ESC_MAGIC):
253 253 oname = oname[1:]
254 254 obj = getattr(self,'magic_'+oname,None)
255 255 if obj is not None:
256 256 found = 1
257 257 ospace = 'IPython internal'
258 258 ismagic = 1
259 259
260 260 # Last try: special-case some literals like '', [], {}, etc:
261 261 if not found and oname_head in ["''",'""','[]','{}','()']:
262 262 obj = eval(oname_head)
263 263 found = 1
264 264 ospace = 'Interactive'
265 265
266 266 return {'found':found, 'obj':obj, 'namespace':ospace,
267 267 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
268 268
269 269 def arg_err(self,func):
270 270 """Print docstring if incorrect arguments were passed"""
271 271 print 'Error in arguments:'
272 272 print OInspect.getdoc(func)
273 273
274 274 def format_latex(self,strng):
275 275 """Format a string for latex inclusion."""
276 276
277 277 # Characters that need to be escaped for latex:
278 278 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
279 279 # Magic command names as headers:
280 280 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
281 281 re.MULTILINE)
282 282 # Magic commands
283 283 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
284 284 re.MULTILINE)
285 285 # Paragraph continue
286 286 par_re = re.compile(r'\\$',re.MULTILINE)
287 287
288 288 # The "\n" symbol
289 289 newline_re = re.compile(r'\\n')
290 290
291 291 # Now build the string for output:
292 292 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
293 293 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
294 294 strng)
295 295 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
296 296 strng = par_re.sub(r'\\\\',strng)
297 297 strng = escape_re.sub(r'\\\1',strng)
298 298 strng = newline_re.sub(r'\\textbackslash{}n',strng)
299 299 return strng
300 300
301 301 def format_screen(self,strng):
302 302 """Format a string for screen printing.
303 303
304 304 This removes some latex-type format codes."""
305 305 # Paragraph continue
306 306 par_re = re.compile(r'\\$',re.MULTILINE)
307 307 strng = par_re.sub('',strng)
308 308 return strng
309 309
310 310 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
311 311 """Parse options passed to an argument string.
312 312
313 313 The interface is similar to that of getopt(), but it returns back a
314 314 Struct with the options as keys and the stripped argument string still
315 315 as a string.
316 316
317 317 arg_str is quoted as a true sys.argv vector by using shlex.split.
318 318 This allows us to easily expand variables, glob files, quote
319 319 arguments, etc.
320 320
321 321 Options:
322 322 -mode: default 'string'. If given as 'list', the argument string is
323 323 returned as a list (split on whitespace) instead of a string.
324 324
325 325 -list_all: put all option values in lists. Normally only options
326 326 appearing more than once are put in a list.
327 327
328 328 -posix (True): whether to split the input line in POSIX mode or not,
329 329 as per the conventions outlined in the shlex module from the
330 330 standard library."""
331 331
332 332 # inject default options at the beginning of the input line
333 333 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
334 334 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
335 335
336 336 mode = kw.get('mode','string')
337 337 if mode not in ['string','list']:
338 338 raise ValueError,'incorrect mode given: %s' % mode
339 339 # Get options
340 340 list_all = kw.get('list_all',0)
341 341 posix = kw.get('posix',True)
342 342
343 343 # Check if we have more than one argument to warrant extra processing:
344 344 odict = {} # Dictionary with options
345 345 args = arg_str.split()
346 346 if len(args) >= 1:
347 347 # If the list of inputs only has 0 or 1 thing in it, there's no
348 348 # need to look for options
349 349 argv = arg_split(arg_str,posix)
350 350 # Do regular option processing
351 351 try:
352 352 opts,args = getopt(argv,opt_str,*long_opts)
353 353 except GetoptError,e:
354 354 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
355 355 " ".join(long_opts)))
356 356 for o,a in opts:
357 357 if o.startswith('--'):
358 358 o = o[2:]
359 359 else:
360 360 o = o[1:]
361 361 try:
362 362 odict[o].append(a)
363 363 except AttributeError:
364 364 odict[o] = [odict[o],a]
365 365 except KeyError:
366 366 if list_all:
367 367 odict[o] = [a]
368 368 else:
369 369 odict[o] = a
370 370
371 371 # Prepare opts,args for return
372 372 opts = Struct(odict)
373 373 if mode == 'string':
374 374 args = ' '.join(args)
375 375
376 376 return opts,args
377 377
378 378 #......................................................................
379 379 # And now the actual magic functions
380 380
381 381 # Functions for IPython shell work (vars,funcs, config, etc)
382 382 def magic_lsmagic(self, parameter_s = ''):
383 383 """List currently available magic functions."""
384 384 mesc = self.shell.ESC_MAGIC
385 385 print 'Available magic functions:\n'+mesc+\
386 386 (' '+mesc).join(self.lsmagic())
387 387 print '\n' + Magic.auto_status[self.shell.rc.automagic]
388 388 return None
389 389
390 390 def magic_magic(self, parameter_s = ''):
391 391 """Print information about the magic function system.
392 392
393 393 Supported formats: -latex, -brief, -rest
394 394 """
395 395
396 396 mode = ''
397 397 try:
398 398 if parameter_s.split()[0] == '-latex':
399 399 mode = 'latex'
400 400 if parameter_s.split()[0] == '-brief':
401 401 mode = 'brief'
402 402 if parameter_s.split()[0] == '-rest':
403 403 mode = 'rest'
404 404 rest_docs = []
405 405 except:
406 406 pass
407 407
408 408 magic_docs = []
409 409 for fname in self.lsmagic():
410 410 mname = 'magic_' + fname
411 411 for space in (Magic,self,self.__class__):
412 412 try:
413 413 fn = space.__dict__[mname]
414 414 except KeyError:
415 415 pass
416 416 else:
417 417 break
418 418 if mode == 'brief':
419 419 # only first line
420 420 if fn.__doc__:
421 421 fndoc = fn.__doc__.split('\n',1)[0]
422 422 else:
423 423 fndoc = 'No documentation'
424 424 else:
425 fndoc = fn.__doc__.rstrip()
425 if fn.__doc__:
426 fndoc = fn.__doc__.rstrip()
427 else:
428 fndoc = 'No documentation'
429
426 430
427 431 if mode == 'rest':
428 432 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
429 433 fname,fndoc))
430 434
431 435 else:
432 436 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
433 437 fname,fndoc))
434 438
435 439 magic_docs = ''.join(magic_docs)
436 440
437 441 if mode == 'rest':
438 442 return "".join(rest_docs)
439 443
440 444 if mode == 'latex':
441 445 print self.format_latex(magic_docs)
442 446 return
443 447 else:
444 448 magic_docs = self.format_screen(magic_docs)
445 449 if mode == 'brief':
446 450 return magic_docs
447 451
448 452 outmsg = """
449 453 IPython's 'magic' functions
450 454 ===========================
451 455
452 456 The magic function system provides a series of functions which allow you to
453 457 control the behavior of IPython itself, plus a lot of system-type
454 458 features. All these functions are prefixed with a % character, but parameters
455 459 are given without parentheses or quotes.
456 460
457 461 NOTE: If you have 'automagic' enabled (via the command line option or with the
458 462 %automagic function), you don't need to type in the % explicitly. By default,
459 463 IPython ships with automagic on, so you should only rarely need the % escape.
460 464
461 465 Example: typing '%cd mydir' (without the quotes) changes you working directory
462 466 to 'mydir', if it exists.
463 467
464 468 You can define your own magic functions to extend the system. See the supplied
465 469 ipythonrc and example-magic.py files for details (in your ipython
466 470 configuration directory, typically $HOME/.ipython/).
467 471
468 472 You can also define your own aliased names for magic functions. In your
469 473 ipythonrc file, placing a line like:
470 474
471 475 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
472 476
473 477 will define %pf as a new name for %profile.
474 478
475 479 You can also call magics in code using the ipmagic() function, which IPython
476 480 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
477 481
478 482 For a list of the available magic functions, use %lsmagic. For a description
479 483 of any of them, type %magic_name?, e.g. '%cd?'.
480 484
481 485 Currently the magic system has the following functions:\n"""
482 486
483 487 mesc = self.shell.ESC_MAGIC
484 488 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
485 489 "\n\n%s%s\n\n%s" % (outmsg,
486 490 magic_docs,mesc,mesc,
487 491 (' '+mesc).join(self.lsmagic()),
488 492 Magic.auto_status[self.shell.rc.automagic] ) )
489 493
490 494 page(outmsg,screen_lines=self.shell.rc.screen_length)
491 495
492 496
493 497 def magic_autoindent(self, parameter_s = ''):
494 498 """Toggle autoindent on/off (if available)."""
495 499
496 500 self.shell.set_autoindent()
497 501 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
498 502
499 503
500 504 def magic_automagic(self, parameter_s = ''):
501 505 """Make magic functions callable without having to type the initial %.
502 506
503 507 Without argumentsl toggles on/off (when off, you must call it as
504 508 %automagic, of course). With arguments it sets the value, and you can
505 509 use any of (case insensitive):
506 510
507 511 - on,1,True: to activate
508 512
509 513 - off,0,False: to deactivate.
510 514
511 515 Note that magic functions have lowest priority, so if there's a
512 516 variable whose name collides with that of a magic fn, automagic won't
513 517 work for that function (you get the variable instead). However, if you
514 518 delete the variable (del var), the previously shadowed magic function
515 519 becomes visible to automagic again."""
516 520
517 521 rc = self.shell.rc
518 522 arg = parameter_s.lower()
519 523 if parameter_s in ('on','1','true'):
520 524 rc.automagic = True
521 525 elif parameter_s in ('off','0','false'):
522 526 rc.automagic = False
523 527 else:
524 528 rc.automagic = not rc.automagic
525 529 print '\n' + Magic.auto_status[rc.automagic]
526 530
527 531 @testdec.skip_doctest
528 532 def magic_autocall(self, parameter_s = ''):
529 533 """Make functions callable without having to type parentheses.
530 534
531 535 Usage:
532 536
533 537 %autocall [mode]
534 538
535 539 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
536 540 value is toggled on and off (remembering the previous state).
537 541
538 542 In more detail, these values mean:
539 543
540 544 0 -> fully disabled
541 545
542 546 1 -> active, but do not apply if there are no arguments on the line.
543 547
544 548 In this mode, you get:
545 549
546 550 In [1]: callable
547 551 Out[1]: <built-in function callable>
548 552
549 553 In [2]: callable 'hello'
550 554 ------> callable('hello')
551 555 Out[2]: False
552 556
553 557 2 -> Active always. Even if no arguments are present, the callable
554 558 object is called:
555 559
556 560 In [2]: float
557 561 ------> float()
558 562 Out[2]: 0.0
559 563
560 564 Note that even with autocall off, you can still use '/' at the start of
561 565 a line to treat the first argument on the command line as a function
562 566 and add parentheses to it:
563 567
564 568 In [8]: /str 43
565 569 ------> str(43)
566 570 Out[8]: '43'
567 571
568 572 # all-random (note for auto-testing)
569 573 """
570 574
571 575 rc = self.shell.rc
572 576
573 577 if parameter_s:
574 578 arg = int(parameter_s)
575 579 else:
576 580 arg = 'toggle'
577 581
578 582 if not arg in (0,1,2,'toggle'):
579 583 error('Valid modes: (0->Off, 1->Smart, 2->Full')
580 584 return
581 585
582 586 if arg in (0,1,2):
583 587 rc.autocall = arg
584 588 else: # toggle
585 589 if rc.autocall:
586 590 self._magic_state.autocall_save = rc.autocall
587 591 rc.autocall = 0
588 592 else:
589 593 try:
590 594 rc.autocall = self._magic_state.autocall_save
591 595 except AttributeError:
592 596 rc.autocall = self._magic_state.autocall_save = 1
593 597
594 598 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
595 599
596 600 def magic_system_verbose(self, parameter_s = ''):
597 601 """Set verbose printing of system calls.
598 602
599 603 If called without an argument, act as a toggle"""
600 604
601 605 if parameter_s:
602 606 val = bool(eval(parameter_s))
603 607 else:
604 608 val = None
605 609
606 610 self.shell.rc_set_toggle('system_verbose',val)
607 611 print "System verbose printing is:",\
608 612 ['OFF','ON'][self.shell.rc.system_verbose]
609 613
610 614
611 615 def magic_page(self, parameter_s=''):
612 616 """Pretty print the object and display it through a pager.
613 617
614 618 %page [options] OBJECT
615 619
616 620 If no object is given, use _ (last output).
617 621
618 622 Options:
619 623
620 624 -r: page str(object), don't pretty-print it."""
621 625
622 626 # After a function contributed by Olivier Aubert, slightly modified.
623 627
624 628 # Process options/args
625 629 opts,args = self.parse_options(parameter_s,'r')
626 630 raw = 'r' in opts
627 631
628 632 oname = args and args or '_'
629 633 info = self._ofind(oname)
630 634 if info['found']:
631 635 txt = (raw and str or pformat)( info['obj'] )
632 636 page(txt)
633 637 else:
634 638 print 'Object `%s` not found' % oname
635 639
636 640 def magic_profile(self, parameter_s=''):
637 641 """Print your currently active IPyhton profile."""
638 642 if self.shell.rc.profile:
639 643 printpl('Current IPython profile: $self.shell.rc.profile.')
640 644 else:
641 645 print 'No profile active.'
642 646
643 647 def magic_pinfo(self, parameter_s='', namespaces=None):
644 648 """Provide detailed information about an object.
645 649
646 650 '%pinfo object' is just a synonym for object? or ?object."""
647 651
648 652 #print 'pinfo par: <%s>' % parameter_s # dbg
649 653
650 654
651 655 # detail_level: 0 -> obj? , 1 -> obj??
652 656 detail_level = 0
653 657 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 658 # happen if the user types 'pinfo foo?' at the cmd line.
655 659 pinfo,qmark1,oname,qmark2 = \
656 660 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 661 if pinfo or qmark1 or qmark2:
658 662 detail_level = 1
659 663 if "*" in oname:
660 664 self.magic_psearch(oname)
661 665 else:
662 666 self._inspect('pinfo', oname, detail_level=detail_level,
663 667 namespaces=namespaces)
664 668
665 669 def magic_pdef(self, parameter_s='', namespaces=None):
666 670 """Print the definition header for any callable object.
667 671
668 672 If the object is a class, print the constructor information."""
669 673 self._inspect('pdef',parameter_s, namespaces)
670 674
671 675 def magic_pdoc(self, parameter_s='', namespaces=None):
672 676 """Print the docstring for an object.
673 677
674 678 If the given object is a class, it will print both the class and the
675 679 constructor docstrings."""
676 680 self._inspect('pdoc',parameter_s, namespaces)
677 681
678 682 def magic_psource(self, parameter_s='', namespaces=None):
679 683 """Print (or run through pager) the source code for an object."""
680 684 self._inspect('psource',parameter_s, namespaces)
681 685
682 686 def magic_pfile(self, parameter_s=''):
683 687 """Print (or run through pager) the file where an object is defined.
684 688
685 689 The file opens at the line where the object definition begins. IPython
686 690 will honor the environment variable PAGER if set, and otherwise will
687 691 do its best to print the file in a convenient form.
688 692
689 693 If the given argument is not an object currently defined, IPython will
690 694 try to interpret it as a filename (automatically adding a .py extension
691 695 if needed). You can thus use %pfile as a syntax highlighting code
692 696 viewer."""
693 697
694 698 # first interpret argument as an object name
695 699 out = self._inspect('pfile',parameter_s)
696 700 # if not, try the input as a filename
697 701 if out == 'not found':
698 702 try:
699 703 filename = get_py_filename(parameter_s)
700 704 except IOError,msg:
701 705 print msg
702 706 return
703 707 page(self.shell.inspector.format(file(filename).read()))
704 708
705 709 def _inspect(self,meth,oname,namespaces=None,**kw):
706 710 """Generic interface to the inspector system.
707 711
708 712 This function is meant to be called by pdef, pdoc & friends."""
709 713
710 714 #oname = oname.strip()
711 715 #print '1- oname: <%r>' % oname # dbg
712 716 try:
713 717 oname = oname.strip().encode('ascii')
714 718 #print '2- oname: <%r>' % oname # dbg
715 719 except UnicodeEncodeError:
716 720 print 'Python identifiers can only contain ascii characters.'
717 721 return 'not found'
718 722
719 723 info = Struct(self._ofind(oname, namespaces))
720 724
721 725 if info.found:
722 726 try:
723 727 IPython.generics.inspect_object(info.obj)
724 728 return
725 729 except IPython.ipapi.TryNext:
726 730 pass
727 731 # Get the docstring of the class property if it exists.
728 732 path = oname.split('.')
729 733 root = '.'.join(path[:-1])
730 734 if info.parent is not None:
731 735 try:
732 736 target = getattr(info.parent, '__class__')
733 737 # The object belongs to a class instance.
734 738 try:
735 739 target = getattr(target, path[-1])
736 740 # The class defines the object.
737 741 if isinstance(target, property):
738 742 oname = root + '.__class__.' + path[-1]
739 743 info = Struct(self._ofind(oname))
740 744 except AttributeError: pass
741 745 except AttributeError: pass
742 746
743 747 pmethod = getattr(self.shell.inspector,meth)
744 748 formatter = info.ismagic and self.format_screen or None
745 749 if meth == 'pdoc':
746 750 pmethod(info.obj,oname,formatter)
747 751 elif meth == 'pinfo':
748 752 pmethod(info.obj,oname,formatter,info,**kw)
749 753 else:
750 754 pmethod(info.obj,oname)
751 755 else:
752 756 print 'Object `%s` not found.' % oname
753 757 return 'not found' # so callers can take other action
754 758
755 759 def magic_psearch(self, parameter_s=''):
756 760 """Search for object in namespaces by wildcard.
757 761
758 762 %psearch [options] PATTERN [OBJECT TYPE]
759 763
760 764 Note: ? can be used as a synonym for %psearch, at the beginning or at
761 765 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
762 766 rest of the command line must be unchanged (options come first), so
763 767 for example the following forms are equivalent
764 768
765 769 %psearch -i a* function
766 770 -i a* function?
767 771 ?-i a* function
768 772
769 773 Arguments:
770 774
771 775 PATTERN
772 776
773 777 where PATTERN is a string containing * as a wildcard similar to its
774 778 use in a shell. The pattern is matched in all namespaces on the
775 779 search path. By default objects starting with a single _ are not
776 780 matched, many IPython generated objects have a single
777 781 underscore. The default is case insensitive matching. Matching is
778 782 also done on the attributes of objects and not only on the objects
779 783 in a module.
780 784
781 785 [OBJECT TYPE]
782 786
783 787 Is the name of a python type from the types module. The name is
784 788 given in lowercase without the ending type, ex. StringType is
785 789 written string. By adding a type here only objects matching the
786 790 given type are matched. Using all here makes the pattern match all
787 791 types (this is the default).
788 792
789 793 Options:
790 794
791 795 -a: makes the pattern match even objects whose names start with a
792 796 single underscore. These names are normally ommitted from the
793 797 search.
794 798
795 799 -i/-c: make the pattern case insensitive/sensitive. If neither of
796 800 these options is given, the default is read from your ipythonrc
797 801 file. The option name which sets this value is
798 802 'wildcards_case_sensitive'. If this option is not specified in your
799 803 ipythonrc file, IPython's internal default is to do a case sensitive
800 804 search.
801 805
802 806 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
803 807 specifiy can be searched in any of the following namespaces:
804 808 'builtin', 'user', 'user_global','internal', 'alias', where
805 809 'builtin' and 'user' are the search defaults. Note that you should
806 810 not use quotes when specifying namespaces.
807 811
808 812 'Builtin' contains the python module builtin, 'user' contains all
809 813 user data, 'alias' only contain the shell aliases and no python
810 814 objects, 'internal' contains objects used by IPython. The
811 815 'user_global' namespace is only used by embedded IPython instances,
812 816 and it contains module-level globals. You can add namespaces to the
813 817 search with -s or exclude them with -e (these options can be given
814 818 more than once).
815 819
816 820 Examples:
817 821
818 822 %psearch a* -> objects beginning with an a
819 823 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
820 824 %psearch a* function -> all functions beginning with an a
821 825 %psearch re.e* -> objects beginning with an e in module re
822 826 %psearch r*.e* -> objects that start with e in modules starting in r
823 827 %psearch r*.* string -> all strings in modules beginning with r
824 828
825 829 Case sensitve search:
826 830
827 831 %psearch -c a* list all object beginning with lower case a
828 832
829 833 Show objects beginning with a single _:
830 834
831 835 %psearch -a _* list objects beginning with a single underscore"""
832 836 try:
833 837 parameter_s = parameter_s.encode('ascii')
834 838 except UnicodeEncodeError:
835 839 print 'Python identifiers can only contain ascii characters.'
836 840 return
837 841
838 842 # default namespaces to be searched
839 843 def_search = ['user','builtin']
840 844
841 845 # Process options/args
842 846 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
843 847 opt = opts.get
844 848 shell = self.shell
845 849 psearch = shell.inspector.psearch
846 850
847 851 # select case options
848 852 if opts.has_key('i'):
849 853 ignore_case = True
850 854 elif opts.has_key('c'):
851 855 ignore_case = False
852 856 else:
853 857 ignore_case = not shell.rc.wildcards_case_sensitive
854 858
855 859 # Build list of namespaces to search from user options
856 860 def_search.extend(opt('s',[]))
857 861 ns_exclude = ns_exclude=opt('e',[])
858 862 ns_search = [nm for nm in def_search if nm not in ns_exclude]
859 863
860 864 # Call the actual search
861 865 try:
862 866 psearch(args,shell.ns_table,ns_search,
863 867 show_all=opt('a'),ignore_case=ignore_case)
864 868 except:
865 869 shell.showtraceback()
866 870
867 871 def magic_who_ls(self, parameter_s=''):
868 872 """Return a sorted list of all interactive variables.
869 873
870 874 If arguments are given, only variables of types matching these
871 875 arguments are returned."""
872 876
873 877 user_ns = self.shell.user_ns
874 878 internal_ns = self.shell.internal_ns
875 879 user_config_ns = self.shell.user_config_ns
876 880 out = []
877 881 typelist = parameter_s.split()
878 882
879 883 for i in user_ns:
880 884 if not (i.startswith('_') or i.startswith('_i')) \
881 885 and not (i in internal_ns or i in user_config_ns):
882 886 if typelist:
883 887 if type(user_ns[i]).__name__ in typelist:
884 888 out.append(i)
885 889 else:
886 890 out.append(i)
887 891 out.sort()
888 892 return out
889 893
890 894 def magic_who(self, parameter_s=''):
891 895 """Print all interactive variables, with some minimal formatting.
892 896
893 897 If any arguments are given, only variables whose type matches one of
894 898 these are printed. For example:
895 899
896 900 %who function str
897 901
898 902 will only list functions and strings, excluding all other types of
899 903 variables. To find the proper type names, simply use type(var) at a
900 904 command line to see how python prints type names. For example:
901 905
902 906 In [1]: type('hello')\\
903 907 Out[1]: <type 'str'>
904 908
905 909 indicates that the type name for strings is 'str'.
906 910
907 911 %who always excludes executed names loaded through your configuration
908 912 file and things which are internal to IPython.
909 913
910 914 This is deliberate, as typically you may load many modules and the
911 915 purpose of %who is to show you only what you've manually defined."""
912 916
913 917 varlist = self.magic_who_ls(parameter_s)
914 918 if not varlist:
915 919 if parameter_s:
916 920 print 'No variables match your requested type.'
917 921 else:
918 922 print 'Interactive namespace is empty.'
919 923 return
920 924
921 925 # if we have variables, move on...
922 926 count = 0
923 927 for i in varlist:
924 928 print i+'\t',
925 929 count += 1
926 930 if count > 8:
927 931 count = 0
928 932 print
929 933 print
930 934
931 935 def magic_whos(self, parameter_s=''):
932 936 """Like %who, but gives some extra information about each variable.
933 937
934 938 The same type filtering of %who can be applied here.
935 939
936 940 For all variables, the type is printed. Additionally it prints:
937 941
938 942 - For {},[],(): their length.
939 943
940 944 - For numpy and Numeric arrays, a summary with shape, number of
941 945 elements, typecode and size in memory.
942 946
943 947 - Everything else: a string representation, snipping their middle if
944 948 too long."""
945 949
946 950 varnames = self.magic_who_ls(parameter_s)
947 951 if not varnames:
948 952 if parameter_s:
949 953 print 'No variables match your requested type.'
950 954 else:
951 955 print 'Interactive namespace is empty.'
952 956 return
953 957
954 958 # if we have variables, move on...
955 959
956 960 # for these types, show len() instead of data:
957 961 seq_types = [types.DictType,types.ListType,types.TupleType]
958 962
959 963 # for numpy/Numeric arrays, display summary info
960 964 try:
961 965 import numpy
962 966 except ImportError:
963 967 ndarray_type = None
964 968 else:
965 969 ndarray_type = numpy.ndarray.__name__
966 970 try:
967 971 import Numeric
968 972 except ImportError:
969 973 array_type = None
970 974 else:
971 975 array_type = Numeric.ArrayType.__name__
972 976
973 977 # Find all variable names and types so we can figure out column sizes
974 978 def get_vars(i):
975 979 return self.shell.user_ns[i]
976 980
977 981 # some types are well known and can be shorter
978 982 abbrevs = {'IPython.macro.Macro' : 'Macro'}
979 983 def type_name(v):
980 984 tn = type(v).__name__
981 985 return abbrevs.get(tn,tn)
982 986
983 987 varlist = map(get_vars,varnames)
984 988
985 989 typelist = []
986 990 for vv in varlist:
987 991 tt = type_name(vv)
988 992
989 993 if tt=='instance':
990 994 typelist.append( abbrevs.get(str(vv.__class__),
991 995 str(vv.__class__)))
992 996 else:
993 997 typelist.append(tt)
994 998
995 999 # column labels and # of spaces as separator
996 1000 varlabel = 'Variable'
997 1001 typelabel = 'Type'
998 1002 datalabel = 'Data/Info'
999 1003 colsep = 3
1000 1004 # variable format strings
1001 1005 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1002 1006 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1003 1007 aformat = "%s: %s elems, type `%s`, %s bytes"
1004 1008 # find the size of the columns to format the output nicely
1005 1009 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1006 1010 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1007 1011 # table header
1008 1012 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1009 1013 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1010 1014 # and the table itself
1011 1015 kb = 1024
1012 1016 Mb = 1048576 # kb**2
1013 1017 for vname,var,vtype in zip(varnames,varlist,typelist):
1014 1018 print itpl(vformat),
1015 1019 if vtype in seq_types:
1016 1020 print len(var)
1017 1021 elif vtype in [array_type,ndarray_type]:
1018 1022 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1019 1023 if vtype==ndarray_type:
1020 1024 # numpy
1021 1025 vsize = var.size
1022 1026 vbytes = vsize*var.itemsize
1023 1027 vdtype = var.dtype
1024 1028 else:
1025 1029 # Numeric
1026 1030 vsize = Numeric.size(var)
1027 1031 vbytes = vsize*var.itemsize()
1028 1032 vdtype = var.typecode()
1029 1033
1030 1034 if vbytes < 100000:
1031 1035 print aformat % (vshape,vsize,vdtype,vbytes)
1032 1036 else:
1033 1037 print aformat % (vshape,vsize,vdtype,vbytes),
1034 1038 if vbytes < Mb:
1035 1039 print '(%s kb)' % (vbytes/kb,)
1036 1040 else:
1037 1041 print '(%s Mb)' % (vbytes/Mb,)
1038 1042 else:
1039 1043 try:
1040 1044 vstr = str(var)
1041 1045 except UnicodeEncodeError:
1042 1046 vstr = unicode(var).encode(sys.getdefaultencoding(),
1043 1047 'backslashreplace')
1044 1048 vstr = vstr.replace('\n','\\n')
1045 1049 if len(vstr) < 50:
1046 1050 print vstr
1047 1051 else:
1048 1052 printpl(vfmt_short)
1049 1053
1050 1054 def magic_reset(self, parameter_s=''):
1051 1055 """Resets the namespace by removing all names defined by the user.
1052 1056
1053 1057 Input/Output history are left around in case you need them."""
1054 1058
1055 1059 ans = self.shell.ask_yes_no(
1056 1060 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1057 1061 if not ans:
1058 1062 print 'Nothing done.'
1059 1063 return
1060 1064 user_ns = self.shell.user_ns
1061 1065 for i in self.magic_who_ls():
1062 1066 del(user_ns[i])
1063 1067
1064 1068 # Also flush the private list of module references kept for script
1065 1069 # execution protection
1066 1070 self.shell._user_main_modules[:] = []
1067 1071
1068 1072 def magic_logstart(self,parameter_s=''):
1069 1073 """Start logging anywhere in a session.
1070 1074
1071 1075 %logstart [-o|-r|-t] [log_name [log_mode]]
1072 1076
1073 1077 If no name is given, it defaults to a file named 'ipython_log.py' in your
1074 1078 current directory, in 'rotate' mode (see below).
1075 1079
1076 1080 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1077 1081 history up to that point and then continues logging.
1078 1082
1079 1083 %logstart takes a second optional parameter: logging mode. This can be one
1080 1084 of (note that the modes are given unquoted):\\
1081 1085 append: well, that says it.\\
1082 1086 backup: rename (if exists) to name~ and start name.\\
1083 1087 global: single logfile in your home dir, appended to.\\
1084 1088 over : overwrite existing log.\\
1085 1089 rotate: create rotating logs name.1~, name.2~, etc.
1086 1090
1087 1091 Options:
1088 1092
1089 1093 -o: log also IPython's output. In this mode, all commands which
1090 1094 generate an Out[NN] prompt are recorded to the logfile, right after
1091 1095 their corresponding input line. The output lines are always
1092 1096 prepended with a '#[Out]# ' marker, so that the log remains valid
1093 1097 Python code.
1094 1098
1095 1099 Since this marker is always the same, filtering only the output from
1096 1100 a log is very easy, using for example a simple awk call:
1097 1101
1098 1102 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1099 1103
1100 1104 -r: log 'raw' input. Normally, IPython's logs contain the processed
1101 1105 input, so that user lines are logged in their final form, converted
1102 1106 into valid Python. For example, %Exit is logged as
1103 1107 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1104 1108 exactly as typed, with no transformations applied.
1105 1109
1106 1110 -t: put timestamps before each input line logged (these are put in
1107 1111 comments)."""
1108 1112
1109 1113 opts,par = self.parse_options(parameter_s,'ort')
1110 1114 log_output = 'o' in opts
1111 1115 log_raw_input = 'r' in opts
1112 1116 timestamp = 't' in opts
1113 1117
1114 1118 rc = self.shell.rc
1115 1119 logger = self.shell.logger
1116 1120
1117 1121 # if no args are given, the defaults set in the logger constructor by
1118 1122 # ipytohn remain valid
1119 1123 if par:
1120 1124 try:
1121 1125 logfname,logmode = par.split()
1122 1126 except:
1123 1127 logfname = par
1124 1128 logmode = 'backup'
1125 1129 else:
1126 1130 logfname = logger.logfname
1127 1131 logmode = logger.logmode
1128 1132 # put logfname into rc struct as if it had been called on the command
1129 1133 # line, so it ends up saved in the log header Save it in case we need
1130 1134 # to restore it...
1131 1135 old_logfile = rc.opts.get('logfile','')
1132 1136 if logfname:
1133 1137 logfname = os.path.expanduser(logfname)
1134 1138 rc.opts.logfile = logfname
1135 1139 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1136 1140 try:
1137 1141 started = logger.logstart(logfname,loghead,logmode,
1138 1142 log_output,timestamp,log_raw_input)
1139 1143 except:
1140 1144 rc.opts.logfile = old_logfile
1141 1145 warn("Couldn't start log: %s" % sys.exc_info()[1])
1142 1146 else:
1143 1147 # log input history up to this point, optionally interleaving
1144 1148 # output if requested
1145 1149
1146 1150 if timestamp:
1147 1151 # disable timestamping for the previous history, since we've
1148 1152 # lost those already (no time machine here).
1149 1153 logger.timestamp = False
1150 1154
1151 1155 if log_raw_input:
1152 1156 input_hist = self.shell.input_hist_raw
1153 1157 else:
1154 1158 input_hist = self.shell.input_hist
1155 1159
1156 1160 if log_output:
1157 1161 log_write = logger.log_write
1158 1162 output_hist = self.shell.output_hist
1159 1163 for n in range(1,len(input_hist)-1):
1160 1164 log_write(input_hist[n].rstrip())
1161 1165 if n in output_hist:
1162 1166 log_write(repr(output_hist[n]),'output')
1163 1167 else:
1164 1168 logger.log_write(input_hist[1:])
1165 1169 if timestamp:
1166 1170 # re-enable timestamping
1167 1171 logger.timestamp = True
1168 1172
1169 1173 print ('Activating auto-logging. '
1170 1174 'Current session state plus future input saved.')
1171 1175 logger.logstate()
1172 1176
1173 1177 def magic_logstop(self,parameter_s=''):
1174 1178 """Fully stop logging and close log file.
1175 1179
1176 1180 In order to start logging again, a new %logstart call needs to be made,
1177 1181 possibly (though not necessarily) with a new filename, mode and other
1178 1182 options."""
1179 1183 self.logger.logstop()
1180 1184
1181 1185 def magic_logoff(self,parameter_s=''):
1182 1186 """Temporarily stop logging.
1183 1187
1184 1188 You must have previously started logging."""
1185 1189 self.shell.logger.switch_log(0)
1186 1190
1187 1191 def magic_logon(self,parameter_s=''):
1188 1192 """Restart logging.
1189 1193
1190 1194 This function is for restarting logging which you've temporarily
1191 1195 stopped with %logoff. For starting logging for the first time, you
1192 1196 must use the %logstart function, which allows you to specify an
1193 1197 optional log filename."""
1194 1198
1195 1199 self.shell.logger.switch_log(1)
1196 1200
1197 1201 def magic_logstate(self,parameter_s=''):
1198 1202 """Print the status of the logging system."""
1199 1203
1200 1204 self.shell.logger.logstate()
1201 1205
1202 1206 def magic_pdb(self, parameter_s=''):
1203 1207 """Control the automatic calling of the pdb interactive debugger.
1204 1208
1205 1209 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1206 1210 argument it works as a toggle.
1207 1211
1208 1212 When an exception is triggered, IPython can optionally call the
1209 1213 interactive pdb debugger after the traceback printout. %pdb toggles
1210 1214 this feature on and off.
1211 1215
1212 1216 The initial state of this feature is set in your ipythonrc
1213 1217 configuration file (the variable is called 'pdb').
1214 1218
1215 1219 If you want to just activate the debugger AFTER an exception has fired,
1216 1220 without having to type '%pdb on' and rerunning your code, you can use
1217 1221 the %debug magic."""
1218 1222
1219 1223 par = parameter_s.strip().lower()
1220 1224
1221 1225 if par:
1222 1226 try:
1223 1227 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1224 1228 except KeyError:
1225 1229 print ('Incorrect argument. Use on/1, off/0, '
1226 1230 'or nothing for a toggle.')
1227 1231 return
1228 1232 else:
1229 1233 # toggle
1230 1234 new_pdb = not self.shell.call_pdb
1231 1235
1232 1236 # set on the shell
1233 1237 self.shell.call_pdb = new_pdb
1234 1238 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1235 1239
1236 1240 def magic_debug(self, parameter_s=''):
1237 1241 """Activate the interactive debugger in post-mortem mode.
1238 1242
1239 1243 If an exception has just occurred, this lets you inspect its stack
1240 1244 frames interactively. Note that this will always work only on the last
1241 1245 traceback that occurred, so you must call this quickly after an
1242 1246 exception that you wish to inspect has fired, because if another one
1243 1247 occurs, it clobbers the previous one.
1244 1248
1245 1249 If you want IPython to automatically do this on every exception, see
1246 1250 the %pdb magic for more details.
1247 1251 """
1248 1252
1249 1253 self.shell.debugger(force=True)
1250 1254
1251 1255 @testdec.skip_doctest
1252 1256 def magic_prun(self, parameter_s ='',user_mode=1,
1253 1257 opts=None,arg_lst=None,prog_ns=None):
1254 1258
1255 1259 """Run a statement through the python code profiler.
1256 1260
1257 1261 Usage:
1258 1262 %prun [options] statement
1259 1263
1260 1264 The given statement (which doesn't require quote marks) is run via the
1261 1265 python profiler in a manner similar to the profile.run() function.
1262 1266 Namespaces are internally managed to work correctly; profile.run
1263 1267 cannot be used in IPython because it makes certain assumptions about
1264 1268 namespaces which do not hold under IPython.
1265 1269
1266 1270 Options:
1267 1271
1268 1272 -l <limit>: you can place restrictions on what or how much of the
1269 1273 profile gets printed. The limit value can be:
1270 1274
1271 1275 * A string: only information for function names containing this string
1272 1276 is printed.
1273 1277
1274 1278 * An integer: only these many lines are printed.
1275 1279
1276 1280 * A float (between 0 and 1): this fraction of the report is printed
1277 1281 (for example, use a limit of 0.4 to see the topmost 40% only).
1278 1282
1279 1283 You can combine several limits with repeated use of the option. For
1280 1284 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1281 1285 information about class constructors.
1282 1286
1283 1287 -r: return the pstats.Stats object generated by the profiling. This
1284 1288 object has all the information about the profile in it, and you can
1285 1289 later use it for further analysis or in other functions.
1286 1290
1287 1291 -s <key>: sort profile by given key. You can provide more than one key
1288 1292 by using the option several times: '-s key1 -s key2 -s key3...'. The
1289 1293 default sorting key is 'time'.
1290 1294
1291 1295 The following is copied verbatim from the profile documentation
1292 1296 referenced below:
1293 1297
1294 1298 When more than one key is provided, additional keys are used as
1295 1299 secondary criteria when the there is equality in all keys selected
1296 1300 before them.
1297 1301
1298 1302 Abbreviations can be used for any key names, as long as the
1299 1303 abbreviation is unambiguous. The following are the keys currently
1300 1304 defined:
1301 1305
1302 1306 Valid Arg Meaning
1303 1307 "calls" call count
1304 1308 "cumulative" cumulative time
1305 1309 "file" file name
1306 1310 "module" file name
1307 1311 "pcalls" primitive call count
1308 1312 "line" line number
1309 1313 "name" function name
1310 1314 "nfl" name/file/line
1311 1315 "stdname" standard name
1312 1316 "time" internal time
1313 1317
1314 1318 Note that all sorts on statistics are in descending order (placing
1315 1319 most time consuming items first), where as name, file, and line number
1316 1320 searches are in ascending order (i.e., alphabetical). The subtle
1317 1321 distinction between "nfl" and "stdname" is that the standard name is a
1318 1322 sort of the name as printed, which means that the embedded line
1319 1323 numbers get compared in an odd way. For example, lines 3, 20, and 40
1320 1324 would (if the file names were the same) appear in the string order
1321 1325 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1322 1326 line numbers. In fact, sort_stats("nfl") is the same as
1323 1327 sort_stats("name", "file", "line").
1324 1328
1325 1329 -T <filename>: save profile results as shown on screen to a text
1326 1330 file. The profile is still shown on screen.
1327 1331
1328 1332 -D <filename>: save (via dump_stats) profile statistics to given
1329 1333 filename. This data is in a format understod by the pstats module, and
1330 1334 is generated by a call to the dump_stats() method of profile
1331 1335 objects. The profile is still shown on screen.
1332 1336
1333 1337 If you want to run complete programs under the profiler's control, use
1334 1338 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1335 1339 contains profiler specific options as described here.
1336 1340
1337 1341 You can read the complete documentation for the profile module with::
1338 1342
1339 1343 In [1]: import profile; profile.help()
1340 1344 """
1341 1345
1342 1346 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1343 1347 # protect user quote marks
1344 1348 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1345 1349
1346 1350 if user_mode: # regular user call
1347 1351 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1348 1352 list_all=1)
1349 1353 namespace = self.shell.user_ns
1350 1354 else: # called to run a program by %run -p
1351 1355 try:
1352 1356 filename = get_py_filename(arg_lst[0])
1353 1357 except IOError,msg:
1354 1358 error(msg)
1355 1359 return
1356 1360
1357 1361 arg_str = 'execfile(filename,prog_ns)'
1358 1362 namespace = locals()
1359 1363
1360 1364 opts.merge(opts_def)
1361 1365
1362 1366 prof = profile.Profile()
1363 1367 try:
1364 1368 prof = prof.runctx(arg_str,namespace,namespace)
1365 1369 sys_exit = ''
1366 1370 except SystemExit:
1367 1371 sys_exit = """*** SystemExit exception caught in code being profiled."""
1368 1372
1369 1373 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1370 1374
1371 1375 lims = opts.l
1372 1376 if lims:
1373 1377 lims = [] # rebuild lims with ints/floats/strings
1374 1378 for lim in opts.l:
1375 1379 try:
1376 1380 lims.append(int(lim))
1377 1381 except ValueError:
1378 1382 try:
1379 1383 lims.append(float(lim))
1380 1384 except ValueError:
1381 1385 lims.append(lim)
1382 1386
1383 1387 # Trap output.
1384 1388 stdout_trap = StringIO()
1385 1389
1386 1390 if hasattr(stats,'stream'):
1387 1391 # In newer versions of python, the stats object has a 'stream'
1388 1392 # attribute to write into.
1389 1393 stats.stream = stdout_trap
1390 1394 stats.print_stats(*lims)
1391 1395 else:
1392 1396 # For older versions, we manually redirect stdout during printing
1393 1397 sys_stdout = sys.stdout
1394 1398 try:
1395 1399 sys.stdout = stdout_trap
1396 1400 stats.print_stats(*lims)
1397 1401 finally:
1398 1402 sys.stdout = sys_stdout
1399 1403
1400 1404 output = stdout_trap.getvalue()
1401 1405 output = output.rstrip()
1402 1406
1403 1407 page(output,screen_lines=self.shell.rc.screen_length)
1404 1408 print sys_exit,
1405 1409
1406 1410 dump_file = opts.D[0]
1407 1411 text_file = opts.T[0]
1408 1412 if dump_file:
1409 1413 prof.dump_stats(dump_file)
1410 1414 print '\n*** Profile stats marshalled to file',\
1411 1415 `dump_file`+'.',sys_exit
1412 1416 if text_file:
1413 1417 pfile = file(text_file,'w')
1414 1418 pfile.write(output)
1415 1419 pfile.close()
1416 1420 print '\n*** Profile printout saved to text file',\
1417 1421 `text_file`+'.',sys_exit
1418 1422
1419 1423 if opts.has_key('r'):
1420 1424 return stats
1421 1425 else:
1422 1426 return None
1423 1427
1424 1428 @testdec.skip_doctest
1425 1429 def magic_run(self, parameter_s ='',runner=None):
1426 1430 """Run the named file inside IPython as a program.
1427 1431
1428 1432 Usage:\\
1429 1433 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1430 1434
1431 1435 Parameters after the filename are passed as command-line arguments to
1432 1436 the program (put in sys.argv). Then, control returns to IPython's
1433 1437 prompt.
1434 1438
1435 1439 This is similar to running at a system prompt:\\
1436 1440 $ python file args\\
1437 1441 but with the advantage of giving you IPython's tracebacks, and of
1438 1442 loading all variables into your interactive namespace for further use
1439 1443 (unless -p is used, see below).
1440 1444
1441 1445 The file is executed in a namespace initially consisting only of
1442 1446 __name__=='__main__' and sys.argv constructed as indicated. It thus
1443 1447 sees its environment as if it were being run as a stand-alone program
1444 1448 (except for sharing global objects such as previously imported
1445 1449 modules). But after execution, the IPython interactive namespace gets
1446 1450 updated with all variables defined in the program (except for __name__
1447 1451 and sys.argv). This allows for very convenient loading of code for
1448 1452 interactive work, while giving each program a 'clean sheet' to run in.
1449 1453
1450 1454 Options:
1451 1455
1452 1456 -n: __name__ is NOT set to '__main__', but to the running file's name
1453 1457 without extension (as python does under import). This allows running
1454 1458 scripts and reloading the definitions in them without calling code
1455 1459 protected by an ' if __name__ == "__main__" ' clause.
1456 1460
1457 1461 -i: run the file in IPython's namespace instead of an empty one. This
1458 1462 is useful if you are experimenting with code written in a text editor
1459 1463 which depends on variables defined interactively.
1460 1464
1461 1465 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1462 1466 being run. This is particularly useful if IPython is being used to
1463 1467 run unittests, which always exit with a sys.exit() call. In such
1464 1468 cases you are interested in the output of the test results, not in
1465 1469 seeing a traceback of the unittest module.
1466 1470
1467 1471 -t: print timing information at the end of the run. IPython will give
1468 1472 you an estimated CPU time consumption for your script, which under
1469 1473 Unix uses the resource module to avoid the wraparound problems of
1470 1474 time.clock(). Under Unix, an estimate of time spent on system tasks
1471 1475 is also given (for Windows platforms this is reported as 0.0).
1472 1476
1473 1477 If -t is given, an additional -N<N> option can be given, where <N>
1474 1478 must be an integer indicating how many times you want the script to
1475 1479 run. The final timing report will include total and per run results.
1476 1480
1477 1481 For example (testing the script uniq_stable.py):
1478 1482
1479 1483 In [1]: run -t uniq_stable
1480 1484
1481 1485 IPython CPU timings (estimated):\\
1482 1486 User : 0.19597 s.\\
1483 1487 System: 0.0 s.\\
1484 1488
1485 1489 In [2]: run -t -N5 uniq_stable
1486 1490
1487 1491 IPython CPU timings (estimated):\\
1488 1492 Total runs performed: 5\\
1489 1493 Times : Total Per run\\
1490 1494 User : 0.910862 s, 0.1821724 s.\\
1491 1495 System: 0.0 s, 0.0 s.
1492 1496
1493 1497 -d: run your program under the control of pdb, the Python debugger.
1494 1498 This allows you to execute your program step by step, watch variables,
1495 1499 etc. Internally, what IPython does is similar to calling:
1496 1500
1497 1501 pdb.run('execfile("YOURFILENAME")')
1498 1502
1499 1503 with a breakpoint set on line 1 of your file. You can change the line
1500 1504 number for this automatic breakpoint to be <N> by using the -bN option
1501 1505 (where N must be an integer). For example:
1502 1506
1503 1507 %run -d -b40 myscript
1504 1508
1505 1509 will set the first breakpoint at line 40 in myscript.py. Note that
1506 1510 the first breakpoint must be set on a line which actually does
1507 1511 something (not a comment or docstring) for it to stop execution.
1508 1512
1509 1513 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1510 1514 first enter 'c' (without qoutes) to start execution up to the first
1511 1515 breakpoint.
1512 1516
1513 1517 Entering 'help' gives information about the use of the debugger. You
1514 1518 can easily see pdb's full documentation with "import pdb;pdb.help()"
1515 1519 at a prompt.
1516 1520
1517 1521 -p: run program under the control of the Python profiler module (which
1518 1522 prints a detailed report of execution times, function calls, etc).
1519 1523
1520 1524 You can pass other options after -p which affect the behavior of the
1521 1525 profiler itself. See the docs for %prun for details.
1522 1526
1523 1527 In this mode, the program's variables do NOT propagate back to the
1524 1528 IPython interactive namespace (because they remain in the namespace
1525 1529 where the profiler executes them).
1526 1530
1527 1531 Internally this triggers a call to %prun, see its documentation for
1528 1532 details on the options available specifically for profiling.
1529 1533
1530 1534 There is one special usage for which the text above doesn't apply:
1531 1535 if the filename ends with .ipy, the file is run as ipython script,
1532 1536 just as if the commands were written on IPython prompt.
1533 1537 """
1534 1538
1535 1539 # get arguments and set sys.argv for program to be run.
1536 1540 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1537 1541 mode='list',list_all=1)
1538 1542
1539 1543 try:
1540 1544 filename = get_py_filename(arg_lst[0])
1541 1545 except IndexError:
1542 1546 warn('you must provide at least a filename.')
1543 1547 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1544 1548 return
1545 1549 except IOError,msg:
1546 1550 error(msg)
1547 1551 return
1548 1552
1549 1553 if filename.lower().endswith('.ipy'):
1550 1554 self.api.runlines(open(filename).read())
1551 1555 return
1552 1556
1553 1557 # Control the response to exit() calls made by the script being run
1554 1558 exit_ignore = opts.has_key('e')
1555 1559
1556 1560 # Make sure that the running script gets a proper sys.argv as if it
1557 1561 # were run from a system shell.
1558 1562 save_argv = sys.argv # save it for later restoring
1559 1563 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1560 1564
1561 1565 if opts.has_key('i'):
1562 1566 # Run in user's interactive namespace
1563 1567 prog_ns = self.shell.user_ns
1564 1568 __name__save = self.shell.user_ns['__name__']
1565 1569 prog_ns['__name__'] = '__main__'
1566 1570 main_mod = FakeModule(prog_ns)
1567 1571 else:
1568 1572 # Run in a fresh, empty namespace
1569 1573 if opts.has_key('n'):
1570 1574 name = os.path.splitext(os.path.basename(filename))[0]
1571 1575 else:
1572 1576 name = '__main__'
1573 1577 main_mod = FakeModule()
1574 1578 prog_ns = main_mod.__dict__
1575 1579 prog_ns['__name__'] = name
1576 1580 # The shell MUST hold a reference to main_mod so after %run exits,
1577 1581 # the python deletion mechanism doesn't zero it out (leaving
1578 1582 # dangling references)
1579 1583 self.shell._user_main_modules.append(main_mod)
1580 1584
1581 1585 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1582 1586 # set the __file__ global in the script's namespace
1583 1587 prog_ns['__file__'] = filename
1584 1588
1585 1589 # pickle fix. See iplib for an explanation. But we need to make sure
1586 1590 # that, if we overwrite __main__, we replace it at the end
1587 1591 main_mod_name = prog_ns['__name__']
1588 1592
1589 1593 if main_mod_name == '__main__':
1590 1594 restore_main = sys.modules['__main__']
1591 1595 else:
1592 1596 restore_main = False
1593 1597
1594 1598 # This needs to be undone at the end to prevent holding references to
1595 1599 # every single object ever created.
1596 1600 sys.modules[main_mod_name] = main_mod
1597 1601
1598 1602 stats = None
1599 1603 try:
1600 1604 self.shell.savehist()
1601 1605
1602 1606 if opts.has_key('p'):
1603 1607 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1604 1608 else:
1605 1609 if opts.has_key('d'):
1606 1610 deb = Debugger.Pdb(self.shell.rc.colors)
1607 1611 # reset Breakpoint state, which is moronically kept
1608 1612 # in a class
1609 1613 bdb.Breakpoint.next = 1
1610 1614 bdb.Breakpoint.bplist = {}
1611 1615 bdb.Breakpoint.bpbynumber = [None]
1612 1616 # Set an initial breakpoint to stop execution
1613 1617 maxtries = 10
1614 1618 bp = int(opts.get('b',[1])[0])
1615 1619 checkline = deb.checkline(filename,bp)
1616 1620 if not checkline:
1617 1621 for bp in range(bp+1,bp+maxtries+1):
1618 1622 if deb.checkline(filename,bp):
1619 1623 break
1620 1624 else:
1621 1625 msg = ("\nI failed to find a valid line to set "
1622 1626 "a breakpoint\n"
1623 1627 "after trying up to line: %s.\n"
1624 1628 "Please set a valid breakpoint manually "
1625 1629 "with the -b option." % bp)
1626 1630 error(msg)
1627 1631 return
1628 1632 # if we find a good linenumber, set the breakpoint
1629 1633 deb.do_break('%s:%s' % (filename,bp))
1630 1634 # Start file run
1631 1635 print "NOTE: Enter 'c' at the",
1632 1636 print "%s prompt to start your script." % deb.prompt
1633 1637 try:
1634 1638 deb.run('execfile("%s")' % filename,prog_ns)
1635 1639
1636 1640 except:
1637 1641 etype, value, tb = sys.exc_info()
1638 1642 # Skip three frames in the traceback: the %run one,
1639 1643 # one inside bdb.py, and the command-line typed by the
1640 1644 # user (run by exec in pdb itself).
1641 1645 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1642 1646 else:
1643 1647 if runner is None:
1644 1648 runner = self.shell.safe_execfile
1645 1649 if opts.has_key('t'):
1646 1650 # timed execution
1647 1651 try:
1648 1652 nruns = int(opts['N'][0])
1649 1653 if nruns < 1:
1650 1654 error('Number of runs must be >=1')
1651 1655 return
1652 1656 except (KeyError):
1653 1657 nruns = 1
1654 1658 if nruns == 1:
1655 1659 t0 = clock2()
1656 1660 runner(filename,prog_ns,prog_ns,
1657 1661 exit_ignore=exit_ignore)
1658 1662 t1 = clock2()
1659 1663 t_usr = t1[0]-t0[0]
1660 1664 t_sys = t1[1]-t1[1]
1661 1665 print "\nIPython CPU timings (estimated):"
1662 1666 print " User : %10s s." % t_usr
1663 1667 print " System: %10s s." % t_sys
1664 1668 else:
1665 1669 runs = range(nruns)
1666 1670 t0 = clock2()
1667 1671 for nr in runs:
1668 1672 runner(filename,prog_ns,prog_ns,
1669 1673 exit_ignore=exit_ignore)
1670 1674 t1 = clock2()
1671 1675 t_usr = t1[0]-t0[0]
1672 1676 t_sys = t1[1]-t1[1]
1673 1677 print "\nIPython CPU timings (estimated):"
1674 1678 print "Total runs performed:",nruns
1675 1679 print " Times : %10s %10s" % ('Total','Per run')
1676 1680 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1677 1681 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1678 1682
1679 1683 else:
1680 1684 # regular execution
1681 1685 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1682 1686 if opts.has_key('i'):
1683 1687 self.shell.user_ns['__name__'] = __name__save
1684 1688 else:
1685 1689 # update IPython interactive namespace
1686 1690 del prog_ns['__name__']
1687 1691 self.shell.user_ns.update(prog_ns)
1688 1692 finally:
1689 1693 # Ensure key global structures are restored
1690 1694 sys.argv = save_argv
1691 1695 if restore_main:
1692 1696 sys.modules['__main__'] = restore_main
1693 1697 else:
1694 1698 # Remove from sys.modules the reference to main_mod we'd
1695 1699 # added. Otherwise it will trap references to objects
1696 1700 # contained therein.
1697 1701 del sys.modules[main_mod_name]
1698 1702 self.shell.reloadhist()
1699 1703
1700 1704 return stats
1701 1705
1702 1706 def magic_runlog(self, parameter_s =''):
1703 1707 """Run files as logs.
1704 1708
1705 1709 Usage:\\
1706 1710 %runlog file1 file2 ...
1707 1711
1708 1712 Run the named files (treating them as log files) in sequence inside
1709 1713 the interpreter, and return to the prompt. This is much slower than
1710 1714 %run because each line is executed in a try/except block, but it
1711 1715 allows running files with syntax errors in them.
1712 1716
1713 1717 Normally IPython will guess when a file is one of its own logfiles, so
1714 1718 you can typically use %run even for logs. This shorthand allows you to
1715 1719 force any file to be treated as a log file."""
1716 1720
1717 1721 for f in parameter_s.split():
1718 1722 self.shell.safe_execfile(f,self.shell.user_ns,
1719 1723 self.shell.user_ns,islog=1)
1720 1724
1721 1725 @testdec.skip_doctest
1722 1726 def magic_timeit(self, parameter_s =''):
1723 1727 """Time execution of a Python statement or expression
1724 1728
1725 1729 Usage:\\
1726 1730 %timeit [-n<N> -r<R> [-t|-c]] statement
1727 1731
1728 1732 Time execution of a Python statement or expression using the timeit
1729 1733 module.
1730 1734
1731 1735 Options:
1732 1736 -n<N>: execute the given statement <N> times in a loop. If this value
1733 1737 is not given, a fitting value is chosen.
1734 1738
1735 1739 -r<R>: repeat the loop iteration <R> times and take the best result.
1736 1740 Default: 3
1737 1741
1738 1742 -t: use time.time to measure the time, which is the default on Unix.
1739 1743 This function measures wall time.
1740 1744
1741 1745 -c: use time.clock to measure the time, which is the default on
1742 1746 Windows and measures wall time. On Unix, resource.getrusage is used
1743 1747 instead and returns the CPU user time.
1744 1748
1745 1749 -p<P>: use a precision of <P> digits to display the timing result.
1746 1750 Default: 3
1747 1751
1748 1752
1749 1753 Examples:
1750 1754
1751 1755 In [1]: %timeit pass
1752 1756 10000000 loops, best of 3: 53.3 ns per loop
1753 1757
1754 1758 In [2]: u = None
1755 1759
1756 1760 In [3]: %timeit u is None
1757 1761 10000000 loops, best of 3: 184 ns per loop
1758 1762
1759 1763 In [4]: %timeit -r 4 u == None
1760 1764 1000000 loops, best of 4: 242 ns per loop
1761 1765
1762 1766 In [5]: import time
1763 1767
1764 1768 In [6]: %timeit -n1 time.sleep(2)
1765 1769 1 loops, best of 3: 2 s per loop
1766 1770
1767 1771
1768 1772 The times reported by %timeit will be slightly higher than those
1769 1773 reported by the timeit.py script when variables are accessed. This is
1770 1774 due to the fact that %timeit executes the statement in the namespace
1771 1775 of the shell, compared with timeit.py, which uses a single setup
1772 1776 statement to import function or create variables. Generally, the bias
1773 1777 does not matter as long as results from timeit.py are not mixed with
1774 1778 those from %timeit."""
1775 1779
1776 1780 import timeit
1777 1781 import math
1778 1782
1779 1783 units = [u"s", u"ms", u"\xb5s", u"ns"]
1780 1784 scaling = [1, 1e3, 1e6, 1e9]
1781 1785
1782 1786 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1783 1787 posix=False)
1784 1788 if stmt == "":
1785 1789 return
1786 1790 timefunc = timeit.default_timer
1787 1791 number = int(getattr(opts, "n", 0))
1788 1792 repeat = int(getattr(opts, "r", timeit.default_repeat))
1789 1793 precision = int(getattr(opts, "p", 3))
1790 1794 if hasattr(opts, "t"):
1791 1795 timefunc = time.time
1792 1796 if hasattr(opts, "c"):
1793 1797 timefunc = clock
1794 1798
1795 1799 timer = timeit.Timer(timer=timefunc)
1796 1800 # this code has tight coupling to the inner workings of timeit.Timer,
1797 1801 # but is there a better way to achieve that the code stmt has access
1798 1802 # to the shell namespace?
1799 1803
1800 1804 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1801 1805 'setup': "pass"}
1802 1806 # Track compilation time so it can be reported if too long
1803 1807 # Minimum time above which compilation time will be reported
1804 1808 tc_min = 0.1
1805 1809
1806 1810 t0 = clock()
1807 1811 code = compile(src, "<magic-timeit>", "exec")
1808 1812 tc = clock()-t0
1809 1813
1810 1814 ns = {}
1811 1815 exec code in self.shell.user_ns, ns
1812 1816 timer.inner = ns["inner"]
1813 1817
1814 1818 if number == 0:
1815 1819 # determine number so that 0.2 <= total time < 2.0
1816 1820 number = 1
1817 1821 for i in range(1, 10):
1818 1822 number *= 10
1819 1823 if timer.timeit(number) >= 0.2:
1820 1824 break
1821 1825
1822 1826 best = min(timer.repeat(repeat, number)) / number
1823 1827
1824 1828 if best > 0.0:
1825 1829 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1826 1830 else:
1827 1831 order = 3
1828 1832 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1829 1833 precision,
1830 1834 best * scaling[order],
1831 1835 units[order])
1832 1836 if tc > tc_min:
1833 1837 print "Compiler time: %.2f s" % tc
1834 1838
1835 1839 @testdec.skip_doctest
1836 1840 def magic_time(self,parameter_s = ''):
1837 1841 """Time execution of a Python statement or expression.
1838 1842
1839 1843 The CPU and wall clock times are printed, and the value of the
1840 1844 expression (if any) is returned. Note that under Win32, system time
1841 1845 is always reported as 0, since it can not be measured.
1842 1846
1843 1847 This function provides very basic timing functionality. In Python
1844 1848 2.3, the timeit module offers more control and sophistication, so this
1845 1849 could be rewritten to use it (patches welcome).
1846 1850
1847 1851 Some examples:
1848 1852
1849 1853 In [1]: time 2**128
1850 1854 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1851 1855 Wall time: 0.00
1852 1856 Out[1]: 340282366920938463463374607431768211456L
1853 1857
1854 1858 In [2]: n = 1000000
1855 1859
1856 1860 In [3]: time sum(range(n))
1857 1861 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1858 1862 Wall time: 1.37
1859 1863 Out[3]: 499999500000L
1860 1864
1861 1865 In [4]: time print 'hello world'
1862 1866 hello world
1863 1867 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1864 1868 Wall time: 0.00
1865 1869
1866 1870 Note that the time needed by Python to compile the given expression
1867 1871 will be reported if it is more than 0.1s. In this example, the
1868 1872 actual exponentiation is done by Python at compilation time, so while
1869 1873 the expression can take a noticeable amount of time to compute, that
1870 1874 time is purely due to the compilation:
1871 1875
1872 1876 In [5]: time 3**9999;
1873 1877 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1874 1878 Wall time: 0.00 s
1875 1879
1876 1880 In [6]: time 3**999999;
1877 1881 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1878 1882 Wall time: 0.00 s
1879 1883 Compiler : 0.78 s
1880 1884 """
1881 1885
1882 1886 # fail immediately if the given expression can't be compiled
1883 1887
1884 1888 expr = self.shell.prefilter(parameter_s,False)
1885 1889
1886 1890 # Minimum time above which compilation time will be reported
1887 1891 tc_min = 0.1
1888 1892
1889 1893 try:
1890 1894 mode = 'eval'
1891 1895 t0 = clock()
1892 1896 code = compile(expr,'<timed eval>',mode)
1893 1897 tc = clock()-t0
1894 1898 except SyntaxError:
1895 1899 mode = 'exec'
1896 1900 t0 = clock()
1897 1901 code = compile(expr,'<timed exec>',mode)
1898 1902 tc = clock()-t0
1899 1903 # skew measurement as little as possible
1900 1904 glob = self.shell.user_ns
1901 1905 clk = clock2
1902 1906 wtime = time.time
1903 1907 # time execution
1904 1908 wall_st = wtime()
1905 1909 if mode=='eval':
1906 1910 st = clk()
1907 1911 out = eval(code,glob)
1908 1912 end = clk()
1909 1913 else:
1910 1914 st = clk()
1911 1915 exec code in glob
1912 1916 end = clk()
1913 1917 out = None
1914 1918 wall_end = wtime()
1915 1919 # Compute actual times and report
1916 1920 wall_time = wall_end-wall_st
1917 1921 cpu_user = end[0]-st[0]
1918 1922 cpu_sys = end[1]-st[1]
1919 1923 cpu_tot = cpu_user+cpu_sys
1920 1924 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1921 1925 (cpu_user,cpu_sys,cpu_tot)
1922 1926 print "Wall time: %.2f s" % wall_time
1923 1927 if tc > tc_min:
1924 1928 print "Compiler : %.2f s" % tc
1925 1929 return out
1926 1930
1927 1931 @testdec.skip_doctest
1928 1932 def magic_macro(self,parameter_s = ''):
1929 1933 """Define a set of input lines as a macro for future re-execution.
1930 1934
1931 1935 Usage:\\
1932 1936 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1933 1937
1934 1938 Options:
1935 1939
1936 1940 -r: use 'raw' input. By default, the 'processed' history is used,
1937 1941 so that magics are loaded in their transformed version to valid
1938 1942 Python. If this option is given, the raw input as typed as the
1939 1943 command line is used instead.
1940 1944
1941 1945 This will define a global variable called `name` which is a string
1942 1946 made of joining the slices and lines you specify (n1,n2,... numbers
1943 1947 above) from your input history into a single string. This variable
1944 1948 acts like an automatic function which re-executes those lines as if
1945 1949 you had typed them. You just type 'name' at the prompt and the code
1946 1950 executes.
1947 1951
1948 1952 The notation for indicating number ranges is: n1-n2 means 'use line
1949 1953 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1950 1954 using the lines numbered 5,6 and 7.
1951 1955
1952 1956 Note: as a 'hidden' feature, you can also use traditional python slice
1953 1957 notation, where N:M means numbers N through M-1.
1954 1958
1955 1959 For example, if your history contains (%hist prints it):
1956 1960
1957 1961 44: x=1
1958 1962 45: y=3
1959 1963 46: z=x+y
1960 1964 47: print x
1961 1965 48: a=5
1962 1966 49: print 'x',x,'y',y
1963 1967
1964 1968 you can create a macro with lines 44 through 47 (included) and line 49
1965 1969 called my_macro with:
1966 1970
1967 1971 In [55]: %macro my_macro 44-47 49
1968 1972
1969 1973 Now, typing `my_macro` (without quotes) will re-execute all this code
1970 1974 in one pass.
1971 1975
1972 1976 You don't need to give the line-numbers in order, and any given line
1973 1977 number can appear multiple times. You can assemble macros with any
1974 1978 lines from your input history in any order.
1975 1979
1976 1980 The macro is a simple object which holds its value in an attribute,
1977 1981 but IPython's display system checks for macros and executes them as
1978 1982 code instead of printing them when you type their name.
1979 1983
1980 1984 You can view a macro's contents by explicitly printing it with:
1981 1985
1982 1986 'print macro_name'.
1983 1987
1984 1988 For one-off cases which DON'T contain magic function calls in them you
1985 1989 can obtain similar results by explicitly executing slices from your
1986 1990 input history with:
1987 1991
1988 1992 In [60]: exec In[44:48]+In[49]"""
1989 1993
1990 1994 opts,args = self.parse_options(parameter_s,'r',mode='list')
1991 1995 if not args:
1992 1996 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1993 1997 macs.sort()
1994 1998 return macs
1995 1999 if len(args) == 1:
1996 2000 raise UsageError(
1997 2001 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1998 2002 name,ranges = args[0], args[1:]
1999 2003
2000 2004 #print 'rng',ranges # dbg
2001 2005 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2002 2006 macro = Macro(lines)
2003 2007 self.shell.user_ns.update({name:macro})
2004 2008 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2005 2009 print 'Macro contents:'
2006 2010 print macro,
2007 2011
2008 2012 def magic_save(self,parameter_s = ''):
2009 2013 """Save a set of lines to a given filename.
2010 2014
2011 2015 Usage:\\
2012 2016 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2013 2017
2014 2018 Options:
2015 2019
2016 2020 -r: use 'raw' input. By default, the 'processed' history is used,
2017 2021 so that magics are loaded in their transformed version to valid
2018 2022 Python. If this option is given, the raw input as typed as the
2019 2023 command line is used instead.
2020 2024
2021 2025 This function uses the same syntax as %macro for line extraction, but
2022 2026 instead of creating a macro it saves the resulting string to the
2023 2027 filename you specify.
2024 2028
2025 2029 It adds a '.py' extension to the file if you don't do so yourself, and
2026 2030 it asks for confirmation before overwriting existing files."""
2027 2031
2028 2032 opts,args = self.parse_options(parameter_s,'r',mode='list')
2029 2033 fname,ranges = args[0], args[1:]
2030 2034 if not fname.endswith('.py'):
2031 2035 fname += '.py'
2032 2036 if os.path.isfile(fname):
2033 2037 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2034 2038 if ans.lower() not in ['y','yes']:
2035 2039 print 'Operation cancelled.'
2036 2040 return
2037 2041 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2038 2042 f = file(fname,'w')
2039 2043 f.write(cmds)
2040 2044 f.close()
2041 2045 print 'The following commands were written to file `%s`:' % fname
2042 2046 print cmds
2043 2047
2044 2048 def _edit_macro(self,mname,macro):
2045 2049 """open an editor with the macro data in a file"""
2046 2050 filename = self.shell.mktempfile(macro.value)
2047 2051 self.shell.hooks.editor(filename)
2048 2052
2049 2053 # and make a new macro object, to replace the old one
2050 2054 mfile = open(filename)
2051 2055 mvalue = mfile.read()
2052 2056 mfile.close()
2053 2057 self.shell.user_ns[mname] = Macro(mvalue)
2054 2058
2055 2059 def magic_ed(self,parameter_s=''):
2056 2060 """Alias to %edit."""
2057 2061 return self.magic_edit(parameter_s)
2058 2062
2059 2063 @testdec.skip_doctest
2060 2064 def magic_edit(self,parameter_s='',last_call=['','']):
2061 2065 """Bring up an editor and execute the resulting code.
2062 2066
2063 2067 Usage:
2064 2068 %edit [options] [args]
2065 2069
2066 2070 %edit runs IPython's editor hook. The default version of this hook is
2067 2071 set to call the __IPYTHON__.rc.editor command. This is read from your
2068 2072 environment variable $EDITOR. If this isn't found, it will default to
2069 2073 vi under Linux/Unix and to notepad under Windows. See the end of this
2070 2074 docstring for how to change the editor hook.
2071 2075
2072 2076 You can also set the value of this editor via the command line option
2073 2077 '-editor' or in your ipythonrc file. This is useful if you wish to use
2074 2078 specifically for IPython an editor different from your typical default
2075 2079 (and for Windows users who typically don't set environment variables).
2076 2080
2077 2081 This command allows you to conveniently edit multi-line code right in
2078 2082 your IPython session.
2079 2083
2080 2084 If called without arguments, %edit opens up an empty editor with a
2081 2085 temporary file and will execute the contents of this file when you
2082 2086 close it (don't forget to save it!).
2083 2087
2084 2088
2085 2089 Options:
2086 2090
2087 2091 -n <number>: open the editor at a specified line number. By default,
2088 2092 the IPython editor hook uses the unix syntax 'editor +N filename', but
2089 2093 you can configure this by providing your own modified hook if your
2090 2094 favorite editor supports line-number specifications with a different
2091 2095 syntax.
2092 2096
2093 2097 -p: this will call the editor with the same data as the previous time
2094 2098 it was used, regardless of how long ago (in your current session) it
2095 2099 was.
2096 2100
2097 2101 -r: use 'raw' input. This option only applies to input taken from the
2098 2102 user's history. By default, the 'processed' history is used, so that
2099 2103 magics are loaded in their transformed version to valid Python. If
2100 2104 this option is given, the raw input as typed as the command line is
2101 2105 used instead. When you exit the editor, it will be executed by
2102 2106 IPython's own processor.
2103 2107
2104 2108 -x: do not execute the edited code immediately upon exit. This is
2105 2109 mainly useful if you are editing programs which need to be called with
2106 2110 command line arguments, which you can then do using %run.
2107 2111
2108 2112
2109 2113 Arguments:
2110 2114
2111 2115 If arguments are given, the following possibilites exist:
2112 2116
2113 2117 - The arguments are numbers or pairs of colon-separated numbers (like
2114 2118 1 4:8 9). These are interpreted as lines of previous input to be
2115 2119 loaded into the editor. The syntax is the same of the %macro command.
2116 2120
2117 2121 - If the argument doesn't start with a number, it is evaluated as a
2118 2122 variable and its contents loaded into the editor. You can thus edit
2119 2123 any string which contains python code (including the result of
2120 2124 previous edits).
2121 2125
2122 2126 - If the argument is the name of an object (other than a string),
2123 2127 IPython will try to locate the file where it was defined and open the
2124 2128 editor at the point where it is defined. You can use `%edit function`
2125 2129 to load an editor exactly at the point where 'function' is defined,
2126 2130 edit it and have the file be executed automatically.
2127 2131
2128 2132 If the object is a macro (see %macro for details), this opens up your
2129 2133 specified editor with a temporary file containing the macro's data.
2130 2134 Upon exit, the macro is reloaded with the contents of the file.
2131 2135
2132 2136 Note: opening at an exact line is only supported under Unix, and some
2133 2137 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2134 2138 '+NUMBER' parameter necessary for this feature. Good editors like
2135 2139 (X)Emacs, vi, jed, pico and joe all do.
2136 2140
2137 2141 - If the argument is not found as a variable, IPython will look for a
2138 2142 file with that name (adding .py if necessary) and load it into the
2139 2143 editor. It will execute its contents with execfile() when you exit,
2140 2144 loading any code in the file into your interactive namespace.
2141 2145
2142 2146 After executing your code, %edit will return as output the code you
2143 2147 typed in the editor (except when it was an existing file). This way
2144 2148 you can reload the code in further invocations of %edit as a variable,
2145 2149 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2146 2150 the output.
2147 2151
2148 2152 Note that %edit is also available through the alias %ed.
2149 2153
2150 2154 This is an example of creating a simple function inside the editor and
2151 2155 then modifying it. First, start up the editor:
2152 2156
2153 2157 In [1]: ed
2154 2158 Editing... done. Executing edited code...
2155 2159 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2156 2160
2157 2161 We can then call the function foo():
2158 2162
2159 2163 In [2]: foo()
2160 2164 foo() was defined in an editing session
2161 2165
2162 2166 Now we edit foo. IPython automatically loads the editor with the
2163 2167 (temporary) file where foo() was previously defined:
2164 2168
2165 2169 In [3]: ed foo
2166 2170 Editing... done. Executing edited code...
2167 2171
2168 2172 And if we call foo() again we get the modified version:
2169 2173
2170 2174 In [4]: foo()
2171 2175 foo() has now been changed!
2172 2176
2173 2177 Here is an example of how to edit a code snippet successive
2174 2178 times. First we call the editor:
2175 2179
2176 2180 In [5]: ed
2177 2181 Editing... done. Executing edited code...
2178 2182 hello
2179 2183 Out[5]: "print 'hello'n"
2180 2184
2181 2185 Now we call it again with the previous output (stored in _):
2182 2186
2183 2187 In [6]: ed _
2184 2188 Editing... done. Executing edited code...
2185 2189 hello world
2186 2190 Out[6]: "print 'hello world'n"
2187 2191
2188 2192 Now we call it with the output #8 (stored in _8, also as Out[8]):
2189 2193
2190 2194 In [7]: ed _8
2191 2195 Editing... done. Executing edited code...
2192 2196 hello again
2193 2197 Out[7]: "print 'hello again'n"
2194 2198
2195 2199
2196 2200 Changing the default editor hook:
2197 2201
2198 2202 If you wish to write your own editor hook, you can put it in a
2199 2203 configuration file which you load at startup time. The default hook
2200 2204 is defined in the IPython.hooks module, and you can use that as a
2201 2205 starting example for further modifications. That file also has
2202 2206 general instructions on how to set a new hook for use once you've
2203 2207 defined it."""
2204 2208
2205 2209 # FIXME: This function has become a convoluted mess. It needs a
2206 2210 # ground-up rewrite with clean, simple logic.
2207 2211
2208 2212 def make_filename(arg):
2209 2213 "Make a filename from the given args"
2210 2214 try:
2211 2215 filename = get_py_filename(arg)
2212 2216 except IOError:
2213 2217 if args.endswith('.py'):
2214 2218 filename = arg
2215 2219 else:
2216 2220 filename = None
2217 2221 return filename
2218 2222
2219 2223 # custom exceptions
2220 2224 class DataIsObject(Exception): pass
2221 2225
2222 2226 opts,args = self.parse_options(parameter_s,'prxn:')
2223 2227 # Set a few locals from the options for convenience:
2224 2228 opts_p = opts.has_key('p')
2225 2229 opts_r = opts.has_key('r')
2226 2230
2227 2231 # Default line number value
2228 2232 lineno = opts.get('n',None)
2229 2233
2230 2234 if opts_p:
2231 2235 args = '_%s' % last_call[0]
2232 2236 if not self.shell.user_ns.has_key(args):
2233 2237 args = last_call[1]
2234 2238
2235 2239 # use last_call to remember the state of the previous call, but don't
2236 2240 # let it be clobbered by successive '-p' calls.
2237 2241 try:
2238 2242 last_call[0] = self.shell.outputcache.prompt_count
2239 2243 if not opts_p:
2240 2244 last_call[1] = parameter_s
2241 2245 except:
2242 2246 pass
2243 2247
2244 2248 # by default this is done with temp files, except when the given
2245 2249 # arg is a filename
2246 2250 use_temp = 1
2247 2251
2248 2252 if re.match(r'\d',args):
2249 2253 # Mode where user specifies ranges of lines, like in %macro.
2250 2254 # This means that you can't edit files whose names begin with
2251 2255 # numbers this way. Tough.
2252 2256 ranges = args.split()
2253 2257 data = ''.join(self.extract_input_slices(ranges,opts_r))
2254 2258 elif args.endswith('.py'):
2255 2259 filename = make_filename(args)
2256 2260 data = ''
2257 2261 use_temp = 0
2258 2262 elif args:
2259 2263 try:
2260 2264 # Load the parameter given as a variable. If not a string,
2261 2265 # process it as an object instead (below)
2262 2266
2263 2267 #print '*** args',args,'type',type(args) # dbg
2264 2268 data = eval(args,self.shell.user_ns)
2265 2269 if not type(data) in StringTypes:
2266 2270 raise DataIsObject
2267 2271
2268 2272 except (NameError,SyntaxError):
2269 2273 # given argument is not a variable, try as a filename
2270 2274 filename = make_filename(args)
2271 2275 if filename is None:
2272 2276 warn("Argument given (%s) can't be found as a variable "
2273 2277 "or as a filename." % args)
2274 2278 return
2275 2279
2276 2280 data = ''
2277 2281 use_temp = 0
2278 2282 except DataIsObject:
2279 2283
2280 2284 # macros have a special edit function
2281 2285 if isinstance(data,Macro):
2282 2286 self._edit_macro(args,data)
2283 2287 return
2284 2288
2285 2289 # For objects, try to edit the file where they are defined
2286 2290 try:
2287 2291 filename = inspect.getabsfile(data)
2288 2292 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2289 2293 # class created by %edit? Try to find source
2290 2294 # by looking for method definitions instead, the
2291 2295 # __module__ in those classes is FakeModule.
2292 2296 attrs = [getattr(data, aname) for aname in dir(data)]
2293 2297 for attr in attrs:
2294 2298 if not inspect.ismethod(attr):
2295 2299 continue
2296 2300 filename = inspect.getabsfile(attr)
2297 2301 if filename and 'fakemodule' not in filename.lower():
2298 2302 # change the attribute to be the edit target instead
2299 2303 data = attr
2300 2304 break
2301 2305
2302 2306 datafile = 1
2303 2307 except TypeError:
2304 2308 filename = make_filename(args)
2305 2309 datafile = 1
2306 2310 warn('Could not find file where `%s` is defined.\n'
2307 2311 'Opening a file named `%s`' % (args,filename))
2308 2312 # Now, make sure we can actually read the source (if it was in
2309 2313 # a temp file it's gone by now).
2310 2314 if datafile:
2311 2315 try:
2312 2316 if lineno is None:
2313 2317 lineno = inspect.getsourcelines(data)[1]
2314 2318 except IOError:
2315 2319 filename = make_filename(args)
2316 2320 if filename is None:
2317 2321 warn('The file `%s` where `%s` was defined cannot '
2318 2322 'be read.' % (filename,data))
2319 2323 return
2320 2324 use_temp = 0
2321 2325 else:
2322 2326 data = ''
2323 2327
2324 2328 if use_temp:
2325 2329 filename = self.shell.mktempfile(data)
2326 2330 print 'IPython will make a temporary file named:',filename
2327 2331
2328 2332 # do actual editing here
2329 2333 print 'Editing...',
2330 2334 sys.stdout.flush()
2331 self.shell.hooks.editor(filename,lineno)
2335 try:
2336 self.shell.hooks.editor(filename,lineno)
2337 except IPython.ipapi.TryNext:
2338 warn('Could not open editor')
2339 return
2340
2341 # XXX TODO: should this be generalized for all string vars?
2342 # For now, this is special-cased to blocks created by cpaste
2343 if args.strip() == 'pasted_block':
2344 self.shell.user_ns['pasted_block'] = file_read(filename)
2345
2332 2346 if opts.has_key('x'): # -x prevents actual execution
2333 2347 print
2334 2348 else:
2335 2349 print 'done. Executing edited code...'
2336 2350 if opts_r:
2337 2351 self.shell.runlines(file_read(filename))
2338 2352 else:
2339 2353 self.shell.safe_execfile(filename,self.shell.user_ns,
2340 2354 self.shell.user_ns)
2355
2356
2341 2357 if use_temp:
2342 2358 try:
2343 2359 return open(filename).read()
2344 2360 except IOError,msg:
2345 2361 if msg.filename == filename:
2346 2362 warn('File not found. Did you forget to save?')
2347 2363 return
2348 2364 else:
2349 2365 self.shell.showtraceback()
2350 2366
2351 2367 def magic_xmode(self,parameter_s = ''):
2352 2368 """Switch modes for the exception handlers.
2353 2369
2354 2370 Valid modes: Plain, Context and Verbose.
2355 2371
2356 2372 If called without arguments, acts as a toggle."""
2357 2373
2358 2374 def xmode_switch_err(name):
2359 2375 warn('Error changing %s exception modes.\n%s' %
2360 2376 (name,sys.exc_info()[1]))
2361 2377
2362 2378 shell = self.shell
2363 2379 new_mode = parameter_s.strip().capitalize()
2364 2380 try:
2365 2381 shell.InteractiveTB.set_mode(mode=new_mode)
2366 2382 print 'Exception reporting mode:',shell.InteractiveTB.mode
2367 2383 except:
2368 2384 xmode_switch_err('user')
2369 2385
2370 2386 # threaded shells use a special handler in sys.excepthook
2371 2387 if shell.isthreaded:
2372 2388 try:
2373 2389 shell.sys_excepthook.set_mode(mode=new_mode)
2374 2390 except:
2375 2391 xmode_switch_err('threaded')
2376 2392
2377 2393 def magic_colors(self,parameter_s = ''):
2378 2394 """Switch color scheme for prompts, info system and exception handlers.
2379 2395
2380 2396 Currently implemented schemes: NoColor, Linux, LightBG.
2381 2397
2382 2398 Color scheme names are not case-sensitive."""
2383 2399
2384 2400 def color_switch_err(name):
2385 2401 warn('Error changing %s color schemes.\n%s' %
2386 2402 (name,sys.exc_info()[1]))
2387 2403
2388 2404
2389 2405 new_scheme = parameter_s.strip()
2390 2406 if not new_scheme:
2391 2407 raise UsageError(
2392 2408 "%colors: you must specify a color scheme. See '%colors?'")
2393 2409 return
2394 2410 # local shortcut
2395 2411 shell = self.shell
2396 2412
2397 2413 import IPython.rlineimpl as readline
2398 2414
2399 2415 if not readline.have_readline and sys.platform == "win32":
2400 2416 msg = """\
2401 2417 Proper color support under MS Windows requires the pyreadline library.
2402 2418 You can find it at:
2403 2419 http://ipython.scipy.org/moin/PyReadline/Intro
2404 2420 Gary's readline needs the ctypes module, from:
2405 2421 http://starship.python.net/crew/theller/ctypes
2406 2422 (Note that ctypes is already part of Python versions 2.5 and newer).
2407 2423
2408 2424 Defaulting color scheme to 'NoColor'"""
2409 2425 new_scheme = 'NoColor'
2410 2426 warn(msg)
2411 2427
2412 2428 # readline option is 0
2413 2429 if not shell.has_readline:
2414 2430 new_scheme = 'NoColor'
2415 2431
2416 2432 # Set prompt colors
2417 2433 try:
2418 2434 shell.outputcache.set_colors(new_scheme)
2419 2435 except:
2420 2436 color_switch_err('prompt')
2421 2437 else:
2422 2438 shell.rc.colors = \
2423 2439 shell.outputcache.color_table.active_scheme_name
2424 2440 # Set exception colors
2425 2441 try:
2426 2442 shell.InteractiveTB.set_colors(scheme = new_scheme)
2427 2443 shell.SyntaxTB.set_colors(scheme = new_scheme)
2428 2444 except:
2429 2445 color_switch_err('exception')
2430 2446
2431 2447 # threaded shells use a verbose traceback in sys.excepthook
2432 2448 if shell.isthreaded:
2433 2449 try:
2434 2450 shell.sys_excepthook.set_colors(scheme=new_scheme)
2435 2451 except:
2436 2452 color_switch_err('system exception handler')
2437 2453
2438 2454 # Set info (for 'object?') colors
2439 2455 if shell.rc.color_info:
2440 2456 try:
2441 2457 shell.inspector.set_active_scheme(new_scheme)
2442 2458 except:
2443 2459 color_switch_err('object inspector')
2444 2460 else:
2445 2461 shell.inspector.set_active_scheme('NoColor')
2446 2462
2447 2463 def magic_color_info(self,parameter_s = ''):
2448 2464 """Toggle color_info.
2449 2465
2450 2466 The color_info configuration parameter controls whether colors are
2451 2467 used for displaying object details (by things like %psource, %pfile or
2452 2468 the '?' system). This function toggles this value with each call.
2453 2469
2454 2470 Note that unless you have a fairly recent pager (less works better
2455 2471 than more) in your system, using colored object information displays
2456 2472 will not work properly. Test it and see."""
2457 2473
2458 2474 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2459 2475 self.magic_colors(self.shell.rc.colors)
2460 2476 print 'Object introspection functions have now coloring:',
2461 2477 print ['OFF','ON'][self.shell.rc.color_info]
2462 2478
2463 2479 def magic_Pprint(self, parameter_s=''):
2464 2480 """Toggle pretty printing on/off."""
2465 2481
2466 2482 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2467 2483 print 'Pretty printing has been turned', \
2468 2484 ['OFF','ON'][self.shell.rc.pprint]
2469 2485
2470 2486 def magic_exit(self, parameter_s=''):
2471 2487 """Exit IPython, confirming if configured to do so.
2472 2488
2473 2489 You can configure whether IPython asks for confirmation upon exit by
2474 2490 setting the confirm_exit flag in the ipythonrc file."""
2475 2491
2476 2492 self.shell.exit()
2477 2493
2478 2494 def magic_quit(self, parameter_s=''):
2479 2495 """Exit IPython, confirming if configured to do so (like %exit)"""
2480 2496
2481 2497 self.shell.exit()
2482 2498
2483 2499 def magic_Exit(self, parameter_s=''):
2484 2500 """Exit IPython without confirmation."""
2485 2501
2486 2502 self.shell.ask_exit()
2487 2503
2488 2504 #......................................................................
2489 2505 # Functions to implement unix shell-type things
2490 2506
2491 2507 @testdec.skip_doctest
2492 2508 def magic_alias(self, parameter_s = ''):
2493 2509 """Define an alias for a system command.
2494 2510
2495 2511 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2496 2512
2497 2513 Then, typing 'alias_name params' will execute the system command 'cmd
2498 2514 params' (from your underlying operating system).
2499 2515
2500 2516 Aliases have lower precedence than magic functions and Python normal
2501 2517 variables, so if 'foo' is both a Python variable and an alias, the
2502 2518 alias can not be executed until 'del foo' removes the Python variable.
2503 2519
2504 2520 You can use the %l specifier in an alias definition to represent the
2505 2521 whole line when the alias is called. For example:
2506 2522
2507 2523 In [2]: alias all echo "Input in brackets: <%l>"
2508 2524 In [3]: all hello world
2509 2525 Input in brackets: <hello world>
2510 2526
2511 2527 You can also define aliases with parameters using %s specifiers (one
2512 2528 per parameter):
2513 2529
2514 2530 In [1]: alias parts echo first %s second %s
2515 2531 In [2]: %parts A B
2516 2532 first A second B
2517 2533 In [3]: %parts A
2518 2534 Incorrect number of arguments: 2 expected.
2519 2535 parts is an alias to: 'echo first %s second %s'
2520 2536
2521 2537 Note that %l and %s are mutually exclusive. You can only use one or
2522 2538 the other in your aliases.
2523 2539
2524 2540 Aliases expand Python variables just like system calls using ! or !!
2525 2541 do: all expressions prefixed with '$' get expanded. For details of
2526 2542 the semantic rules, see PEP-215:
2527 2543 http://www.python.org/peps/pep-0215.html. This is the library used by
2528 2544 IPython for variable expansion. If you want to access a true shell
2529 2545 variable, an extra $ is necessary to prevent its expansion by IPython:
2530 2546
2531 2547 In [6]: alias show echo
2532 2548 In [7]: PATH='A Python string'
2533 2549 In [8]: show $PATH
2534 2550 A Python string
2535 2551 In [9]: show $$PATH
2536 2552 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2537 2553
2538 2554 You can use the alias facility to acess all of $PATH. See the %rehash
2539 2555 and %rehashx functions, which automatically create aliases for the
2540 2556 contents of your $PATH.
2541 2557
2542 2558 If called with no parameters, %alias prints the current alias table."""
2543 2559
2544 2560 par = parameter_s.strip()
2545 2561 if not par:
2546 2562 stored = self.db.get('stored_aliases', {} )
2547 2563 atab = self.shell.alias_table
2548 2564 aliases = atab.keys()
2549 2565 aliases.sort()
2550 2566 res = []
2551 2567 showlast = []
2552 2568 for alias in aliases:
2553 2569 special = False
2554 2570 try:
2555 2571 tgt = atab[alias][1]
2556 2572 except (TypeError, AttributeError):
2557 2573 # unsubscriptable? probably a callable
2558 2574 tgt = atab[alias]
2559 2575 special = True
2560 2576 # 'interesting' aliases
2561 2577 if (alias in stored or
2562 2578 special or
2563 2579 alias.lower() != os.path.splitext(tgt)[0].lower() or
2564 2580 ' ' in tgt):
2565 2581 showlast.append((alias, tgt))
2566 2582 else:
2567 2583 res.append((alias, tgt ))
2568 2584
2569 2585 # show most interesting aliases last
2570 2586 res.extend(showlast)
2571 2587 print "Total number of aliases:",len(aliases)
2572 2588 return res
2573 2589 try:
2574 2590 alias,cmd = par.split(None,1)
2575 2591 except:
2576 2592 print OInspect.getdoc(self.magic_alias)
2577 2593 else:
2578 2594 nargs = cmd.count('%s')
2579 2595 if nargs>0 and cmd.find('%l')>=0:
2580 2596 error('The %s and %l specifiers are mutually exclusive '
2581 2597 'in alias definitions.')
2582 2598 else: # all looks OK
2583 2599 self.shell.alias_table[alias] = (nargs,cmd)
2584 2600 self.shell.alias_table_validate(verbose=0)
2585 2601 # end magic_alias
2586 2602
2587 2603 def magic_unalias(self, parameter_s = ''):
2588 2604 """Remove an alias"""
2589 2605
2590 2606 aname = parameter_s.strip()
2591 2607 if aname in self.shell.alias_table:
2592 2608 del self.shell.alias_table[aname]
2593 2609 stored = self.db.get('stored_aliases', {} )
2594 2610 if aname in stored:
2595 2611 print "Removing %stored alias",aname
2596 2612 del stored[aname]
2597 2613 self.db['stored_aliases'] = stored
2598 2614
2599 2615
2600 2616 def magic_rehashx(self, parameter_s = ''):
2601 2617 """Update the alias table with all executable files in $PATH.
2602 2618
2603 2619 This version explicitly checks that every entry in $PATH is a file
2604 2620 with execute access (os.X_OK), so it is much slower than %rehash.
2605 2621
2606 2622 Under Windows, it checks executability as a match agains a
2607 2623 '|'-separated string of extensions, stored in the IPython config
2608 2624 variable win_exec_ext. This defaults to 'exe|com|bat'.
2609 2625
2610 2626 This function also resets the root module cache of module completer,
2611 2627 used on slow filesystems.
2612 2628 """
2613 2629
2614 2630
2615 2631 ip = self.api
2616 2632
2617 2633 # for the benefit of module completer in ipy_completers.py
2618 2634 del ip.db['rootmodules']
2619 2635
2620 2636 path = [os.path.abspath(os.path.expanduser(p)) for p in
2621 2637 os.environ.get('PATH','').split(os.pathsep)]
2622 2638 path = filter(os.path.isdir,path)
2623 2639
2624 2640 alias_table = self.shell.alias_table
2625 2641 syscmdlist = []
2626 2642 if os.name == 'posix':
2627 2643 isexec = lambda fname:os.path.isfile(fname) and \
2628 2644 os.access(fname,os.X_OK)
2629 2645 else:
2630 2646
2631 2647 try:
2632 2648 winext = os.environ['pathext'].replace(';','|').replace('.','')
2633 2649 except KeyError:
2634 2650 winext = 'exe|com|bat|py'
2635 2651 if 'py' not in winext:
2636 2652 winext += '|py'
2637 2653 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2638 2654 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2639 2655 savedir = os.getcwd()
2640 2656 try:
2641 2657 # write the whole loop for posix/Windows so we don't have an if in
2642 2658 # the innermost part
2643 2659 if os.name == 'posix':
2644 2660 for pdir in path:
2645 2661 os.chdir(pdir)
2646 2662 for ff in os.listdir(pdir):
2647 2663 if isexec(ff) and ff not in self.shell.no_alias:
2648 2664 # each entry in the alias table must be (N,name),
2649 2665 # where N is the number of positional arguments of the
2650 # alias.
2651 alias_table[ff] = (0,ff)
2666 # alias.
2667 # Dots will be removed from alias names, since ipython
2668 # assumes names with dots to be python code
2669 alias_table[ff.replace('.','')] = (0,ff)
2652 2670 syscmdlist.append(ff)
2653 2671 else:
2654 2672 for pdir in path:
2655 2673 os.chdir(pdir)
2656 2674 for ff in os.listdir(pdir):
2657 2675 base, ext = os.path.splitext(ff)
2658 2676 if isexec(ff) and base.lower() not in self.shell.no_alias:
2659 2677 if ext.lower() == '.exe':
2660 2678 ff = base
2661 alias_table[base.lower()] = (0,ff)
2679 alias_table[base.lower().replace('.','')] = (0,ff)
2662 2680 syscmdlist.append(ff)
2663 2681 # Make sure the alias table doesn't contain keywords or builtins
2664 2682 self.shell.alias_table_validate()
2665 2683 # Call again init_auto_alias() so we get 'rm -i' and other
2666 2684 # modified aliases since %rehashx will probably clobber them
2667 2685
2668 2686 # no, we don't want them. if %rehashx clobbers them, good,
2669 2687 # we'll probably get better versions
2670 2688 # self.shell.init_auto_alias()
2671 2689 db = ip.db
2672 2690 db['syscmdlist'] = syscmdlist
2673 2691 finally:
2674 2692 os.chdir(savedir)
2675 2693
2676 2694 def magic_pwd(self, parameter_s = ''):
2677 2695 """Return the current working directory path."""
2678 2696 return os.getcwd()
2679 2697
2680 2698 def magic_cd(self, parameter_s=''):
2681 2699 """Change the current working directory.
2682 2700
2683 2701 This command automatically maintains an internal list of directories
2684 2702 you visit during your IPython session, in the variable _dh. The
2685 2703 command %dhist shows this history nicely formatted. You can also
2686 2704 do 'cd -<tab>' to see directory history conveniently.
2687 2705
2688 2706 Usage:
2689 2707
2690 2708 cd 'dir': changes to directory 'dir'.
2691 2709
2692 2710 cd -: changes to the last visited directory.
2693 2711
2694 2712 cd -<n>: changes to the n-th directory in the directory history.
2695 2713
2696 2714 cd --foo: change to directory that matches 'foo' in history
2697 2715
2698 2716 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2699 2717 (note: cd <bookmark_name> is enough if there is no
2700 2718 directory <bookmark_name>, but a bookmark with the name exists.)
2701 2719 'cd -b <tab>' allows you to tab-complete bookmark names.
2702 2720
2703 2721 Options:
2704 2722
2705 2723 -q: quiet. Do not print the working directory after the cd command is
2706 2724 executed. By default IPython's cd command does print this directory,
2707 2725 since the default prompts do not display path information.
2708 2726
2709 2727 Note that !cd doesn't work for this purpose because the shell where
2710 2728 !command runs is immediately discarded after executing 'command'."""
2711 2729
2712 2730 parameter_s = parameter_s.strip()
2713 2731 #bkms = self.shell.persist.get("bookmarks",{})
2714 2732
2715 2733 oldcwd = os.getcwd()
2716 2734 numcd = re.match(r'(-)(\d+)$',parameter_s)
2717 2735 # jump in directory history by number
2718 2736 if numcd:
2719 2737 nn = int(numcd.group(2))
2720 2738 try:
2721 2739 ps = self.shell.user_ns['_dh'][nn]
2722 2740 except IndexError:
2723 2741 print 'The requested directory does not exist in history.'
2724 2742 return
2725 2743 else:
2726 2744 opts = {}
2727 2745 elif parameter_s.startswith('--'):
2728 2746 ps = None
2729 2747 fallback = None
2730 2748 pat = parameter_s[2:]
2731 2749 dh = self.shell.user_ns['_dh']
2732 2750 # first search only by basename (last component)
2733 2751 for ent in reversed(dh):
2734 2752 if pat in os.path.basename(ent) and os.path.isdir(ent):
2735 2753 ps = ent
2736 2754 break
2737 2755
2738 2756 if fallback is None and pat in ent and os.path.isdir(ent):
2739 2757 fallback = ent
2740 2758
2741 2759 # if we have no last part match, pick the first full path match
2742 2760 if ps is None:
2743 2761 ps = fallback
2744 2762
2745 2763 if ps is None:
2746 2764 print "No matching entry in directory history"
2747 2765 return
2748 2766 else:
2749 2767 opts = {}
2750 2768
2751 2769
2752 2770 else:
2753 2771 #turn all non-space-escaping backslashes to slashes,
2754 2772 # for c:\windows\directory\names\
2755 2773 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2756 2774 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2757 2775 # jump to previous
2758 2776 if ps == '-':
2759 2777 try:
2760 2778 ps = self.shell.user_ns['_dh'][-2]
2761 2779 except IndexError:
2762 2780 raise UsageError('%cd -: No previous directory to change to.')
2763 2781 # jump to bookmark if needed
2764 2782 else:
2765 2783 if not os.path.isdir(ps) or opts.has_key('b'):
2766 2784 bkms = self.db.get('bookmarks', {})
2767 2785
2768 2786 if bkms.has_key(ps):
2769 2787 target = bkms[ps]
2770 2788 print '(bookmark:%s) -> %s' % (ps,target)
2771 2789 ps = target
2772 2790 else:
2773 2791 if opts.has_key('b'):
2774 2792 raise UsageError("Bookmark '%s' not found. "
2775 2793 "Use '%%bookmark -l' to see your bookmarks." % ps)
2776 2794
2777 2795 # at this point ps should point to the target dir
2778 2796 if ps:
2779 2797 try:
2780 2798 os.chdir(os.path.expanduser(ps))
2781 2799 if self.shell.rc.term_title:
2782 2800 #print 'set term title:',self.shell.rc.term_title # dbg
2783 2801 platutils.set_term_title('IPy ' + abbrev_cwd())
2784 2802 except OSError:
2785 2803 print sys.exc_info()[1]
2786 2804 else:
2787 2805 cwd = os.getcwd()
2788 2806 dhist = self.shell.user_ns['_dh']
2789 2807 if oldcwd != cwd:
2790 2808 dhist.append(cwd)
2791 2809 self.db['dhist'] = compress_dhist(dhist)[-100:]
2792 2810
2793 2811 else:
2794 2812 os.chdir(self.shell.home_dir)
2795 2813 if self.shell.rc.term_title:
2796 2814 platutils.set_term_title("IPy ~")
2797 2815 cwd = os.getcwd()
2798 2816 dhist = self.shell.user_ns['_dh']
2799 2817
2800 2818 if oldcwd != cwd:
2801 2819 dhist.append(cwd)
2802 2820 self.db['dhist'] = compress_dhist(dhist)[-100:]
2803 2821 if not 'q' in opts and self.shell.user_ns['_dh']:
2804 2822 print self.shell.user_ns['_dh'][-1]
2805 2823
2806 2824
2807 2825 def magic_env(self, parameter_s=''):
2808 2826 """List environment variables."""
2809 2827
2810 2828 return os.environ.data
2811 2829
2812 2830 def magic_pushd(self, parameter_s=''):
2813 2831 """Place the current dir on stack and change directory.
2814 2832
2815 2833 Usage:\\
2816 2834 %pushd ['dirname']
2817 2835 """
2818 2836
2819 2837 dir_s = self.shell.dir_stack
2820 2838 tgt = os.path.expanduser(parameter_s)
2821 2839 cwd = os.getcwd().replace(self.home_dir,'~')
2822 2840 if tgt:
2823 2841 self.magic_cd(parameter_s)
2824 2842 dir_s.insert(0,cwd)
2825 2843 return self.magic_dirs()
2826 2844
2827 2845 def magic_popd(self, parameter_s=''):
2828 2846 """Change to directory popped off the top of the stack.
2829 2847 """
2830 2848 if not self.shell.dir_stack:
2831 2849 raise UsageError("%popd on empty stack")
2832 2850 top = self.shell.dir_stack.pop(0)
2833 2851 self.magic_cd(top)
2834 2852 print "popd ->",top
2835 2853
2836 2854 def magic_dirs(self, parameter_s=''):
2837 2855 """Return the current directory stack."""
2838 2856
2839 2857 return self.shell.dir_stack
2840 2858
2841 2859 def magic_dhist(self, parameter_s=''):
2842 2860 """Print your history of visited directories.
2843 2861
2844 2862 %dhist -> print full history\\
2845 2863 %dhist n -> print last n entries only\\
2846 2864 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2847 2865
2848 2866 This history is automatically maintained by the %cd command, and
2849 2867 always available as the global list variable _dh. You can use %cd -<n>
2850 2868 to go to directory number <n>.
2851 2869
2852 2870 Note that most of time, you should view directory history by entering
2853 2871 cd -<TAB>.
2854 2872
2855 2873 """
2856 2874
2857 2875 dh = self.shell.user_ns['_dh']
2858 2876 if parameter_s:
2859 2877 try:
2860 2878 args = map(int,parameter_s.split())
2861 2879 except:
2862 2880 self.arg_err(Magic.magic_dhist)
2863 2881 return
2864 2882 if len(args) == 1:
2865 2883 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2866 2884 elif len(args) == 2:
2867 2885 ini,fin = args
2868 2886 else:
2869 2887 self.arg_err(Magic.magic_dhist)
2870 2888 return
2871 2889 else:
2872 2890 ini,fin = 0,len(dh)
2873 2891 nlprint(dh,
2874 2892 header = 'Directory history (kept in _dh)',
2875 2893 start=ini,stop=fin)
2876 2894
2877 2895 @testdec.skip_doctest
2878 2896 def magic_sc(self, parameter_s=''):
2879 2897 """Shell capture - execute a shell command and capture its output.
2880 2898
2881 2899 DEPRECATED. Suboptimal, retained for backwards compatibility.
2882 2900
2883 2901 You should use the form 'var = !command' instead. Example:
2884 2902
2885 2903 "%sc -l myfiles = ls ~" should now be written as
2886 2904
2887 2905 "myfiles = !ls ~"
2888 2906
2889 2907 myfiles.s, myfiles.l and myfiles.n still apply as documented
2890 2908 below.
2891 2909
2892 2910 --
2893 2911 %sc [options] varname=command
2894 2912
2895 2913 IPython will run the given command using commands.getoutput(), and
2896 2914 will then update the user's interactive namespace with a variable
2897 2915 called varname, containing the value of the call. Your command can
2898 2916 contain shell wildcards, pipes, etc.
2899 2917
2900 2918 The '=' sign in the syntax is mandatory, and the variable name you
2901 2919 supply must follow Python's standard conventions for valid names.
2902 2920
2903 2921 (A special format without variable name exists for internal use)
2904 2922
2905 2923 Options:
2906 2924
2907 2925 -l: list output. Split the output on newlines into a list before
2908 2926 assigning it to the given variable. By default the output is stored
2909 2927 as a single string.
2910 2928
2911 2929 -v: verbose. Print the contents of the variable.
2912 2930
2913 2931 In most cases you should not need to split as a list, because the
2914 2932 returned value is a special type of string which can automatically
2915 2933 provide its contents either as a list (split on newlines) or as a
2916 2934 space-separated string. These are convenient, respectively, either
2917 2935 for sequential processing or to be passed to a shell command.
2918 2936
2919 2937 For example:
2920 2938
2921 2939 # all-random
2922 2940
2923 2941 # Capture into variable a
2924 2942 In [1]: sc a=ls *py
2925 2943
2926 2944 # a is a string with embedded newlines
2927 2945 In [2]: a
2928 2946 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2929 2947
2930 2948 # which can be seen as a list:
2931 2949 In [3]: a.l
2932 2950 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2933 2951
2934 2952 # or as a whitespace-separated string:
2935 2953 In [4]: a.s
2936 2954 Out[4]: 'setup.py win32_manual_post_install.py'
2937 2955
2938 2956 # a.s is useful to pass as a single command line:
2939 2957 In [5]: !wc -l $a.s
2940 2958 146 setup.py
2941 2959 130 win32_manual_post_install.py
2942 2960 276 total
2943 2961
2944 2962 # while the list form is useful to loop over:
2945 2963 In [6]: for f in a.l:
2946 2964 ...: !wc -l $f
2947 2965 ...:
2948 2966 146 setup.py
2949 2967 130 win32_manual_post_install.py
2950 2968
2951 2969 Similiarly, the lists returned by the -l option are also special, in
2952 2970 the sense that you can equally invoke the .s attribute on them to
2953 2971 automatically get a whitespace-separated string from their contents:
2954 2972
2955 2973 In [7]: sc -l b=ls *py
2956 2974
2957 2975 In [8]: b
2958 2976 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2959 2977
2960 2978 In [9]: b.s
2961 2979 Out[9]: 'setup.py win32_manual_post_install.py'
2962 2980
2963 2981 In summary, both the lists and strings used for ouptut capture have
2964 2982 the following special attributes:
2965 2983
2966 2984 .l (or .list) : value as list.
2967 2985 .n (or .nlstr): value as newline-separated string.
2968 2986 .s (or .spstr): value as space-separated string.
2969 2987 """
2970 2988
2971 2989 opts,args = self.parse_options(parameter_s,'lv')
2972 2990 # Try to get a variable name and command to run
2973 2991 try:
2974 2992 # the variable name must be obtained from the parse_options
2975 2993 # output, which uses shlex.split to strip options out.
2976 2994 var,_ = args.split('=',1)
2977 2995 var = var.strip()
2978 2996 # But the the command has to be extracted from the original input
2979 2997 # parameter_s, not on what parse_options returns, to avoid the
2980 2998 # quote stripping which shlex.split performs on it.
2981 2999 _,cmd = parameter_s.split('=',1)
2982 3000 except ValueError:
2983 3001 var,cmd = '',''
2984 3002 # If all looks ok, proceed
2985 3003 out,err = self.shell.getoutputerror(cmd)
2986 3004 if err:
2987 3005 print >> Term.cerr,err
2988 3006 if opts.has_key('l'):
2989 3007 out = SList(out.split('\n'))
2990 3008 else:
2991 3009 out = LSString(out)
2992 3010 if opts.has_key('v'):
2993 3011 print '%s ==\n%s' % (var,pformat(out))
2994 3012 if var:
2995 3013 self.shell.user_ns.update({var:out})
2996 3014 else:
2997 3015 return out
2998 3016
2999 3017 def magic_sx(self, parameter_s=''):
3000 3018 """Shell execute - run a shell command and capture its output.
3001 3019
3002 3020 %sx command
3003 3021
3004 3022 IPython will run the given command using commands.getoutput(), and
3005 3023 return the result formatted as a list (split on '\\n'). Since the
3006 3024 output is _returned_, it will be stored in ipython's regular output
3007 3025 cache Out[N] and in the '_N' automatic variables.
3008 3026
3009 3027 Notes:
3010 3028
3011 3029 1) If an input line begins with '!!', then %sx is automatically
3012 3030 invoked. That is, while:
3013 3031 !ls
3014 3032 causes ipython to simply issue system('ls'), typing
3015 3033 !!ls
3016 3034 is a shorthand equivalent to:
3017 3035 %sx ls
3018 3036
3019 3037 2) %sx differs from %sc in that %sx automatically splits into a list,
3020 3038 like '%sc -l'. The reason for this is to make it as easy as possible
3021 3039 to process line-oriented shell output via further python commands.
3022 3040 %sc is meant to provide much finer control, but requires more
3023 3041 typing.
3024 3042
3025 3043 3) Just like %sc -l, this is a list with special attributes:
3026 3044
3027 3045 .l (or .list) : value as list.
3028 3046 .n (or .nlstr): value as newline-separated string.
3029 3047 .s (or .spstr): value as whitespace-separated string.
3030 3048
3031 3049 This is very useful when trying to use such lists as arguments to
3032 3050 system commands."""
3033 3051
3034 3052 if parameter_s:
3035 3053 out,err = self.shell.getoutputerror(parameter_s)
3036 3054 if err:
3037 3055 print >> Term.cerr,err
3038 3056 return SList(out.split('\n'))
3039 3057
3040 3058 def magic_bg(self, parameter_s=''):
3041 3059 """Run a job in the background, in a separate thread.
3042 3060
3043 3061 For example,
3044 3062
3045 3063 %bg myfunc(x,y,z=1)
3046 3064
3047 3065 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3048 3066 execution starts, a message will be printed indicating the job
3049 3067 number. If your job number is 5, you can use
3050 3068
3051 3069 myvar = jobs.result(5) or myvar = jobs[5].result
3052 3070
3053 3071 to assign this result to variable 'myvar'.
3054 3072
3055 3073 IPython has a job manager, accessible via the 'jobs' object. You can
3056 3074 type jobs? to get more information about it, and use jobs.<TAB> to see
3057 3075 its attributes. All attributes not starting with an underscore are
3058 3076 meant for public use.
3059 3077
3060 3078 In particular, look at the jobs.new() method, which is used to create
3061 3079 new jobs. This magic %bg function is just a convenience wrapper
3062 3080 around jobs.new(), for expression-based jobs. If you want to create a
3063 3081 new job with an explicit function object and arguments, you must call
3064 3082 jobs.new() directly.
3065 3083
3066 3084 The jobs.new docstring also describes in detail several important
3067 3085 caveats associated with a thread-based model for background job
3068 3086 execution. Type jobs.new? for details.
3069 3087
3070 3088 You can check the status of all jobs with jobs.status().
3071 3089
3072 3090 The jobs variable is set by IPython into the Python builtin namespace.
3073 3091 If you ever declare a variable named 'jobs', you will shadow this
3074 3092 name. You can either delete your global jobs variable to regain
3075 3093 access to the job manager, or make a new name and assign it manually
3076 3094 to the manager (stored in IPython's namespace). For example, to
3077 3095 assign the job manager to the Jobs name, use:
3078 3096
3079 3097 Jobs = __builtins__.jobs"""
3080 3098
3081 3099 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3082 3100
3083 3101 def magic_r(self, parameter_s=''):
3084 3102 """Repeat previous input.
3085 3103
3086 3104 Note: Consider using the more powerfull %rep instead!
3087 3105
3088 3106 If given an argument, repeats the previous command which starts with
3089 3107 the same string, otherwise it just repeats the previous input.
3090 3108
3091 3109 Shell escaped commands (with ! as first character) are not recognized
3092 3110 by this system, only pure python code and magic commands.
3093 3111 """
3094 3112
3095 3113 start = parameter_s.strip()
3096 3114 esc_magic = self.shell.ESC_MAGIC
3097 3115 # Identify magic commands even if automagic is on (which means
3098 3116 # the in-memory version is different from that typed by the user).
3099 3117 if self.shell.rc.automagic:
3100 3118 start_magic = esc_magic+start
3101 3119 else:
3102 3120 start_magic = start
3103 3121 # Look through the input history in reverse
3104 3122 for n in range(len(self.shell.input_hist)-2,0,-1):
3105 3123 input = self.shell.input_hist[n]
3106 3124 # skip plain 'r' lines so we don't recurse to infinity
3107 3125 if input != '_ip.magic("r")\n' and \
3108 3126 (input.startswith(start) or input.startswith(start_magic)):
3109 3127 #print 'match',`input` # dbg
3110 3128 print 'Executing:',input,
3111 3129 self.shell.runlines(input)
3112 3130 return
3113 3131 print 'No previous input matching `%s` found.' % start
3114 3132
3115 3133
3116 3134 def magic_bookmark(self, parameter_s=''):
3117 3135 """Manage IPython's bookmark system.
3118 3136
3119 3137 %bookmark <name> - set bookmark to current dir
3120 3138 %bookmark <name> <dir> - set bookmark to <dir>
3121 3139 %bookmark -l - list all bookmarks
3122 3140 %bookmark -d <name> - remove bookmark
3123 3141 %bookmark -r - remove all bookmarks
3124 3142
3125 3143 You can later on access a bookmarked folder with:
3126 3144 %cd -b <name>
3127 3145 or simply '%cd <name>' if there is no directory called <name> AND
3128 3146 there is such a bookmark defined.
3129 3147
3130 3148 Your bookmarks persist through IPython sessions, but they are
3131 3149 associated with each profile."""
3132 3150
3133 3151 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3134 3152 if len(args) > 2:
3135 3153 raise UsageError("%bookmark: too many arguments")
3136 3154
3137 3155 bkms = self.db.get('bookmarks',{})
3138 3156
3139 3157 if opts.has_key('d'):
3140 3158 try:
3141 3159 todel = args[0]
3142 3160 except IndexError:
3143 3161 raise UsageError(
3144 3162 "%bookmark -d: must provide a bookmark to delete")
3145 3163 else:
3146 3164 try:
3147 3165 del bkms[todel]
3148 3166 except KeyError:
3149 3167 raise UsageError(
3150 3168 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3151 3169
3152 3170 elif opts.has_key('r'):
3153 3171 bkms = {}
3154 3172 elif opts.has_key('l'):
3155 3173 bks = bkms.keys()
3156 3174 bks.sort()
3157 3175 if bks:
3158 3176 size = max(map(len,bks))
3159 3177 else:
3160 3178 size = 0
3161 3179 fmt = '%-'+str(size)+'s -> %s'
3162 3180 print 'Current bookmarks:'
3163 3181 for bk in bks:
3164 3182 print fmt % (bk,bkms[bk])
3165 3183 else:
3166 3184 if not args:
3167 3185 raise UsageError("%bookmark: You must specify the bookmark name")
3168 3186 elif len(args)==1:
3169 3187 bkms[args[0]] = os.getcwd()
3170 3188 elif len(args)==2:
3171 3189 bkms[args[0]] = args[1]
3172 3190 self.db['bookmarks'] = bkms
3173 3191
3174 3192 def magic_pycat(self, parameter_s=''):
3175 3193 """Show a syntax-highlighted file through a pager.
3176 3194
3177 3195 This magic is similar to the cat utility, but it will assume the file
3178 3196 to be Python source and will show it with syntax highlighting. """
3179 3197
3180 3198 try:
3181 3199 filename = get_py_filename(parameter_s)
3182 3200 cont = file_read(filename)
3183 3201 except IOError:
3184 3202 try:
3185 3203 cont = eval(parameter_s,self.user_ns)
3186 3204 except NameError:
3187 3205 cont = None
3188 3206 if cont is None:
3189 3207 print "Error: no such file or variable"
3190 3208 return
3191 3209
3192 3210 page(self.shell.pycolorize(cont),
3193 3211 screen_lines=self.shell.rc.screen_length)
3194 3212
3195 3213 def magic_cpaste(self, parameter_s=''):
3196 3214 """Allows you to paste & execute a pre-formatted code block from clipboard.
3197 3215
3198 3216 You must terminate the block with '--' (two minus-signs) alone on the
3199 3217 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3200 3218 is the new sentinel for this operation)
3201 3219
3202 3220 The block is dedented prior to execution to enable execution of method
3203 3221 definitions. '>' and '+' characters at the beginning of a line are
3204 3222 ignored, to allow pasting directly from e-mails, diff files and
3205 3223 doctests (the '...' continuation prompt is also stripped). The
3206 3224 executed block is also assigned to variable named 'pasted_block' for
3207 3225 later editing with '%edit pasted_block'.
3208 3226
3209 3227 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3210 3228 This assigns the pasted block to variable 'foo' as string, without
3211 3229 dedenting or executing it (preceding >>> and + is still stripped)
3212 3230
3231 '%cpaste -r' re-executes the block previously entered by cpaste.
3232
3213 3233 Do not be alarmed by garbled output on Windows (it's a readline bug).
3214 3234 Just press enter and type -- (and press enter again) and the block
3215 3235 will be what was just pasted.
3216 3236
3217 3237 IPython statements (magics, shell escapes) are not supported (yet).
3218 3238 """
3219 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3239 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3220 3240 par = args.strip()
3241 if opts.has_key('r'):
3242 b = self.user_ns.get('pasted_block', None)
3243 if b is None:
3244 raise UsageError('No previous pasted block available')
3245 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3246 exec b in self.user_ns
3247 return
3248
3221 3249 sentinel = opts.get('s','--')
3222 3250
3223 3251 # Regular expressions that declare text we strip from the input:
3224 3252 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3225 3253 r'^\s*(\s?>)+', # Python input prompt
3226 3254 r'^\s*\.{3,}', # Continuation prompts
3227 3255 r'^\++',
3228 3256 ]
3229 3257
3230 3258 strip_from_start = map(re.compile,strip_re)
3231 3259
3232 3260 from IPython import iplib
3233 3261 lines = []
3234 3262 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3235 3263 while 1:
3236 3264 l = iplib.raw_input_original(':')
3237 3265 if l ==sentinel:
3238 3266 break
3239 3267
3240 3268 for pat in strip_from_start:
3241 3269 l = pat.sub('',l)
3242 3270 lines.append(l)
3243 3271
3244 3272 block = "\n".join(lines) + '\n'
3245 3273 #print "block:\n",block
3246 3274 if not par:
3247 3275 b = textwrap.dedent(block)
3248 exec b in self.user_ns
3249 3276 self.user_ns['pasted_block'] = b
3277 exec b in self.user_ns
3250 3278 else:
3251 3279 self.user_ns[par] = SList(block.splitlines())
3252 3280 print "Block assigned to '%s'" % par
3253 3281
3254 3282 def magic_quickref(self,arg):
3255 3283 """ Show a quick reference sheet """
3256 3284 import IPython.usage
3257 3285 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3258 3286
3259 3287 page(qr)
3260 3288
3261 3289 def magic_upgrade(self,arg):
3262 3290 """ Upgrade your IPython installation
3263 3291
3264 3292 This will copy the config files that don't yet exist in your
3265 3293 ipython dir from the system config dir. Use this after upgrading
3266 3294 IPython if you don't wish to delete your .ipython dir.
3267 3295
3268 3296 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3269 3297 new users)
3270 3298
3271 3299 """
3272 3300 ip = self.getapi()
3273 3301 ipinstallation = path(IPython.__file__).dirname()
3274 3302 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3275 3303 src_config = ipinstallation / 'UserConfig'
3276 3304 userdir = path(ip.options.ipythondir)
3277 3305 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3278 3306 print ">",cmd
3279 3307 shell(cmd)
3280 3308 if arg == '-nolegacy':
3281 3309 legacy = userdir.files('ipythonrc*')
3282 3310 print "Nuking legacy files:",legacy
3283 3311
3284 3312 [p.remove() for p in legacy]
3285 3313 suffix = (sys.platform == 'win32' and '.ini' or '')
3286 3314 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3287 3315
3288 3316
3289 3317 def magic_doctest_mode(self,parameter_s=''):
3290 3318 """Toggle doctest mode on and off.
3291 3319
3292 3320 This mode allows you to toggle the prompt behavior between normal
3293 3321 IPython prompts and ones that are as similar to the default IPython
3294 3322 interpreter as possible.
3295 3323
3296 3324 It also supports the pasting of code snippets that have leading '>>>'
3297 3325 and '...' prompts in them. This means that you can paste doctests from
3298 3326 files or docstrings (even if they have leading whitespace), and the
3299 3327 code will execute correctly. You can then use '%history -tn' to see
3300 3328 the translated history without line numbers; this will give you the
3301 3329 input after removal of all the leading prompts and whitespace, which
3302 3330 can be pasted back into an editor.
3303 3331
3304 3332 With these features, you can switch into this mode easily whenever you
3305 3333 need to do testing and changes to doctests, without having to leave
3306 3334 your existing IPython session.
3307 3335 """
3308 3336
3309 3337 # XXX - Fix this to have cleaner activate/deactivate calls.
3310 3338 from IPython.Extensions import InterpreterPasteInput as ipaste
3311 3339 from IPython.ipstruct import Struct
3312 3340
3313 3341 # Shorthands
3314 3342 shell = self.shell
3315 3343 oc = shell.outputcache
3316 3344 rc = shell.rc
3317 3345 meta = shell.meta
3318 3346 # dstore is a data store kept in the instance metadata bag to track any
3319 3347 # changes we make, so we can undo them later.
3320 3348 dstore = meta.setdefault('doctest_mode',Struct())
3321 3349 save_dstore = dstore.setdefault
3322 3350
3323 3351 # save a few values we'll need to recover later
3324 3352 mode = save_dstore('mode',False)
3325 3353 save_dstore('rc_pprint',rc.pprint)
3326 3354 save_dstore('xmode',shell.InteractiveTB.mode)
3327 3355 save_dstore('rc_separate_out',rc.separate_out)
3328 3356 save_dstore('rc_separate_out2',rc.separate_out2)
3329 3357 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3330 3358 save_dstore('rc_separate_in',rc.separate_in)
3331 3359
3332 3360 if mode == False:
3333 3361 # turn on
3334 3362 ipaste.activate_prefilter()
3335 3363
3336 3364 oc.prompt1.p_template = '>>> '
3337 3365 oc.prompt2.p_template = '... '
3338 3366 oc.prompt_out.p_template = ''
3339 3367
3340 3368 # Prompt separators like plain python
3341 3369 oc.input_sep = oc.prompt1.sep = ''
3342 3370 oc.output_sep = ''
3343 3371 oc.output_sep2 = ''
3344 3372
3345 3373 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3346 3374 oc.prompt_out.pad_left = False
3347 3375
3348 3376 rc.pprint = False
3349 3377
3350 3378 shell.magic_xmode('Plain')
3351 3379
3352 3380 else:
3353 3381 # turn off
3354 3382 ipaste.deactivate_prefilter()
3355 3383
3356 3384 oc.prompt1.p_template = rc.prompt_in1
3357 3385 oc.prompt2.p_template = rc.prompt_in2
3358 3386 oc.prompt_out.p_template = rc.prompt_out
3359 3387
3360 3388 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3361 3389
3362 3390 oc.output_sep = dstore.rc_separate_out
3363 3391 oc.output_sep2 = dstore.rc_separate_out2
3364 3392
3365 3393 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3366 3394 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3367 3395
3368 3396 rc.pprint = dstore.rc_pprint
3369 3397
3370 3398 shell.magic_xmode(dstore.xmode)
3371 3399
3372 3400 # Store new mode and inform
3373 3401 dstore.mode = bool(1-int(mode))
3374 3402 print 'Doctest mode is:',
3375 3403 print ['OFF','ON'][dstore.mode]
3376 3404
3377 3405 # end Magic
@@ -1,97 +1,121 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Release data for the IPython project."""
3 3
4 4 #*****************************************************************************
5 5 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
6 6 #
7 7 # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray
8 8 # <n8gray@caltech.edu>
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 # Name of the package for release purposes. This is the name which labels
15 15 # the tarballs and RPMs made by distutils, so it's best to lowercase it.
16 16 name = 'ipython'
17 17
18 18 # For versions with substrings (like 0.6.16.svn), use an extra . to separate
19 19 # the new substring. We have to avoid using either dashes or underscores,
20 20 # because bdist_rpm does not accept dashes (an RPM) convention, and
21 21 # bdist_deb does not accept underscores (a Debian convention).
22 22
23 23 development = False # change this to False to do a release
24 24 version_base = '0.9.1'
25 25 branch = 'ipython'
26 26 revision = '1143'
27 27
28 28 if development:
29 29 if branch == 'ipython':
30 30 version = '%s.bzr.r%s' % (version_base, revision)
31 31 else:
32 32 version = '%s.bzr.r%s.%s' % (version_base, revision, branch)
33 33 else:
34 34 version = version_base
35 35
36 36
37 description = "Tools for interactive development in Python."
37 description = "An interactive computing environment for Python"
38 38
39 39 long_description = \
40 40 """
41 IPython provides a replacement for the interactive Python interpreter with
42 extra functionality.
41 The goal of IPython is to create a comprehensive environment for
42 interactive and exploratory computing. To support this goal, IPython
43 has two main components:
43 44
44 Main features:
45 * An enhanced interactive Python shell.
45 46
46 * Comprehensive object introspection.
47 * An architecture for interactive parallel computing.
47 48
48 * Input history, persistent across sessions.
49 The enhanced interactive Python shell has the following main features:
49 50
50 * Caching of output results during a session with automatically generated
51 references.
51 * Comprehensive object introspection.
52 52
53 * Readline based name completion.
53 * Input history, persistent across sessions.
54 54
55 * Extensible system of 'magic' commands for controlling the environment and
56 performing many tasks related either to IPython or the operating system.
55 * Caching of output results during a session with automatically generated
56 references.
57 57
58 * Configuration system with easy switching between different setups (simpler
59 than changing $PYTHONSTARTUP environment variables every time).
58 * Readline based name completion.
60 59
61 * Session logging and reloading.
60 * Extensible system of 'magic' commands for controlling the environment and
61 performing many tasks related either to IPython or the operating system.
62 62
63 * Extensible syntax processing for special purpose situations.
63 * Configuration system with easy switching between different setups (simpler
64 than changing $PYTHONSTARTUP environment variables every time).
64 65
65 * Access to the system shell with user-extensible alias system.
66 * Session logging and reloading.
66 67
67 * Easily embeddable in other Python programs.
68 * Extensible syntax processing for special purpose situations.
68 69
69 * Integrated access to the pdb debugger and the Python profiler.
70 * Access to the system shell with user-extensible alias system.
70 71
71 The latest development version is always available at the IPython subversion
72 repository_.
72 * Easily embeddable in other Python programs and wxPython GUIs.
73 73
74 .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev
75 """
74 * Integrated access to the pdb debugger and the Python profiler.
75
76 The parallel computing architecture has the following main features:
77
78 * Quickly parallelize Python code from an interactive Python/IPython session.
79
80 * A flexible and dynamic process model that be deployed on anything from
81 multicore workstations to supercomputers.
82
83 * An architecture that supports many different styles of parallelism, from
84 message passing to task farming.
85
86 * Both blocking and fully asynchronous interfaces.
87
88 * High level APIs that enable many things to be parallelized in a few lines
89 of code.
90
91 * Share live parallel jobs with other users securely.
92
93 * Dynamically load balanced task farming system.
94
95 * Robust error handling in parallel code.
96
97 The latest development version is always available from IPython's `Launchpad
98 site <http://launchpad.net/ipython>`_.
99 """
76 100
77 101 license = 'BSD'
78 102
79 103 authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'),
80 104 'Janko' : ('Janko Hauser','jhauser@zscout.de'),
81 105 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'),
82 106 'Ville' : ('Ville Vainio','vivainio@gmail.com'),
83 107 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'),
84 108 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com')
85 109 }
86 110
87 111 author = 'The IPython Development Team'
88 112
89 113 author_email = 'ipython-dev@scipy.org'
90 114
91 115 url = 'http://ipython.scipy.org'
92 116
93 117 download_url = 'http://ipython.scipy.org/dist'
94 118
95 119 platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME']
96 120
97 121 keywords = ['Interactive','Interpreter','Shell','Parallel','Distributed']
@@ -1,1238 +1,1249 b''
1 1 # -*- coding: utf-8 -*-
2 2 """IPython Shell classes.
3 3
4 4 All the matplotlib support code was co-developed with John Hunter,
5 5 matplotlib's author.
6 6
7 7 $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
8 8
9 9 #*****************************************************************************
10 10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #*****************************************************************************
15 15
16 16 from IPython import Release
17 17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 18 __license__ = Release.license
19 19
20 20 # Code begins
21 21 # Stdlib imports
22 22 import __builtin__
23 23 import __main__
24 24 import Queue
25 25 import inspect
26 26 import os
27 27 import sys
28 28 import thread
29 29 import threading
30 30 import time
31 31
32 32 from signal import signal, SIGINT
33 33
34 34 try:
35 35 import ctypes
36 36 HAS_CTYPES = True
37 37 except ImportError:
38 38 HAS_CTYPES = False
39 39
40 40 # IPython imports
41 41 import IPython
42 42 from IPython import ultraTB, ipapi
43 43 from IPython.Magic import Magic
44 44 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
45 45 from IPython.iplib import InteractiveShell
46 46 from IPython.ipmaker import make_IPython
47 47 from IPython.ipstruct import Struct
48 48 from IPython.testing import decorators as testdec
49 49
50 50 # Globals
51 51 # global flag to pass around information about Ctrl-C without exceptions
52 52 KBINT = False
53 53
54 54 # global flag to turn on/off Tk support.
55 55 USE_TK = False
56 56
57 57 # ID for the main thread, used for cross-thread exceptions
58 58 MAIN_THREAD_ID = thread.get_ident()
59 59
60 60 # Tag when runcode() is active, for exception handling
61 61 CODE_RUN = None
62 62
63 63 # Default timeout for waiting for multithreaded shells (in seconds)
64 64 GUI_TIMEOUT = 10
65 65
66 66 #-----------------------------------------------------------------------------
67 67 # This class is trivial now, but I want to have it in to publish a clean
68 68 # interface. Later when the internals are reorganized, code that uses this
69 69 # shouldn't have to change.
70 70
71 71 class IPShell:
72 72 """Create an IPython instance."""
73 73
74 74 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
75 75 debug=1,shell_class=InteractiveShell):
76 76 self.IP = make_IPython(argv,user_ns=user_ns,
77 77 user_global_ns=user_global_ns,
78 78 debug=debug,shell_class=shell_class)
79 79
80 80 def mainloop(self,sys_exit=0,banner=None):
81 81 self.IP.mainloop(banner)
82 82 if sys_exit:
83 83 sys.exit()
84 84
85 85 #-----------------------------------------------------------------------------
86 86 def kill_embedded(self,parameter_s=''):
87 87 """%kill_embedded : deactivate for good the current embedded IPython.
88 88
89 89 This function (after asking for confirmation) sets an internal flag so that
90 90 an embedded IPython will never activate again. This is useful to
91 91 permanently disable a shell that is being called inside a loop: once you've
92 92 figured out what you needed from it, you may then kill it and the program
93 93 will then continue to run without the interactive shell interfering again.
94 94 """
95 95
96 96 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
97 97 "(y/n)? [y/N] ",'n')
98 98 if kill:
99 99 self.shell.embedded_active = False
100 100 print "This embedded IPython will not reactivate anymore once you exit."
101 101
102 102 class IPShellEmbed:
103 103 """Allow embedding an IPython shell into a running program.
104 104
105 105 Instances of this class are callable, with the __call__ method being an
106 106 alias to the embed() method of an InteractiveShell instance.
107 107
108 108 Usage (see also the example-embed.py file for a running example):
109 109
110 110 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
111 111
112 112 - argv: list containing valid command-line options for IPython, as they
113 113 would appear in sys.argv[1:].
114 114
115 115 For example, the following command-line options:
116 116
117 117 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
118 118
119 119 would be passed in the argv list as:
120 120
121 121 ['-prompt_in1','Input <\\#>','-colors','LightBG']
122 122
123 123 - banner: string which gets printed every time the interpreter starts.
124 124
125 125 - exit_msg: string which gets printed every time the interpreter exits.
126 126
127 127 - rc_override: a dict or Struct of configuration options such as those
128 128 used by IPython. These options are read from your ~/.ipython/ipythonrc
129 129 file when the Shell object is created. Passing an explicit rc_override
130 130 dict with any options you want allows you to override those values at
131 131 creation time without having to modify the file. This way you can create
132 132 embeddable instances configured in any way you want without editing any
133 133 global files (thus keeping your interactive IPython configuration
134 134 unchanged).
135 135
136 136 Then the ipshell instance can be called anywhere inside your code:
137 137
138 138 ipshell(header='') -> Opens up an IPython shell.
139 139
140 140 - header: string printed by the IPython shell upon startup. This can let
141 141 you know where in your code you are when dropping into the shell. Note
142 142 that 'banner' gets prepended to all calls, so header is used for
143 143 location-specific information.
144 144
145 145 For more details, see the __call__ method below.
146 146
147 147 When the IPython shell is exited with Ctrl-D, normal program execution
148 148 resumes.
149 149
150 150 This functionality was inspired by a posting on comp.lang.python by cmkl
151 151 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
152 152 by the IDL stop/continue commands."""
153 153
154 154 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
155 155 user_ns=None):
156 156 """Note that argv here is a string, NOT a list."""
157 157 self.set_banner(banner)
158 158 self.set_exit_msg(exit_msg)
159 159 self.set_dummy_mode(0)
160 160
161 161 # sys.displayhook is a global, we need to save the user's original
162 162 # Don't rely on __displayhook__, as the user may have changed that.
163 163 self.sys_displayhook_ori = sys.displayhook
164 164
165 165 # save readline completer status
166 166 try:
167 167 #print 'Save completer',sys.ipcompleter # dbg
168 168 self.sys_ipcompleter_ori = sys.ipcompleter
169 169 except:
170 170 pass # not nested with IPython
171 171
172 172 self.IP = make_IPython(argv,rc_override=rc_override,
173 173 embedded=True,
174 174 user_ns=user_ns)
175 175
176 176 ip = ipapi.IPApi(self.IP)
177 177 ip.expose_magic("kill_embedded",kill_embedded)
178 178
179 179 # copy our own displayhook also
180 180 self.sys_displayhook_embed = sys.displayhook
181 181 # and leave the system's display hook clean
182 182 sys.displayhook = self.sys_displayhook_ori
183 183 # don't use the ipython crash handler so that user exceptions aren't
184 184 # trapped
185 185 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
186 186 mode = self.IP.rc.xmode,
187 187 call_pdb = self.IP.rc.pdb)
188 188 self.restore_system_completer()
189 189
190 190 def restore_system_completer(self):
191 191 """Restores the readline completer which was in place.
192 192
193 193 This allows embedded IPython within IPython not to disrupt the
194 194 parent's completion.
195 195 """
196 196
197 197 try:
198 198 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
199 199 sys.ipcompleter = self.sys_ipcompleter_ori
200 200 except:
201 201 pass
202 202
203 203 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
204 204 """Activate the interactive interpreter.
205 205
206 206 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
207 207 the interpreter shell with the given local and global namespaces, and
208 208 optionally print a header string at startup.
209 209
210 210 The shell can be globally activated/deactivated using the
211 211 set/get_dummy_mode methods. This allows you to turn off a shell used
212 212 for debugging globally.
213 213
214 214 However, *each* time you call the shell you can override the current
215 215 state of dummy_mode with the optional keyword parameter 'dummy'. For
216 216 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
217 217 can still have a specific call work by making it as IPShell(dummy=0).
218 218
219 219 The optional keyword parameter dummy controls whether the call
220 220 actually does anything. """
221 221
222 222 # If the user has turned it off, go away
223 223 if not self.IP.embedded_active:
224 224 return
225 225
226 226 # Normal exits from interactive mode set this flag, so the shell can't
227 227 # re-enter (it checks this variable at the start of interactive mode).
228 228 self.IP.exit_now = False
229 229
230 230 # Allow the dummy parameter to override the global __dummy_mode
231 231 if dummy or (dummy != 0 and self.__dummy_mode):
232 232 return
233 233
234 234 # Set global subsystems (display,completions) to our values
235 235 sys.displayhook = self.sys_displayhook_embed
236 236 if self.IP.has_readline:
237 237 self.IP.set_completer()
238 238
239 239 if self.banner and header:
240 240 format = '%s\n%s\n'
241 241 else:
242 242 format = '%s%s\n'
243 243 banner = format % (self.banner,header)
244 244
245 245 # Call the embedding code with a stack depth of 1 so it can skip over
246 246 # our call and get the original caller's namespaces.
247 247 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
248 248
249 249 if self.exit_msg:
250 250 print self.exit_msg
251 251
252 252 # Restore global systems (display, completion)
253 253 sys.displayhook = self.sys_displayhook_ori
254 254 self.restore_system_completer()
255 255
256 256 def set_dummy_mode(self,dummy):
257 257 """Sets the embeddable shell's dummy mode parameter.
258 258
259 259 set_dummy_mode(dummy): dummy = 0 or 1.
260 260
261 261 This parameter is persistent and makes calls to the embeddable shell
262 262 silently return without performing any action. This allows you to
263 263 globally activate or deactivate a shell you're using with a single call.
264 264
265 265 If you need to manually"""
266 266
267 267 if dummy not in [0,1,False,True]:
268 268 raise ValueError,'dummy parameter must be boolean'
269 269 self.__dummy_mode = dummy
270 270
271 271 def get_dummy_mode(self):
272 272 """Return the current value of the dummy mode parameter.
273 273 """
274 274 return self.__dummy_mode
275 275
276 276 def set_banner(self,banner):
277 277 """Sets the global banner.
278 278
279 279 This banner gets prepended to every header printed when the shell
280 280 instance is called."""
281 281
282 282 self.banner = banner
283 283
284 284 def set_exit_msg(self,exit_msg):
285 285 """Sets the global exit_msg.
286 286
287 287 This exit message gets printed upon exiting every time the embedded
288 288 shell is called. It is None by default. """
289 289
290 290 self.exit_msg = exit_msg
291 291
292 292 #-----------------------------------------------------------------------------
293 293 if HAS_CTYPES:
294 294 # Add async exception support. Trick taken from:
295 295 # http://sebulba.wikispaces.com/recipe+thread2
296 296 def _async_raise(tid, exctype):
297 297 """raises the exception, performs cleanup if needed"""
298 298 if not inspect.isclass(exctype):
299 299 raise TypeError("Only types can be raised (not instances)")
300 300 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
301 301 ctypes.py_object(exctype))
302 302 if res == 0:
303 303 raise ValueError("invalid thread id")
304 304 elif res != 1:
305 305 # """if it returns a number greater than one, you're in trouble,
306 306 # and you should call it again with exc=NULL to revert the effect"""
307 307 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
308 308 raise SystemError("PyThreadState_SetAsyncExc failed")
309 309
310 310 def sigint_handler (signum,stack_frame):
311 311 """Sigint handler for threaded apps.
312 312
313 313 This is a horrible hack to pass information about SIGINT _without_
314 314 using exceptions, since I haven't been able to properly manage
315 315 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
316 316 done (or at least that's my understanding from a c.l.py thread where
317 317 this was discussed)."""
318 318
319 319 global KBINT
320 320
321 321 if CODE_RUN:
322 322 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
323 323 else:
324 324 KBINT = True
325 325 print '\nKeyboardInterrupt - Press <Enter> to continue.',
326 326 Term.cout.flush()
327 327
328 328 else:
329 329 def sigint_handler (signum,stack_frame):
330 330 """Sigint handler for threaded apps.
331 331
332 332 This is a horrible hack to pass information about SIGINT _without_
333 333 using exceptions, since I haven't been able to properly manage
334 334 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
335 335 done (or at least that's my understanding from a c.l.py thread where
336 336 this was discussed)."""
337 337
338 338 global KBINT
339 339
340 340 print '\nKeyboardInterrupt - Press <Enter> to continue.',
341 341 Term.cout.flush()
342 342 # Set global flag so that runsource can know that Ctrl-C was hit
343 343 KBINT = True
344 344
345 345
346 346 class MTInteractiveShell(InteractiveShell):
347 347 """Simple multi-threaded shell."""
348 348
349 349 # Threading strategy taken from:
350 350 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
351 351 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
352 352 # from the pygtk mailing list, to avoid lockups with system calls.
353 353
354 354 # class attribute to indicate whether the class supports threads or not.
355 355 # Subclasses with thread support should override this as needed.
356 356 isthreaded = True
357 357
358 358 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
359 359 user_ns=None,user_global_ns=None,banner2='',
360 360 gui_timeout=GUI_TIMEOUT,**kw):
361 361 """Similar to the normal InteractiveShell, but with threading control"""
362 362
363 363 InteractiveShell.__init__(self,name,usage,rc,user_ns,
364 364 user_global_ns,banner2)
365 365
366 366 # Timeout we wait for GUI thread
367 367 self.gui_timeout = gui_timeout
368 368
369 369 # A queue to hold the code to be executed.
370 370 self.code_queue = Queue.Queue()
371 371
372 372 # Stuff to do at closing time
373 373 self._kill = None
374 374 on_kill = kw.get('on_kill', [])
375 375 # Check that all things to kill are callable:
376 376 for t in on_kill:
377 377 if not callable(t):
378 378 raise TypeError,'on_kill must be a list of callables'
379 379 self.on_kill = on_kill
380 380 # thread identity of the "worker thread" (that may execute code directly)
381 381 self.worker_ident = None
382 382
383 383 def runsource(self, source, filename="<input>", symbol="single"):
384 384 """Compile and run some source in the interpreter.
385 385
386 386 Modified version of code.py's runsource(), to handle threading issues.
387 387 See the original for full docstring details."""
388
388
389 389 global KBINT
390 390
391 391 # If Ctrl-C was typed, we reset the flag and return right away
392 392 if KBINT:
393 393 KBINT = False
394 394 return False
395 395
396 396 if self._kill:
397 397 # can't queue new code if we are being killed
398 398 return True
399 399
400 400 try:
401 401 code = self.compile(source, filename, symbol)
402 402 except (OverflowError, SyntaxError, ValueError):
403 403 # Case 1
404 404 self.showsyntaxerror(filename)
405 405 return False
406 406
407 407 if code is None:
408 408 # Case 2
409 409 return True
410 410
411 411 # shortcut - if we are in worker thread, or the worker thread is not
412 412 # running, execute directly (to allow recursion and prevent deadlock if
413 413 # code is run early in IPython construction)
414 414
415 415 if (self.worker_ident is None
416 416 or self.worker_ident == thread.get_ident() ):
417 417 InteractiveShell.runcode(self,code)
418 return
418 return False
419 419
420 420 # Case 3
421 421 # Store code in queue, so the execution thread can handle it.
422 422
423 423 completed_ev, received_ev = threading.Event(), threading.Event()
424 424
425 425 self.code_queue.put((code,completed_ev, received_ev))
426 426 # first make sure the message was received, with timeout
427 427 received_ev.wait(self.gui_timeout)
428 428 if not received_ev.isSet():
429 429 # the mainloop is dead, start executing code directly
430 430 print "Warning: Timeout for mainloop thread exceeded"
431 431 print "switching to nonthreaded mode (until mainloop wakes up again)"
432 432 self.worker_ident = None
433 433 else:
434 434 completed_ev.wait()
435 435 return False
436 436
437 437 def runcode(self):
438 438 """Execute a code object.
439 439
440 440 Multithreaded wrapper around IPython's runcode()."""
441 441
442 442 global CODE_RUN
443 443
444 444 # we are in worker thread, stash out the id for runsource()
445 445 self.worker_ident = thread.get_ident()
446 446
447 447 if self._kill:
448 448 print >>Term.cout, 'Closing threads...',
449 449 Term.cout.flush()
450 450 for tokill in self.on_kill:
451 451 tokill()
452 452 print >>Term.cout, 'Done.'
453 453 # allow kill() to return
454 454 self._kill.set()
455 455 return True
456 456
457 457 # Install sigint handler. We do it every time to ensure that if user
458 458 # code modifies it, we restore our own handling.
459 459 try:
460 460 signal(SIGINT,sigint_handler)
461 461 except SystemError:
462 462 # This happens under Windows, which seems to have all sorts
463 463 # of problems with signal handling. Oh well...
464 464 pass
465 465
466 466 # Flush queue of pending code by calling the run methood of the parent
467 467 # class with all items which may be in the queue.
468 468 code_to_run = None
469 469 while 1:
470 470 try:
471 471 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
472 472 except Queue.Empty:
473 473 break
474 474 received_ev.set()
475 475
476 476 # Exceptions need to be raised differently depending on which
477 477 # thread is active. This convoluted try/except is only there to
478 478 # protect against asynchronous exceptions, to ensure that a KBINT
479 479 # at the wrong time doesn't deadlock everything. The global
480 480 # CODE_TO_RUN is set to true/false as close as possible to the
481 481 # runcode() call, so that the KBINT handler is correctly informed.
482 482 try:
483 483 try:
484 484 CODE_RUN = True
485 485 InteractiveShell.runcode(self,code_to_run)
486 486 except KeyboardInterrupt:
487 487 print "Keyboard interrupted in mainloop"
488 488 while not self.code_queue.empty():
489 489 code, ev1,ev2 = self.code_queue.get_nowait()
490 490 ev1.set()
491 491 ev2.set()
492 492 break
493 493 finally:
494 494 CODE_RUN = False
495 495 # allow runsource() return from wait
496 496 completed_ev.set()
497 497
498 498
499 499 # This MUST return true for gtk threading to work
500 500 return True
501 501
502 502 def kill(self):
503 503 """Kill the thread, returning when it has been shut down."""
504 504 self._kill = threading.Event()
505 505 self._kill.wait()
506 506
507 507 class MatplotlibShellBase:
508 508 """Mixin class to provide the necessary modifications to regular IPython
509 509 shell classes for matplotlib support.
510 510
511 511 Given Python's MRO, this should be used as the FIRST class in the
512 512 inheritance hierarchy, so that it overrides the relevant methods."""
513 513
514 514 def _matplotlib_config(self,name,user_ns,user_global_ns=None):
515 515 """Return items needed to setup the user's shell with matplotlib"""
516 516
517 517 # Initialize matplotlib to interactive mode always
518 518 import matplotlib
519 519 from matplotlib import backends
520 520 matplotlib.interactive(True)
521 521
522 522 def use(arg):
523 523 """IPython wrapper for matplotlib's backend switcher.
524 524
525 525 In interactive use, we can not allow switching to a different
526 526 interactive backend, since thread conflicts will most likely crash
527 527 the python interpreter. This routine does a safety check first,
528 528 and refuses to perform a dangerous switch. It still allows
529 529 switching to non-interactive backends."""
530 530
531 531 if arg in backends.interactive_bk and arg != self.mpl_backend:
532 532 m=('invalid matplotlib backend switch.\n'
533 533 'This script attempted to switch to the interactive '
534 534 'backend: `%s`\n'
535 535 'Your current choice of interactive backend is: `%s`\n\n'
536 536 'Switching interactive matplotlib backends at runtime\n'
537 537 'would crash the python interpreter, '
538 538 'and IPython has blocked it.\n\n'
539 539 'You need to either change your choice of matplotlib backend\n'
540 540 'by editing your .matplotlibrc file, or run this script as a \n'
541 541 'standalone file from the command line, not using IPython.\n' %
542 542 (arg,self.mpl_backend) )
543 543 raise RuntimeError, m
544 544 else:
545 545 self.mpl_use(arg)
546 546 self.mpl_use._called = True
547 547
548 548 self.matplotlib = matplotlib
549 549 self.mpl_backend = matplotlib.rcParams['backend']
550 550
551 551 # we also need to block switching of interactive backends by use()
552 552 self.mpl_use = matplotlib.use
553 553 self.mpl_use._called = False
554 554 # overwrite the original matplotlib.use with our wrapper
555 555 matplotlib.use = use
556 556
557 557 # This must be imported last in the matplotlib series, after
558 558 # backend/interactivity choices have been made
559 559 import matplotlib.pylab as pylab
560 560 self.pylab = pylab
561 561
562 562 self.pylab.show._needmain = False
563 563 # We need to detect at runtime whether show() is called by the user.
564 564 # For this, we wrap it into a decorator which adds a 'called' flag.
565 565 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
566 566
567 567 # Build a user namespace initialized with matplotlib/matlab features.
568 568 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
569 569 user_global_ns)
570 570
571 571 # Import numpy as np/pyplot as plt are conventions we're trying to
572 572 # somewhat standardize on. Making them available to users by default
573 573 # will greatly help this.
574 574 exec ("import numpy\n"
575 575 "import numpy as np\n"
576 576 "import matplotlib\n"
577 577 "import matplotlib.pylab as pylab\n"
578 578 "try:\n"
579 579 " import matplotlib.pyplot as plt\n"
580 580 "except ImportError:\n"
581 581 " pass\n"
582 582 ) in user_ns
583 583
584 584 # Build matplotlib info banner
585 585 b="""
586 586 Welcome to pylab, a matplotlib-based Python environment.
587 587 For more information, type 'help(pylab)'.
588 588 """
589 589 return user_ns,user_global_ns,b
590 590
591 591 def mplot_exec(self,fname,*where,**kw):
592 592 """Execute a matplotlib script.
593 593
594 594 This is a call to execfile(), but wrapped in safeties to properly
595 595 handle interactive rendering and backend switching."""
596 596
597 597 #print '*** Matplotlib runner ***' # dbg
598 598 # turn off rendering until end of script
599 599 isInteractive = self.matplotlib.rcParams['interactive']
600 600 self.matplotlib.interactive(False)
601 601 self.safe_execfile(fname,*where,**kw)
602 602 self.matplotlib.interactive(isInteractive)
603 603 # make rendering call now, if the user tried to do it
604 604 if self.pylab.draw_if_interactive.called:
605 605 self.pylab.draw()
606 606 self.pylab.draw_if_interactive.called = False
607 607
608 608 # if a backend switch was performed, reverse it now
609 609 if self.mpl_use._called:
610 610 self.matplotlib.rcParams['backend'] = self.mpl_backend
611 611
612 612 @testdec.skip_doctest
613 613 def magic_run(self,parameter_s=''):
614 614 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
615 615
616 616 # Fix the docstring so users see the original as well
617 617 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
618 618 "\n *** Modified %run for Matplotlib,"
619 619 " with proper interactive handling ***")
620 620
621 621 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
622 622 # and multithreaded. Note that these are meant for internal use, the IPShell*
623 623 # classes below are the ones meant for public consumption.
624 624
625 625 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
626 626 """Single-threaded shell with matplotlib support."""
627 627
628 628 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
629 629 user_ns=None,user_global_ns=None,**kw):
630 630 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
631 631 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
632 632 banner2=b2,**kw)
633 633
634 634 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
635 635 """Multi-threaded shell with matplotlib support."""
636 636
637 637 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
638 638 user_ns=None,user_global_ns=None, **kw):
639 639 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
640 640 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
641 641 banner2=b2,**kw)
642 642
643 643 #-----------------------------------------------------------------------------
644 644 # Utility functions for the different GUI enabled IPShell* classes.
645 645
646 646 def get_tk():
647 647 """Tries to import Tkinter and returns a withdrawn Tkinter root
648 648 window. If Tkinter is already imported or not available, this
649 649 returns None. This function calls `hijack_tk` underneath.
650 650 """
651 651 if not USE_TK or sys.modules.has_key('Tkinter'):
652 652 return None
653 653 else:
654 654 try:
655 655 import Tkinter
656 656 except ImportError:
657 657 return None
658 658 else:
659 659 hijack_tk()
660 660 r = Tkinter.Tk()
661 661 r.withdraw()
662 662 return r
663 663
664 664 def hijack_tk():
665 665 """Modifies Tkinter's mainloop with a dummy so when a module calls
666 666 mainloop, it does not block.
667 667
668 668 """
669 669 def misc_mainloop(self, n=0):
670 670 pass
671 671 def tkinter_mainloop(n=0):
672 672 pass
673 673
674 674 import Tkinter
675 675 Tkinter.Misc.mainloop = misc_mainloop
676 676 Tkinter.mainloop = tkinter_mainloop
677 677
678 678 def update_tk(tk):
679 679 """Updates the Tkinter event loop. This is typically called from
680 680 the respective WX or GTK mainloops.
681 681 """
682 682 if tk:
683 683 tk.update()
684 684
685 685 def hijack_wx():
686 686 """Modifies wxPython's MainLoop with a dummy so user code does not
687 687 block IPython. The hijacked mainloop function is returned.
688 688 """
689 689 def dummy_mainloop(*args, **kw):
690 690 pass
691 691
692 692 try:
693 693 import wx
694 694 except ImportError:
695 695 # For very old versions of WX
696 696 import wxPython as wx
697 697
698 698 ver = wx.__version__
699 699 orig_mainloop = None
700 700 if ver[:3] >= '2.5':
701 701 import wx
702 702 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
703 703 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
704 704 else: raise AttributeError('Could not find wx core module')
705 705 orig_mainloop = core.PyApp_MainLoop
706 706 core.PyApp_MainLoop = dummy_mainloop
707 707 elif ver[:3] == '2.4':
708 708 orig_mainloop = wx.wxc.wxPyApp_MainLoop
709 709 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
710 710 else:
711 711 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
712 712 return orig_mainloop
713 713
714 714 def hijack_gtk():
715 715 """Modifies pyGTK's mainloop with a dummy so user code does not
716 716 block IPython. This function returns the original `gtk.mainloop`
717 717 function that has been hijacked.
718 718 """
719 719 def dummy_mainloop(*args, **kw):
720 720 pass
721 721 import gtk
722 722 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
723 723 else: orig_mainloop = gtk.mainloop
724 724 gtk.mainloop = dummy_mainloop
725 725 gtk.main = dummy_mainloop
726 726 return orig_mainloop
727 727
728 728 def hijack_qt():
729 729 """Modifies PyQt's mainloop with a dummy so user code does not
730 730 block IPython. This function returns the original
731 731 `qt.qApp.exec_loop` function that has been hijacked.
732 732 """
733 733 def dummy_mainloop(*args, **kw):
734 734 pass
735 735 import qt
736 736 orig_mainloop = qt.qApp.exec_loop
737 737 qt.qApp.exec_loop = dummy_mainloop
738 738 qt.QApplication.exec_loop = dummy_mainloop
739 739 return orig_mainloop
740 740
741 741 def hijack_qt4():
742 742 """Modifies PyQt4's mainloop with a dummy so user code does not
743 743 block IPython. This function returns the original
744 744 `QtGui.qApp.exec_` function that has been hijacked.
745 745 """
746 746 def dummy_mainloop(*args, **kw):
747 747 pass
748 748 from PyQt4 import QtGui, QtCore
749 749 orig_mainloop = QtGui.qApp.exec_
750 750 QtGui.qApp.exec_ = dummy_mainloop
751 751 QtGui.QApplication.exec_ = dummy_mainloop
752 752 QtCore.QCoreApplication.exec_ = dummy_mainloop
753 753 return orig_mainloop
754 754
755 755 #-----------------------------------------------------------------------------
756 756 # The IPShell* classes below are the ones meant to be run by external code as
757 757 # IPython instances. Note that unless a specific threading strategy is
758 758 # desired, the factory function start() below should be used instead (it
759 759 # selects the proper threaded class).
760 760
761 761 class IPThread(threading.Thread):
762 762 def run(self):
763 763 self.IP.mainloop(self._banner)
764 764 self.IP.kill()
765 765
766 766 class IPShellGTK(IPThread):
767 767 """Run a gtk mainloop() in a separate thread.
768 768
769 769 Python commands can be passed to the thread where they will be executed.
770 770 This is implemented by periodically checking for passed code using a
771 771 GTK timeout callback."""
772 772
773 773 TIMEOUT = 100 # Millisecond interval between timeouts.
774 774
775 775 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
776 776 debug=1,shell_class=MTInteractiveShell):
777 777
778 778 import gtk
779 # Check for set_interactive, coming up in new pygtk.
780 # Disable it so that this code works, but notify
781 # the user that he has a better option as well.
782 # XXX TODO better support when set_interactive is released
783 try:
784 gtk.set_interactive(False)
785 print "Your PyGtk has set_interactive(), so you can use the"
786 print "more stable single-threaded Gtk mode."
787 print "See https://bugs.launchpad.net/ipython/+bug/270856"
788 except AttributeError:
789 pass
779 790
780 791 self.gtk = gtk
781 792 self.gtk_mainloop = hijack_gtk()
782 793
783 794 # Allows us to use both Tk and GTK.
784 795 self.tk = get_tk()
785 796
786 797 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
787 798 else: mainquit = self.gtk.mainquit
788 799
789 800 self.IP = make_IPython(argv,user_ns=user_ns,
790 801 user_global_ns=user_global_ns,
791 802 debug=debug,
792 803 shell_class=shell_class,
793 804 on_kill=[mainquit])
794 805
795 806 # HACK: slot for banner in self; it will be passed to the mainloop
796 807 # method only and .run() needs it. The actual value will be set by
797 808 # .mainloop().
798 809 self._banner = None
799 810
800 811 threading.Thread.__init__(self)
801 812
802 813 def mainloop(self,sys_exit=0,banner=None):
803 814
804 815 self._banner = banner
805 816
806 817 if self.gtk.pygtk_version >= (2,4,0):
807 818 import gobject
808 819 gobject.idle_add(self.on_timer)
809 820 else:
810 821 self.gtk.idle_add(self.on_timer)
811 822
812 823 if sys.platform != 'win32':
813 824 try:
814 825 if self.gtk.gtk_version[0] >= 2:
815 826 self.gtk.gdk.threads_init()
816 827 except AttributeError:
817 828 pass
818 829 except RuntimeError:
819 830 error('Your pyGTK likely has not been compiled with '
820 831 'threading support.\n'
821 832 'The exception printout is below.\n'
822 833 'You can either rebuild pyGTK with threads, or '
823 834 'try using \n'
824 835 'matplotlib with a different backend (like Tk or WX).\n'
825 836 'Note that matplotlib will most likely not work in its '
826 837 'current state!')
827 838 self.IP.InteractiveTB()
828 839
829 840 self.start()
830 841 self.gtk.gdk.threads_enter()
831 842 self.gtk_mainloop()
832 843 self.gtk.gdk.threads_leave()
833 844 self.join()
834 845
835 846 def on_timer(self):
836 847 """Called when GTK is idle.
837 848
838 849 Must return True always, otherwise GTK stops calling it"""
839 850
840 851 update_tk(self.tk)
841 852 self.IP.runcode()
842 853 time.sleep(0.01)
843 854 return True
844 855
845 856
846 857 class IPShellWX(IPThread):
847 858 """Run a wx mainloop() in a separate thread.
848 859
849 860 Python commands can be passed to the thread where they will be executed.
850 861 This is implemented by periodically checking for passed code using a
851 862 GTK timeout callback."""
852 863
853 864 TIMEOUT = 100 # Millisecond interval between timeouts.
854 865
855 866 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
856 867 debug=1,shell_class=MTInteractiveShell):
857 868
858 869 self.IP = make_IPython(argv,user_ns=user_ns,
859 870 user_global_ns=user_global_ns,
860 871 debug=debug,
861 872 shell_class=shell_class,
862 873 on_kill=[self.wxexit])
863 874
864 875 wantedwxversion=self.IP.rc.wxversion
865 876 if wantedwxversion!="0":
866 877 try:
867 878 import wxversion
868 879 except ImportError:
869 880 error('The wxversion module is needed for WX version selection')
870 881 else:
871 882 try:
872 883 wxversion.select(wantedwxversion)
873 884 except:
874 885 self.IP.InteractiveTB()
875 886 error('Requested wxPython version %s could not be loaded' %
876 887 wantedwxversion)
877 888
878 889 import wx
879 890
880 891 threading.Thread.__init__(self)
881 892 self.wx = wx
882 893 self.wx_mainloop = hijack_wx()
883 894
884 895 # Allows us to use both Tk and GTK.
885 896 self.tk = get_tk()
886 897
887 898 # HACK: slot for banner in self; it will be passed to the mainloop
888 899 # method only and .run() needs it. The actual value will be set by
889 900 # .mainloop().
890 901 self._banner = None
891 902
892 903 self.app = None
893 904
894 905 def wxexit(self, *args):
895 906 if self.app is not None:
896 907 self.app.agent.timer.Stop()
897 908 self.app.ExitMainLoop()
898 909
899 910 def mainloop(self,sys_exit=0,banner=None):
900 911
901 912 self._banner = banner
902 913
903 914 self.start()
904 915
905 916 class TimerAgent(self.wx.MiniFrame):
906 917 wx = self.wx
907 918 IP = self.IP
908 919 tk = self.tk
909 920 def __init__(self, parent, interval):
910 921 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
911 922 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
912 923 size=(100, 100),style=style)
913 924 self.Show(False)
914 925 self.interval = interval
915 926 self.timerId = self.wx.NewId()
916 927
917 928 def StartWork(self):
918 929 self.timer = self.wx.Timer(self, self.timerId)
919 930 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
920 931 self.timer.Start(self.interval)
921 932
922 933 def OnTimer(self, event):
923 934 update_tk(self.tk)
924 935 self.IP.runcode()
925 936
926 937 class App(self.wx.App):
927 938 wx = self.wx
928 939 TIMEOUT = self.TIMEOUT
929 940 def OnInit(self):
930 941 'Create the main window and insert the custom frame'
931 942 self.agent = TimerAgent(None, self.TIMEOUT)
932 943 self.agent.Show(False)
933 944 self.agent.StartWork()
934 945 return True
935 946
936 947 self.app = App(redirect=False)
937 948 self.wx_mainloop(self.app)
938 949 self.join()
939 950
940 951
941 952 class IPShellQt(IPThread):
942 953 """Run a Qt event loop in a separate thread.
943 954
944 955 Python commands can be passed to the thread where they will be executed.
945 956 This is implemented by periodically checking for passed code using a
946 957 Qt timer / slot."""
947 958
948 959 TIMEOUT = 100 # Millisecond interval between timeouts.
949 960
950 961 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
951 962 debug=0, shell_class=MTInteractiveShell):
952 963
953 964 import qt
954 965
955 966 self.exec_loop = hijack_qt()
956 967
957 968 # Allows us to use both Tk and QT.
958 969 self.tk = get_tk()
959 970
960 971 self.IP = make_IPython(argv,
961 972 user_ns=user_ns,
962 973 user_global_ns=user_global_ns,
963 974 debug=debug,
964 975 shell_class=shell_class,
965 976 on_kill=[qt.qApp.exit])
966 977
967 978 # HACK: slot for banner in self; it will be passed to the mainloop
968 979 # method only and .run() needs it. The actual value will be set by
969 980 # .mainloop().
970 981 self._banner = None
971 982
972 983 threading.Thread.__init__(self)
973 984
974 985 def mainloop(self, sys_exit=0, banner=None):
975 986
976 987 import qt
977 988
978 989 self._banner = banner
979 990
980 991 if qt.QApplication.startingUp():
981 992 a = qt.QApplication(sys.argv)
982 993
983 994 self.timer = qt.QTimer()
984 995 qt.QObject.connect(self.timer,
985 996 qt.SIGNAL('timeout()'),
986 997 self.on_timer)
987 998
988 999 self.start()
989 1000 self.timer.start(self.TIMEOUT, True)
990 1001 while True:
991 1002 if self.IP._kill: break
992 1003 self.exec_loop()
993 1004 self.join()
994 1005
995 1006 def on_timer(self):
996 1007 update_tk(self.tk)
997 1008 result = self.IP.runcode()
998 1009 self.timer.start(self.TIMEOUT, True)
999 1010 return result
1000 1011
1001 1012
1002 1013 class IPShellQt4(IPThread):
1003 1014 """Run a Qt event loop in a separate thread.
1004 1015
1005 1016 Python commands can be passed to the thread where they will be executed.
1006 1017 This is implemented by periodically checking for passed code using a
1007 1018 Qt timer / slot."""
1008 1019
1009 1020 TIMEOUT = 100 # Millisecond interval between timeouts.
1010 1021
1011 1022 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1012 1023 debug=0, shell_class=MTInteractiveShell):
1013 1024
1014 1025 from PyQt4 import QtCore, QtGui
1015 1026
1016 1027 try:
1017 1028 # present in PyQt4-4.2.1 or later
1018 1029 QtCore.pyqtRemoveInputHook()
1019 1030 except AttributeError:
1020 1031 pass
1021 1032
1022 1033 if QtCore.PYQT_VERSION_STR == '4.3':
1023 1034 warn('''PyQt4 version 4.3 detected.
1024 1035 If you experience repeated threading warnings, please update PyQt4.
1025 1036 ''')
1026 1037
1027 1038 self.exec_ = hijack_qt4()
1028 1039
1029 1040 # Allows us to use both Tk and QT.
1030 1041 self.tk = get_tk()
1031 1042
1032 1043 self.IP = make_IPython(argv,
1033 1044 user_ns=user_ns,
1034 1045 user_global_ns=user_global_ns,
1035 1046 debug=debug,
1036 1047 shell_class=shell_class,
1037 1048 on_kill=[QtGui.qApp.exit])
1038 1049
1039 1050 # HACK: slot for banner in self; it will be passed to the mainloop
1040 1051 # method only and .run() needs it. The actual value will be set by
1041 1052 # .mainloop().
1042 1053 self._banner = None
1043 1054
1044 1055 threading.Thread.__init__(self)
1045 1056
1046 1057 def mainloop(self, sys_exit=0, banner=None):
1047 1058
1048 1059 from PyQt4 import QtCore, QtGui
1049 1060
1050 1061 self._banner = banner
1051 1062
1052 1063 if QtGui.QApplication.startingUp():
1053 1064 a = QtGui.QApplication(sys.argv)
1054 1065
1055 1066 self.timer = QtCore.QTimer()
1056 1067 QtCore.QObject.connect(self.timer,
1057 1068 QtCore.SIGNAL('timeout()'),
1058 1069 self.on_timer)
1059 1070
1060 1071 self.start()
1061 1072 self.timer.start(self.TIMEOUT)
1062 1073 while True:
1063 1074 if self.IP._kill: break
1064 1075 self.exec_()
1065 1076 self.join()
1066 1077
1067 1078 def on_timer(self):
1068 1079 update_tk(self.tk)
1069 1080 result = self.IP.runcode()
1070 1081 self.timer.start(self.TIMEOUT)
1071 1082 return result
1072 1083
1073 1084
1074 1085 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1075 1086 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1076 1087 def _load_pylab(user_ns):
1077 1088 """Allow users to disable pulling all of pylab into the top-level
1078 1089 namespace.
1079 1090
1080 1091 This little utility must be called AFTER the actual ipython instance is
1081 1092 running, since only then will the options file have been fully parsed."""
1082 1093
1083 1094 ip = IPython.ipapi.get()
1084 1095 if ip.options.pylab_import_all:
1085 1096 ip.ex("from matplotlib.pylab import *")
1086 1097 ip.IP.user_config_ns.update(ip.user_ns)
1087 1098
1088 1099
1089 1100 class IPShellMatplotlib(IPShell):
1090 1101 """Subclass IPShell with MatplotlibShell as the internal shell.
1091 1102
1092 1103 Single-threaded class, meant for the Tk* and FLTK* backends.
1093 1104
1094 1105 Having this on a separate class simplifies the external driver code."""
1095 1106
1096 1107 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1097 1108 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1098 1109 shell_class=MatplotlibShell)
1099 1110 _load_pylab(self.IP.user_ns)
1100 1111
1101 1112 class IPShellMatplotlibGTK(IPShellGTK):
1102 1113 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1103 1114
1104 1115 Multi-threaded class, meant for the GTK* backends."""
1105 1116
1106 1117 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1107 1118 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1108 1119 shell_class=MatplotlibMTShell)
1109 1120 _load_pylab(self.IP.user_ns)
1110 1121
1111 1122 class IPShellMatplotlibWX(IPShellWX):
1112 1123 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1113 1124
1114 1125 Multi-threaded class, meant for the WX* backends."""
1115 1126
1116 1127 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1117 1128 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1118 1129 shell_class=MatplotlibMTShell)
1119 1130 _load_pylab(self.IP.user_ns)
1120 1131
1121 1132 class IPShellMatplotlibQt(IPShellQt):
1122 1133 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1123 1134
1124 1135 Multi-threaded class, meant for the Qt* backends."""
1125 1136
1126 1137 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1127 1138 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1128 1139 shell_class=MatplotlibMTShell)
1129 1140 _load_pylab(self.IP.user_ns)
1130 1141
1131 1142 class IPShellMatplotlibQt4(IPShellQt4):
1132 1143 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1133 1144
1134 1145 Multi-threaded class, meant for the Qt4* backends."""
1135 1146
1136 1147 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1137 1148 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1138 1149 shell_class=MatplotlibMTShell)
1139 1150 _load_pylab(self.IP.user_ns)
1140 1151
1141 1152 #-----------------------------------------------------------------------------
1142 1153 # Factory functions to actually start the proper thread-aware shell
1143 1154
1144 1155 def _select_shell(argv):
1145 1156 """Select a shell from the given argv vector.
1146 1157
1147 1158 This function implements the threading selection policy, allowing runtime
1148 1159 control of the threading mode, both for general users and for matplotlib.
1149 1160
1150 1161 Return:
1151 1162 Shell class to be instantiated for runtime operation.
1152 1163 """
1153 1164
1154 1165 global USE_TK
1155 1166
1156 1167 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1157 1168 'wthread' : IPShellMatplotlibWX,
1158 1169 'qthread' : IPShellMatplotlibQt,
1159 1170 'q4thread' : IPShellMatplotlibQt4,
1160 1171 'tkthread' : IPShellMatplotlib, # Tk is built-in
1161 1172 }
1162 1173
1163 1174 th_shell = {'gthread' : IPShellGTK,
1164 1175 'wthread' : IPShellWX,
1165 1176 'qthread' : IPShellQt,
1166 1177 'q4thread' : IPShellQt4,
1167 1178 'tkthread' : IPShell, # Tk is built-in
1168 1179 }
1169 1180
1170 1181 backends = {'gthread' : 'GTKAgg',
1171 1182 'wthread' : 'WXAgg',
1172 1183 'qthread' : 'QtAgg',
1173 1184 'q4thread' :'Qt4Agg',
1174 1185 'tkthread' :'TkAgg',
1175 1186 }
1176 1187
1177 1188 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1178 1189 'tkthread'])
1179 1190 user_opts = set([s.replace('-','') for s in argv[:3]])
1180 1191 special_opts = user_opts & all_opts
1181 1192
1182 1193 if 'tk' in special_opts:
1183 1194 USE_TK = True
1184 1195 special_opts.remove('tk')
1185 1196
1186 1197 if 'pylab' in special_opts:
1187 1198
1188 1199 try:
1189 1200 import matplotlib
1190 1201 except ImportError:
1191 1202 error('matplotlib could NOT be imported! Starting normal IPython.')
1192 1203 return IPShell
1193 1204
1194 1205 special_opts.remove('pylab')
1195 1206 # If there's any option left, it means the user wants to force the
1196 1207 # threading backend, else it's auto-selected from the rc file
1197 1208 if special_opts:
1198 1209 th_mode = special_opts.pop()
1199 1210 matplotlib.rcParams['backend'] = backends[th_mode]
1200 1211 else:
1201 1212 backend = matplotlib.rcParams['backend']
1202 1213 if backend.startswith('GTK'):
1203 1214 th_mode = 'gthread'
1204 1215 elif backend.startswith('WX'):
1205 1216 th_mode = 'wthread'
1206 1217 elif backend.startswith('Qt4'):
1207 1218 th_mode = 'q4thread'
1208 1219 elif backend.startswith('Qt'):
1209 1220 th_mode = 'qthread'
1210 1221 else:
1211 1222 # Any other backend, use plain Tk
1212 1223 th_mode = 'tkthread'
1213 1224
1214 1225 return mpl_shell[th_mode]
1215 1226 else:
1216 1227 # No pylab requested, just plain threads
1217 1228 try:
1218 1229 th_mode = special_opts.pop()
1219 1230 except KeyError:
1220 1231 th_mode = 'tkthread'
1221 1232 return th_shell[th_mode]
1222 1233
1223 1234
1224 1235 # This is the one which should be called by external code.
1225 1236 def start(user_ns = None):
1226 1237 """Return a running shell instance, dealing with threading options.
1227 1238
1228 1239 This is a factory function which will instantiate the proper IPython shell
1229 1240 based on the user's threading choice. Such a selector is needed because
1230 1241 different GUI toolkits require different thread handling details."""
1231 1242
1232 1243 shell = _select_shell(sys.argv)
1233 1244 return shell(user_ns = user_ns)
1234 1245
1235 1246 # Some aliases for backwards compatibility
1236 1247 IPythonShell = IPShell
1237 1248 IPythonShellEmbed = IPShellEmbed
1238 1249 #************************ End of file <Shell.py> ***************************
@@ -1,106 +1,102 b''
1 1 # encoding: utf-8
2 2
3 3 """This is the official entry point to IPython's configuration system. """
4 4
5 5 __docformat__ = "restructuredtext en"
6 6
7 7 #-------------------------------------------------------------------------------
8 8 # Copyright (C) 2008 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 os
19 19 from os.path import join as pjoin
20 20
21 21 from IPython.genutils import get_home_dir, get_ipython_dir
22 22 from IPython.external.configobj import ConfigObj
23 23
24 # Traitlets config imports
25 from IPython.config import traitlets
26 from IPython.config.config import *
27 from traitlets import *
28 24
29 25 class ConfigObjManager(object):
30 26
31 27 def __init__(self, configObj, filename):
32 28 self.current = configObj
33 29 self.current.indent_type = ' '
34 30 self.filename = filename
35 31 # self.write_default_config_file()
36 32
37 33 def get_config_obj(self):
38 34 return self.current
39 35
40 36 def update_config_obj(self, newConfig):
41 37 self.current.merge(newConfig)
42 38
43 39 def update_config_obj_from_file(self, filename):
44 40 newConfig = ConfigObj(filename, file_error=False)
45 41 self.current.merge(newConfig)
46 42
47 43 def update_config_obj_from_default_file(self, ipythondir=None):
48 44 fname = self.resolve_file_path(self.filename, ipythondir)
49 45 self.update_config_obj_from_file(fname)
50 46
51 47 def write_config_obj_to_file(self, filename):
52 48 f = open(filename, 'w')
53 49 self.current.write(f)
54 50 f.close()
55 51
56 52 def write_default_config_file(self):
57 53 ipdir = get_ipython_dir()
58 54 fname = pjoin(ipdir, self.filename)
59 55 if not os.path.isfile(fname):
60 56 print "Writing the configuration file to: " + fname
61 57 self.write_config_obj_to_file(fname)
62 58
63 59 def _import(self, key):
64 60 package = '.'.join(key.split('.')[0:-1])
65 61 obj = key.split('.')[-1]
66 62 execString = 'from %s import %s' % (package, obj)
67 63 exec execString
68 64 exec 'temp = %s' % obj
69 65 return temp
70 66
71 67 def resolve_file_path(self, filename, ipythondir = None):
72 68 """Resolve filenames into absolute paths.
73 69
74 70 This function looks in the following directories in order:
75 71
76 72 1. In the current working directory or by absolute path with ~ expanded
77 73 2. In ipythondir if that is set
78 74 3. In the IPYTHONDIR environment variable if it exists
79 75 4. In the ~/.ipython directory
80 76
81 77 Note: The IPYTHONDIR is also used by the trunk version of IPython so
82 78 changing it will also affect it was well.
83 79 """
84 80
85 81 # In cwd or by absolute path with ~ expanded
86 82 trythis = os.path.expanduser(filename)
87 83 if os.path.isfile(trythis):
88 84 return trythis
89 85
90 86 # In ipythondir if it is set
91 87 if ipythondir is not None:
92 88 trythis = pjoin(ipythondir, filename)
93 89 if os.path.isfile(trythis):
94 90 return trythis
95 91
96 92 trythis = pjoin(get_ipython_dir(), filename)
97 93 if os.path.isfile(trythis):
98 94 return trythis
99 95
100 96 return None
101 97
102 98
103 99
104 100
105 101
106 102
@@ -1,526 +1,526 b''
1 1 """Module for interactive demos using IPython.
2 2
3 3 This module implements a few classes for running Python scripts interactively
4 4 in IPython for demonstrations. With very simple markup (a few tags in
5 5 comments), you can control points where the script stops executing and returns
6 6 control to IPython.
7 7
8 8
9 9 Provided classes
10 10 ================
11 11
12 12 The classes are (see their docstrings for further details):
13 13
14 14 - Demo: pure python demos
15 15
16 16 - IPythonDemo: demos with input to be processed by IPython as if it had been
17 17 typed interactively (so magics work, as well as any other special syntax you
18 18 may have added via input prefilters).
19 19
20 20 - LineDemo: single-line version of the Demo class. These demos are executed
21 21 one line at a time, and require no markup.
22 22
23 23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
24 24 executed a line at a time, but processed via IPython).
25 25
26 26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
27 27 declares an empty marquee and a pre_cmd that clears the screen before each
28 28 block (see Subclassing below).
29 29
30 30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
31 31 classes.
32 32
33 33
34 34 Subclassing
35 35 ===========
36 36
37 37 The classes here all include a few methods meant to make customization by
38 38 subclassing more convenient. Their docstrings below have some more details:
39 39
40 40 - marquee(): generates a marquee to provide visible on-screen markers at each
41 41 block start and end.
42 42
43 43 - pre_cmd(): run right before the execution of each block.
44 44
45 45 - post_cmd(): run right after the execution of each block. If the block
46 46 raises an exception, this is NOT called.
47 47
48 48
49 49 Operation
50 50 =========
51 51
52 52 The file is run in its own empty namespace (though you can pass it a string of
53 53 arguments as if in a command line environment, and it will see those as
54 54 sys.argv). But at each stop, the global IPython namespace is updated with the
55 55 current internal demo namespace, so you can work interactively with the data
56 56 accumulated so far.
57 57
58 58 By default, each block of code is printed (with syntax highlighting) before
59 59 executing it and you have to confirm execution. This is intended to show the
60 60 code to an audience first so you can discuss it, and only proceed with
61 61 execution once you agree. There are a few tags which allow you to modify this
62 62 behavior.
63 63
64 64 The supported tags are:
65 65
66 66 # <demo> stop
67 67
68 68 Defines block boundaries, the points where IPython stops execution of the
69 69 file and returns to the interactive prompt.
70 70
71 71 You can optionally mark the stop tag with extra dashes before and after the
72 72 word 'stop', to help visually distinguish the blocks in a text editor:
73 73
74 74 # <demo> --- stop ---
75 75
76 76
77 77 # <demo> silent
78 78
79 79 Make a block execute silently (and hence automatically). Typically used in
80 80 cases where you have some boilerplate or initialization code which you need
81 81 executed but do not want to be seen in the demo.
82 82
83 83 # <demo> auto
84 84
85 85 Make a block execute automatically, but still being printed. Useful for
86 86 simple code which does not warrant discussion, since it avoids the extra
87 87 manual confirmation.
88 88
89 89 # <demo> auto_all
90 90
91 91 This tag can _only_ be in the first block, and if given it overrides the
92 92 individual auto tags to make the whole demo fully automatic (no block asks
93 93 for confirmation). It can also be given at creation time (or the attribute
94 94 set later) to override what's in the file.
95 95
96 96 While _any_ python file can be run as a Demo instance, if there are no stop
97 97 tags the whole file will run in a single block (no different that calling
98 98 first %pycat and then %run). The minimal markup to make this useful is to
99 99 place a set of stop tags; the other tags are only there to let you fine-tune
100 100 the execution.
101 101
102 102 This is probably best explained with the simple example file below. You can
103 103 copy this into a file named ex_demo.py, and try running it via:
104 104
105 105 from IPython.demo import Demo
106 106 d = Demo('ex_demo.py')
107 107 d() <--- Call the d object (omit the parens if you have autocall set to 2).
108 108
109 109 Each time you call the demo object, it runs the next block. The demo object
110 110 has a few useful methods for navigation, like again(), edit(), jump(), seek()
111 111 and back(). It can be reset for a new run via reset() or reloaded from disk
112 112 (in case you've edited the source) via reload(). See their docstrings below.
113 113
114 114
115 115 Example
116 116 =======
117 117
118 118 The following is a very simple example of a valid demo file.
119 119
120 120 #################### EXAMPLE DEMO <ex_demo.py> ###############################
121 121 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
122 122
123 123 print 'Hello, welcome to an interactive IPython demo.'
124 124
125 125 # The mark below defines a block boundary, which is a point where IPython will
126 126 # stop execution and return to the interactive prompt. The dashes are actually
127 127 # optional and used only as a visual aid to clearly separate blocks while
128 128 editing the demo code.
129 129 # <demo> stop
130 130
131 131 x = 1
132 132 y = 2
133 133
134 134 # <demo> stop
135 135
136 136 # the mark below makes this block as silent
137 137 # <demo> silent
138 138
139 139 print 'This is a silent block, which gets executed but not printed.'
140 140
141 141 # <demo> stop
142 142 # <demo> auto
143 143 print 'This is an automatic block.'
144 144 print 'It is executed without asking for confirmation, but printed.'
145 145 z = x+y
146 146
147 147 print 'z=',x
148 148
149 149 # <demo> stop
150 150 # This is just another normal block.
151 151 print 'z is now:', z
152 152
153 153 print 'bye!'
154 154 ################### END EXAMPLE DEMO <ex_demo.py> ############################
155 155 """
156 156
157 157 #*****************************************************************************
158 158 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
159 159 #
160 160 # Distributed under the terms of the BSD License. The full license is in
161 161 # the file COPYING, distributed as part of this software.
162 162 #
163 163 #*****************************************************************************
164 164
165 165 import exceptions
166 166 import os
167 167 import re
168 168 import shlex
169 169 import sys
170 170
171 171 from IPython.PyColorize import Parser
172 172 from IPython.genutils import marquee, file_read, file_readlines
173 173
174 174 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
175 175
176 176 class DemoError(exceptions.Exception): pass
177 177
178 178 def re_mark(mark):
179 179 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
180 180
181 181 class Demo(object):
182 182
183 re_stop = re_mark('-?\s?stop\s?-?')
183 re_stop = re_mark('-*\s?stop\s?-*')
184 184 re_silent = re_mark('silent')
185 185 re_auto = re_mark('auto')
186 186 re_auto_all = re_mark('auto_all')
187 187
188 188 def __init__(self,fname,arg_str='',auto_all=None):
189 189 """Make a new demo object. To run the demo, simply call the object.
190 190
191 191 See the module docstring for full details and an example (you can use
192 192 IPython.Demo? in IPython to see it).
193 193
194 194 Inputs:
195 195
196 196 - fname = filename.
197 197
198 198 Optional inputs:
199 199
200 200 - arg_str(''): a string of arguments, internally converted to a list
201 201 just like sys.argv, so the demo script can see a similar
202 202 environment.
203 203
204 204 - auto_all(None): global flag to run all blocks automatically without
205 205 confirmation. This attribute overrides the block-level tags and
206 206 applies to the whole demo. It is an attribute of the object, and
207 207 can be changed at runtime simply by reassigning it to a boolean
208 208 value.
209 209 """
210 210
211 211 self.fname = fname
212 212 self.sys_argv = [fname] + shlex.split(arg_str)
213 213 self.auto_all = auto_all
214 214
215 215 # get a few things from ipython. While it's a bit ugly design-wise,
216 216 # it ensures that things like color scheme and the like are always in
217 217 # sync with the ipython mode being used. This class is only meant to
218 218 # be used inside ipython anyways, so it's OK.
219 219 self.ip_ns = __IPYTHON__.user_ns
220 220 self.ip_colorize = __IPYTHON__.pycolorize
221 221 self.ip_showtb = __IPYTHON__.showtraceback
222 222 self.ip_runlines = __IPYTHON__.runlines
223 223 self.shell = __IPYTHON__
224 224
225 225 # load user data and initialize data structures
226 226 self.reload()
227 227
228 228 def reload(self):
229 229 """Reload source from disk and initialize state."""
230 230 # read data and parse into blocks
231 231 self.src = file_read(self.fname)
232 232 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
233 233 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
234 234 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
235 235
236 236 # if auto_all is not given (def. None), we read it from the file
237 237 if self.auto_all is None:
238 238 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
239 239 else:
240 240 self.auto_all = bool(self.auto_all)
241 241
242 242 # Clean the sources from all markup so it doesn't get displayed when
243 243 # running the demo
244 244 src_blocks = []
245 245 auto_strip = lambda s: self.re_auto.sub('',s)
246 246 for i,b in enumerate(src_b):
247 247 if self._auto[i]:
248 248 src_blocks.append(auto_strip(b))
249 249 else:
250 250 src_blocks.append(b)
251 251 # remove the auto_all marker
252 252 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
253 253
254 254 self.nblocks = len(src_blocks)
255 255 self.src_blocks = src_blocks
256 256
257 257 # also build syntax-highlighted source
258 258 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
259 259
260 260 # ensure clean namespace and seek offset
261 261 self.reset()
262 262
263 263 def reset(self):
264 264 """Reset the namespace and seek pointer to restart the demo"""
265 265 self.user_ns = {}
266 266 self.finished = False
267 267 self.block_index = 0
268 268
269 269 def _validate_index(self,index):
270 270 if index<0 or index>=self.nblocks:
271 271 raise ValueError('invalid block index %s' % index)
272 272
273 273 def _get_index(self,index):
274 274 """Get the current block index, validating and checking status.
275 275
276 276 Returns None if the demo is finished"""
277 277
278 278 if index is None:
279 279 if self.finished:
280 280 print 'Demo finished. Use reset() if you want to rerun it.'
281 281 return None
282 282 index = self.block_index
283 283 else:
284 284 self._validate_index(index)
285 285 return index
286 286
287 287 def seek(self,index):
288 288 """Move the current seek pointer to the given block.
289 289
290 290 You can use negative indices to seek from the end, with identical
291 291 semantics to those of Python lists."""
292 292 if index<0:
293 293 index = self.nblocks + index
294 294 self._validate_index(index)
295 295 self.block_index = index
296 296 self.finished = False
297 297
298 298 def back(self,num=1):
299 299 """Move the seek pointer back num blocks (default is 1)."""
300 300 self.seek(self.block_index-num)
301 301
302 302 def jump(self,num=1):
303 303 """Jump a given number of blocks relative to the current one.
304 304
305 305 The offset can be positive or negative, defaults to 1."""
306 306 self.seek(self.block_index+num)
307 307
308 308 def again(self):
309 309 """Move the seek pointer back one block and re-execute."""
310 310 self.back(1)
311 311 self()
312 312
313 313 def edit(self,index=None):
314 314 """Edit a block.
315 315
316 316 If no number is given, use the last block executed.
317 317
318 318 This edits the in-memory copy of the demo, it does NOT modify the
319 319 original source file. If you want to do that, simply open the file in
320 320 an editor and use reload() when you make changes to the file. This
321 321 method is meant to let you change a block during a demonstration for
322 322 explanatory purposes, without damaging your original script."""
323 323
324 324 index = self._get_index(index)
325 325 if index is None:
326 326 return
327 327 # decrease the index by one (unless we're at the very beginning), so
328 328 # that the default demo.edit() call opens up the sblock we've last run
329 329 if index>0:
330 330 index -= 1
331 331
332 332 filename = self.shell.mktempfile(self.src_blocks[index])
333 333 self.shell.hooks.editor(filename,1)
334 334 new_block = file_read(filename)
335 335 # update the source and colored block
336 336 self.src_blocks[index] = new_block
337 337 self.src_blocks_colored[index] = self.ip_colorize(new_block)
338 338 self.block_index = index
339 339 # call to run with the newly edited index
340 340 self()
341 341
342 342 def show(self,index=None):
343 343 """Show a single block on screen"""
344 344
345 345 index = self._get_index(index)
346 346 if index is None:
347 347 return
348 348
349 349 print self.marquee('<%s> block # %s (%s remaining)' %
350 350 (self.fname,index,self.nblocks-index-1))
351 351 sys.stdout.write(self.src_blocks_colored[index])
352 352 sys.stdout.flush()
353 353
354 354 def show_all(self):
355 355 """Show entire demo on screen, block by block"""
356 356
357 357 fname = self.fname
358 358 nblocks = self.nblocks
359 359 silent = self._silent
360 360 marquee = self.marquee
361 361 for index,block in enumerate(self.src_blocks_colored):
362 362 if silent[index]:
363 363 print marquee('<%s> SILENT block # %s (%s remaining)' %
364 364 (fname,index,nblocks-index-1))
365 365 else:
366 366 print marquee('<%s> block # %s (%s remaining)' %
367 367 (fname,index,nblocks-index-1))
368 368 print block,
369 369 sys.stdout.flush()
370 370
371 371 def runlines(self,source):
372 372 """Execute a string with one or more lines of code"""
373 373
374 374 exec source in self.user_ns
375 375
376 376 def __call__(self,index=None):
377 377 """run a block of the demo.
378 378
379 379 If index is given, it should be an integer >=1 and <= nblocks. This
380 380 means that the calling convention is one off from typical Python
381 381 lists. The reason for the inconsistency is that the demo always
382 382 prints 'Block n/N, and N is the total, so it would be very odd to use
383 383 zero-indexing here."""
384 384
385 385 index = self._get_index(index)
386 386 if index is None:
387 387 return
388 388 try:
389 389 marquee = self.marquee
390 390 next_block = self.src_blocks[index]
391 391 self.block_index += 1
392 392 if self._silent[index]:
393 393 print marquee('Executing silent block # %s (%s remaining)' %
394 394 (index,self.nblocks-index-1))
395 395 else:
396 396 self.pre_cmd()
397 397 self.show(index)
398 398 if self.auto_all or self._auto[index]:
399 399 print marquee('output:')
400 400 else:
401 401 print marquee('Press <q> to quit, <Enter> to execute...'),
402 402 ans = raw_input().strip()
403 403 if ans:
404 404 print marquee('Block NOT executed')
405 405 return
406 406 try:
407 407 save_argv = sys.argv
408 408 sys.argv = self.sys_argv
409 409 self.runlines(next_block)
410 410 self.post_cmd()
411 411 finally:
412 412 sys.argv = save_argv
413 413
414 414 except:
415 415 self.ip_showtb(filename=self.fname)
416 416 else:
417 417 self.ip_ns.update(self.user_ns)
418 418
419 419 if self.block_index == self.nblocks:
420 420 mq1 = self.marquee('END OF DEMO')
421 421 if mq1:
422 422 # avoid spurious prints if empty marquees are used
423 423 print
424 424 print mq1
425 425 print self.marquee('Use reset() if you want to rerun it.')
426 426 self.finished = True
427 427
428 428 # These methods are meant to be overridden by subclasses who may wish to
429 429 # customize the behavior of of their demos.
430 430 def marquee(self,txt='',width=78,mark='*'):
431 431 """Return the input string centered in a 'marquee'."""
432 432 return marquee(txt,width,mark)
433 433
434 434 def pre_cmd(self):
435 435 """Method called before executing each block."""
436 436 pass
437 437
438 438 def post_cmd(self):
439 439 """Method called after executing each block."""
440 440 pass
441 441
442 442
443 443 class IPythonDemo(Demo):
444 444 """Class for interactive demos with IPython's input processing applied.
445 445
446 446 This subclasses Demo, but instead of executing each block by the Python
447 447 interpreter (via exec), it actually calls IPython on it, so that any input
448 448 filters which may be in place are applied to the input block.
449 449
450 450 If you have an interactive environment which exposes special input
451 451 processing, you can use this class instead to write demo scripts which
452 452 operate exactly as if you had typed them interactively. The default Demo
453 453 class requires the input to be valid, pure Python code.
454 454 """
455 455
456 456 def runlines(self,source):
457 457 """Execute a string with one or more lines of code"""
458 458
459 459 self.shell.runlines(source)
460 460
461 461 class LineDemo(Demo):
462 462 """Demo where each line is executed as a separate block.
463 463
464 464 The input script should be valid Python code.
465 465
466 466 This class doesn't require any markup at all, and it's meant for simple
467 467 scripts (with no nesting or any kind of indentation) which consist of
468 468 multiple lines of input to be executed, one at a time, as if they had been
469 469 typed in the interactive prompt."""
470 470
471 471 def reload(self):
472 472 """Reload source from disk and initialize state."""
473 473 # read data and parse into blocks
474 474 src_b = [l for l in file_readlines(self.fname) if l.strip()]
475 475 nblocks = len(src_b)
476 476 self.src = os.linesep.join(file_readlines(self.fname))
477 477 self._silent = [False]*nblocks
478 478 self._auto = [True]*nblocks
479 479 self.auto_all = True
480 480 self.nblocks = nblocks
481 481 self.src_blocks = src_b
482 482
483 483 # also build syntax-highlighted source
484 484 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
485 485
486 486 # ensure clean namespace and seek offset
487 487 self.reset()
488 488
489 489
490 490 class IPythonLineDemo(IPythonDemo,LineDemo):
491 491 """Variant of the LineDemo class whose input is processed by IPython."""
492 492 pass
493 493
494 494
495 495 class ClearMixin(object):
496 496 """Use this mixin to make Demo classes with less visual clutter.
497 497
498 498 Demos using this mixin will clear the screen before every block and use
499 499 blank marquees.
500 500
501 501 Note that in order for the methods defined here to actually override those
502 502 of the classes it's mixed with, it must go /first/ in the inheritance
503 503 tree. For example:
504 504
505 505 class ClearIPDemo(ClearMixin,IPythonDemo): pass
506 506
507 507 will provide an IPythonDemo class with the mixin's features.
508 508 """
509 509
510 510 def marquee(self,txt='',width=78,mark='*'):
511 511 """Blank marquee that returns '' no matter what the input."""
512 512 return ''
513 513
514 514 def pre_cmd(self):
515 515 """Method called before executing each block.
516 516
517 517 This one simply clears the screen."""
518 518 os.system('clear')
519 519
520 520
521 521 class ClearDemo(ClearMixin,Demo):
522 522 pass
523 523
524 524
525 525 class ClearIPDemo(ClearMixin,IPythonDemo):
526 526 pass
@@ -1,272 +1,281 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 """ History related magics and functionality """
4 4
5 5 # Stdlib imports
6 6 import fnmatch
7 7 import os
8 8
9 9 # IPython imports
10 10 from IPython.genutils import Term, ask_yes_no
11 import IPython.ipapi
11 12
12 13 def magic_history(self, parameter_s = ''):
13 14 """Print input history (_i<n> variables), with most recent last.
14 15
15 16 %history -> print at most 40 inputs (some may be multi-line)\\
16 17 %history n -> print at most n inputs\\
17 18 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
18 19
19 20 Each input's number <n> is shown, and is accessible as the
20 21 automatically generated variable _i<n>. Multi-line statements are
21 22 printed starting at a new line for easy copy/paste.
22 23
23 24
24 25 Options:
25 26
26 27 -n: do NOT print line numbers. This is useful if you want to get a
27 28 printout of many lines which can be directly pasted into a text
28 29 editor.
29 30
30 31 This feature is only available if numbered prompts are in use.
31 32
32 33 -t: (default) print the 'translated' history, as IPython understands it.
33 34 IPython filters your input and converts it all into valid Python source
34 35 before executing it (things like magics or aliases are turned into
35 36 function calls, for example). With this option, you'll see the native
36 37 history instead of the user-entered version: '%cd /' will be seen as
37 38 '_ip.magic("%cd /")' instead of '%cd /'.
38 39
39 40 -r: print the 'raw' history, i.e. the actual commands you typed.
40 41
41 42 -g: treat the arg as a pattern to grep for in (full) history.
42 43 This includes the "shadow history" (almost all commands ever written).
43 44 Use '%hist -g' to show full shadow history (may be very long).
44 45 In shadow history, every index nuwber starts with 0.
45 46
46 47 -f FILENAME: instead of printing the output to the screen, redirect it to
47 48 the given file. The file is always overwritten, though IPython asks for
48 49 confirmation first if it already exists.
49 50
50 51
51 52 """
52 53
53 54 ip = self.api
54 55 shell = self.shell
55 56 if not shell.outputcache.do_full_cache:
56 57 print 'This feature is only available if numbered prompts are in use.'
57 58 return
58 59 opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
59 60
60 61 # Check if output to specific file was requested.
61 62 try:
62 63 outfname = opts['f']
63 64 except KeyError:
64 65 outfile = Term.cout
65 66 # We don't want to close stdout at the end!
66 67 close_at_end = False
67 68 else:
68 69 if os.path.exists(outfname):
69 70 ans = ask_yes_no("File %r exists. Overwrite?" % outfname)
70 71 if not ans:
71 72 print 'Aborting.'
72 73 return
73 74 else:
74 75 outfile = open(outfname,'w')
75 76 close_at_end = True
76 77
77 78
78 79 if opts.has_key('t'):
79 80 input_hist = shell.input_hist
80 81 elif opts.has_key('r'):
81 82 input_hist = shell.input_hist_raw
82 83 else:
83 84 input_hist = shell.input_hist
84 85
85 86
86 87 default_length = 40
87 88 pattern = None
88 89 if opts.has_key('g'):
89 90 init = 1
90 91 final = len(input_hist)
91 92 parts = parameter_s.split(None,1)
92 93 if len(parts) == 1:
93 94 parts += '*'
94 95 head, pattern = parts
95 96 pattern = "*" + pattern + "*"
96 97 elif len(args) == 0:
97 98 final = len(input_hist)
98 99 init = max(1,final-default_length)
99 100 elif len(args) == 1:
100 101 final = len(input_hist)
101 102 init = max(1,final-int(args[0]))
102 103 elif len(args) == 2:
103 104 init,final = map(int,args)
104 105 else:
105 106 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
106 107 print self.magic_hist.__doc__
107 108 return
108 109 width = len(str(final))
109 110 line_sep = ['','\n']
110 111 print_nums = not opts.has_key('n')
111 112
112 113 found = False
113 114 if pattern is not None:
114 115 sh = ip.IP.shadowhist.all()
115 116 for idx, s in sh:
116 117 if fnmatch.fnmatch(s, pattern):
117 118 print "0%d: %s" %(idx, s)
118 119 found = True
119 120
120 121 if found:
121 122 print "==="
122 123 print "shadow history ends, fetch by %rep <number> (must start with 0)"
123 124 print "=== start of normal history ==="
124 125
125 126 for in_num in range(init,final):
126 127 inline = input_hist[in_num]
127 128 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
128 129 continue
129 130
130 131 multiline = int(inline.count('\n') > 1)
131 132 if print_nums:
132 133 print >> outfile, \
133 134 '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
134 135 print >> outfile, inline,
135 136
136 137 if close_at_end:
137 138 outfile.close()
138 139
139 140
140 141
141 142 def magic_hist(self, parameter_s=''):
142 143 """Alternate name for %history."""
143 144 return self.magic_history(parameter_s)
144 145
145 146
146 147
147 148 def rep_f(self, arg):
148 149 r""" Repeat a command, or get command to input line for editing
149 150
150 151 - %rep (no arguments):
151 152
152 153 Place a string version of last computation result (stored in the special '_'
153 154 variable) to the next input prompt. Allows you to create elaborate command
154 155 lines without using copy-paste::
155 156
156 157 $ l = ["hei", "vaan"]
157 158 $ "".join(l)
158 159 ==> heivaan
159 160 $ %rep
160 161 $ heivaan_ <== cursor blinking
161 162
162 163 %rep 45
163 164
164 165 Place history line 45 to next input prompt. Use %hist to find out the
165 166 number.
166 167
167 168 %rep 1-4 6-7 3
168 169
169 170 Repeat the specified lines immediately. Input slice syntax is the same as
170 171 in %macro and %save.
171 172
172 173 %rep foo
173 174
174 175 Place the most recent line that has the substring "foo" to next input.
175 176 (e.g. 'svn ci -m foobar').
176 177
177 178 """
178 179
179 180
180 181 opts,args = self.parse_options(arg,'',mode='list')
181 182 ip = self.api
182 183 if not args:
183 184 ip.set_next_input(str(ip.user_ns["_"]))
184 185 return
185 186
186 187 if len(args) == 1 and not '-' in args[0]:
187 188 arg = args[0]
188 189 if len(arg) > 1 and arg.startswith('0'):
189 190 # get from shadow hist
190 191 num = int(arg[1:])
191 192 line = self.shadowhist.get(num)
192 193 ip.set_next_input(str(line))
193 194 return
194 195 try:
195 196 num = int(args[0])
196 197 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
197 198 return
198 199 except ValueError:
199 200 pass
200 201
201 202 for h in reversed(self.shell.input_hist_raw):
202 203 if 'rep' in h:
203 204 continue
204 205 if fnmatch.fnmatch(h,'*' + arg + '*'):
205 206 ip.set_next_input(str(h).rstrip())
206 207 return
207 208
208 209
209 210 try:
210 211 lines = self.extract_input_slices(args, True)
211 212 print "lines",lines
212 213 ip.runlines(lines)
213 214 except ValueError:
214 215 print "Not found in recent history:", args
215 216
216 217
217 218
218 219 _sentinel = object()
219 220
220 221 class ShadowHist:
221 222 def __init__(self,db):
222 223 # cmd => idx mapping
223 224 self.curidx = 0
224 225 self.db = db
226 self.disabled = False
225 227
226 228 def inc_idx(self):
227 229 idx = self.db.get('shadowhist_idx', 1)
228 230 self.db['shadowhist_idx'] = idx + 1
229 231 return idx
230 232
231 233 def add(self, ent):
232 old = self.db.hget('shadowhist', ent, _sentinel)
233 if old is not _sentinel:
234 if self.disabled:
234 235 return
235 newidx = self.inc_idx()
236 #print "new",newidx # dbg
237 self.db.hset('shadowhist',ent, newidx)
236 try:
237 old = self.db.hget('shadowhist', ent, _sentinel)
238 if old is not _sentinel:
239 return
240 newidx = self.inc_idx()
241 #print "new",newidx # dbg
242 self.db.hset('shadowhist',ent, newidx)
243 except:
244 IPython.ipapi.get().IP.showtraceback()
245 print "WARNING: disabling shadow history"
246 self.disabled = True
238 247
239 248 def all(self):
240 249 d = self.db.hdict('shadowhist')
241 250 items = [(i,s) for (s,i) in d.items()]
242 251 items.sort()
243 252 return items
244 253
245 254 def get(self, idx):
246 255 all = self.all()
247 256
248 257 for k, v in all:
249 258 #print k,v
250 259 if k == idx:
251 260 return v
252 261
253 262 def test_shist():
254 263 from IPython.Extensions import pickleshare
255 264 db = pickleshare.PickleShareDB('~/shist')
256 265 s = ShadowHist(db)
257 266 s.add('hello')
258 267 s.add('world')
259 268 s.add('hello')
260 269 s.add('hello')
261 270 s.add('karhu')
262 271 print "all",s.all()
263 272 print s.get(2)
264 273
265 274 def init_ipython(ip):
266 275 ip.expose_magic("rep",rep_f)
267 276 ip.expose_magic("hist",magic_hist)
268 277 ip.expose_magic("history",magic_history)
269 278
270 279 import ipy_completers
271 280 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
272 281 #test_shist()
@@ -1,249 +1,252 b''
1 1 """hooks for IPython.
2 2
3 3 In Python, it is possible to overwrite any method of any object if you really
4 4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 5 be overwritten by users for customization purposes. This module defines the
6 6 default versions of all such hooks, which get used by IPython if not
7 7 overridden by the user.
8 8
9 9 hooks are simple functions, but they should be declared with 'self' as their
10 10 first argument, because when activated they are registered into IPython as
11 11 instance methods. The self argument will be the IPython running instance
12 12 itself, so hooks have full access to the entire IPython object.
13 13
14 14 If you wish to define a new hook and activate it, you need to put the
15 15 necessary code into a python file which can be either imported or execfile()'d
16 16 from within your ipythonrc configuration.
17 17
18 18 For example, suppose that you have a module called 'myiphooks' in your
19 19 PYTHONPATH, which contains the following definition:
20 20
21 21 import os
22 22 import IPython.ipapi
23 23 ip = IPython.ipapi.get()
24 24
25 25 def calljed(self,filename, linenum):
26 26 "My editor hook calls the jed editor directly."
27 27 print "Calling my own editor, jed ..."
28 os.system('jed +%d %s' % (linenum,filename))
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise ipapi.TryNext()
29 30
30 31 ip.set_hook('editor', calljed)
31 32
32 33 You can then enable the functionality by doing 'import myiphooks'
33 34 somewhere in your configuration files or ipython command line.
34 35
35 36 $Id: hooks.py 2998 2008-01-31 10:06:04Z vivainio $"""
36 37
37 38 #*****************************************************************************
38 39 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 40 #
40 41 # Distributed under the terms of the BSD License. The full license is in
41 42 # the file COPYING, distributed as part of this software.
42 43 #*****************************************************************************
43 44
44 45 from IPython import Release
45 46 from IPython import ipapi
46 47 __author__ = '%s <%s>' % Release.authors['Fernando']
47 48 __license__ = Release.license
48 49 __version__ = Release.version
49 50
50 51 import os,bisect
51 52 from genutils import Term,shell
52 53 from pprint import PrettyPrinter
53 54
54 55 # List here all the default hooks. For now it's just the editor functions
55 56 # but over time we'll move here all the public API for user-accessible things.
56 57 # vds: >>
57 58 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
58 59 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
59 60 'generate_prompt', 'generate_output_prompt','shell_hook',
60 61 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook']
61 62 # vds: <<
62 63
63 64 pformat = PrettyPrinter().pformat
64 65
65 66 def editor(self,filename, linenum=None):
66 67 """Open the default editor at the given filename and linenumber.
67 68
68 69 This is IPython's default editor hook, you can use it as an example to
69 70 write your own modified one. To set your own editor function as the
70 71 new editor hook, call ip.set_hook('editor',yourfunc)."""
71 72
72 73 # IPython configures a default editor at startup by reading $EDITOR from
73 74 # the environment, and falling back on vi (unix) or notepad (win32).
74 75 editor = self.rc.editor
75 76
76 77 # marker for at which line to open the file (for existing objects)
77 78 if linenum is None or editor=='notepad':
78 79 linemark = ''
79 80 else:
80 81 linemark = '+%d' % int(linenum)
81 82
82 83 # Enclose in quotes if necessary and legal
83 84 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
84 85 editor = '"%s"' % editor
85 86
86 87 # Call the actual editor
87 os.system('%s %s %s' % (editor,linemark,filename))
88 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
89 raise ipapi.TryNext()
88 90
89 91 import tempfile
90 92 def fix_error_editor(self,filename,linenum,column,msg):
91 93 """Open the editor at the given filename, linenumber, column and
92 94 show an error message. This is used for correcting syntax errors.
93 95 The current implementation only has special support for the VIM editor,
94 96 and falls back on the 'editor' hook if VIM is not used.
95 97
96 98 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
97 99 """
98 100 def vim_quickfix_file():
99 101 t = tempfile.NamedTemporaryFile()
100 102 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
101 103 t.flush()
102 104 return t
103 105 if os.path.basename(self.rc.editor) != 'vim':
104 106 self.hooks.editor(filename,linenum)
105 107 return
106 108 t = vim_quickfix_file()
107 109 try:
108 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
110 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
111 raise ipapi.TryNext()
109 112 finally:
110 113 t.close()
111 114
112 115 # vds: >>
113 116 def synchronize_with_editor(self, filename, linenum, column):
114 117 pass
115 118 # vds: <<
116 119
117 120 class CommandChainDispatcher:
118 121 """ Dispatch calls to a chain of commands until some func can handle it
119 122
120 123 Usage: instantiate, execute "add" to add commands (with optional
121 124 priority), execute normally via f() calling mechanism.
122 125
123 126 """
124 127 def __init__(self,commands=None):
125 128 if commands is None:
126 129 self.chain = []
127 130 else:
128 131 self.chain = commands
129 132
130 133
131 134 def __call__(self,*args, **kw):
132 135 """ Command chain is called just like normal func.
133 136
134 137 This will call all funcs in chain with the same args as were given to this
135 138 function, and return the result of first func that didn't raise
136 139 TryNext """
137 140
138 141 for prio,cmd in self.chain:
139 142 #print "prio",prio,"cmd",cmd #dbg
140 143 try:
141 144 ret = cmd(*args, **kw)
142 145 return ret
143 146 except ipapi.TryNext, exc:
144 147 if exc.args or exc.kwargs:
145 148 args = exc.args
146 149 kw = exc.kwargs
147 150 # if no function will accept it, raise TryNext up to the caller
148 151 raise ipapi.TryNext
149 152
150 153 def __str__(self):
151 154 return str(self.chain)
152 155
153 156 def add(self, func, priority=0):
154 157 """ Add a func to the cmd chain with given priority """
155 158 bisect.insort(self.chain,(priority,func))
156 159
157 160 def __iter__(self):
158 161 """ Return all objects in chain.
159 162
160 163 Handy if the objects are not callable.
161 164 """
162 165 return iter(self.chain)
163 166
164 167 def result_display(self,arg):
165 168 """ Default display hook.
166 169
167 170 Called for displaying the result to the user.
168 171 """
169 172
170 173 if self.rc.pprint:
171 174 out = pformat(arg)
172 175 if '\n' in out:
173 176 # So that multi-line strings line up with the left column of
174 177 # the screen, instead of having the output prompt mess up
175 178 # their first line.
176 179 Term.cout.write('\n')
177 180 print >>Term.cout, out
178 181 else:
179 182 # By default, the interactive prompt uses repr() to display results,
180 183 # so we should honor this. Users who'd rather use a different
181 184 # mechanism can easily override this hook.
182 185 print >>Term.cout, repr(arg)
183 186 # the default display hook doesn't manipulate the value to put in history
184 187 return None
185 188
186 189 def input_prefilter(self,line):
187 190 """ Default input prefilter
188 191
189 192 This returns the line as unchanged, so that the interpreter
190 193 knows that nothing was done and proceeds with "classic" prefiltering
191 194 (%magics, !shell commands etc.).
192 195
193 196 Note that leading whitespace is not passed to this hook. Prefilter
194 197 can't alter indentation.
195 198
196 199 """
197 200 #print "attempt to rewrite",line #dbg
198 201 return line
199 202
200 203 def shutdown_hook(self):
201 204 """ default shutdown hook
202 205
203 206 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
204 207 """
205 208
206 209 #print "default shutdown hook ok" # dbg
207 210 return
208 211
209 212 def late_startup_hook(self):
210 213 """ Executed after ipython has been constructed and configured
211 214
212 215 """
213 216 #print "default startup hook ok" # dbg
214 217
215 218 def generate_prompt(self, is_continuation):
216 219 """ calculate and return a string with the prompt to display """
217 220 ip = self.api
218 221 if is_continuation:
219 222 return str(ip.IP.outputcache.prompt2)
220 223 return str(ip.IP.outputcache.prompt1)
221 224
222 225 def generate_output_prompt(self):
223 226 ip = self.api
224 227 return str(ip.IP.outputcache.prompt_out)
225 228
226 229 def shell_hook(self,cmd):
227 230 """ Run system/shell command a'la os.system() """
228 231
229 232 shell(cmd, header=self.rc.system_header, verbose=self.rc.system_verbose)
230 233
231 234 def show_in_pager(self,s):
232 235 """ Run a string through pager """
233 236 # raising TryNext here will use the default paging functionality
234 237 raise ipapi.TryNext
235 238
236 239 def pre_prompt_hook(self):
237 240 """ Run before displaying the next prompt
238 241
239 242 Use this e.g. to display output from asynchronous operations (in order
240 243 to not mess up text entry)
241 244 """
242 245
243 246 return None
244 247
245 248 def pre_runcode_hook(self):
246 249 """ Executed before running the (prefiltered) code in IPython """
247 250 return None
248 251
249 252
@@ -1,2686 +1,2695 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 9 """
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #
18 18 # Note: this code originally subclassed code.InteractiveConsole from the
19 19 # Python standard library. Over time, all of that class has been copied
20 20 # verbatim here for modifications which could not be accomplished by
21 21 # subclassing. At this point, there are no dependencies at all on the code
22 22 # module anymore (it is not even imported). The Python License (sec. 2)
23 23 # allows for this, but it's always nice to acknowledge credit where credit is
24 24 # due.
25 25 #*****************************************************************************
26 26
27 27 #****************************************************************************
28 28 # Modules and globals
29 29
30 30 from IPython import Release
31 31 __author__ = '%s <%s>\n%s <%s>' % \
32 32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 33 __license__ = Release.license
34 34 __version__ = Release.version
35 35
36 36 # Python standard modules
37 37 import __main__
38 38 import __builtin__
39 39 import StringIO
40 40 import bdb
41 41 import cPickle as pickle
42 42 import codeop
43 43 import exceptions
44 44 import glob
45 45 import inspect
46 46 import keyword
47 47 import new
48 48 import os
49 49 import pydoc
50 50 import re
51 51 import shutil
52 52 import string
53 53 import sys
54 54 import tempfile
55 55 import traceback
56 56 import types
57 57 import warnings
58 58 warnings.filterwarnings('ignore', r'.*sets module*')
59 59 from sets import Set
60 60 from pprint import pprint, pformat
61 61
62 62 # IPython's own modules
63 63 #import IPython
64 64 from IPython import Debugger,OInspect,PyColorize,ultraTB
65 65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 66 from IPython.Extensions import pickleshare
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic
71 71 from IPython.Prompts import CachedOutput
72 72 from IPython.ipstruct import Struct
73 73 from IPython.background_jobs import BackgroundJobManager
74 74 from IPython.usage import cmd_line_usage,interactive_usage
75 75 from IPython.genutils import *
76 76 from IPython.strdispatch import StrDispatch
77 77 import IPython.ipapi
78 78 import IPython.history
79 79 import IPython.prefilter as prefilter
80 80 import IPython.shadowns
81 81 # Globals
82 82
83 83 # store the builtin raw_input globally, and use this always, in case user code
84 84 # overwrites it (like wx.py.PyShell does)
85 85 raw_input_original = raw_input
86 86
87 87 # compiled regexps for autoindent management
88 88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89 89
90 90
91 91 #****************************************************************************
92 92 # Some utility function definitions
93 93
94 94 ini_spaces_re = re.compile(r'^(\s+)')
95 95
96 96 def num_ini_spaces(strng):
97 97 """Return the number of initial spaces in a string"""
98 98
99 99 ini_spaces = ini_spaces_re.match(strng)
100 100 if ini_spaces:
101 101 return ini_spaces.end()
102 102 else:
103 103 return 0
104 104
105 105 def softspace(file, newvalue):
106 106 """Copied from code.py, to remove the dependency"""
107 107
108 108 oldvalue = 0
109 109 try:
110 110 oldvalue = file.softspace
111 111 except AttributeError:
112 112 pass
113 113 try:
114 114 file.softspace = newvalue
115 115 except (AttributeError, TypeError):
116 116 # "attribute-less object" or "read-only attributes"
117 117 pass
118 118 return oldvalue
119 119
120 120
121 121 #****************************************************************************
122 122 # Local use exceptions
123 123 class SpaceInInput(exceptions.Exception): pass
124 124
125 125
126 126 #****************************************************************************
127 127 # Local use classes
128 128 class Bunch: pass
129 129
130 130 class Undefined: pass
131 131
132 132 class Quitter(object):
133 133 """Simple class to handle exit, similar to Python 2.5's.
134 134
135 135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
136 136 doesn't do (obviously, since it doesn't know about ipython)."""
137 137
138 138 def __init__(self,shell,name):
139 139 self.shell = shell
140 140 self.name = name
141 141
142 142 def __repr__(self):
143 143 return 'Type %s() to exit.' % self.name
144 144 __str__ = __repr__
145 145
146 146 def __call__(self):
147 147 self.shell.exit()
148 148
149 149 class InputList(list):
150 150 """Class to store user input.
151 151
152 152 It's basically a list, but slices return a string instead of a list, thus
153 153 allowing things like (assuming 'In' is an instance):
154 154
155 155 exec In[4:7]
156 156
157 157 or
158 158
159 159 exec In[5:9] + In[14] + In[21:25]"""
160 160
161 161 def __getslice__(self,i,j):
162 162 return ''.join(list.__getslice__(self,i,j))
163 163
164 164 class SyntaxTB(ultraTB.ListTB):
165 165 """Extension which holds some state: the last exception value"""
166 166
167 167 def __init__(self,color_scheme = 'NoColor'):
168 168 ultraTB.ListTB.__init__(self,color_scheme)
169 169 self.last_syntax_error = None
170 170
171 171 def __call__(self, etype, value, elist):
172 172 self.last_syntax_error = value
173 173 ultraTB.ListTB.__call__(self,etype,value,elist)
174 174
175 175 def clear_err_state(self):
176 176 """Return the current error state and clear it"""
177 177 e = self.last_syntax_error
178 178 self.last_syntax_error = None
179 179 return e
180 180
181 181 #****************************************************************************
182 182 # Main IPython class
183 183
184 184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
185 185 # until a full rewrite is made. I've cleaned all cross-class uses of
186 186 # attributes and methods, but too much user code out there relies on the
187 187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
188 188 #
189 189 # But at least now, all the pieces have been separated and we could, in
190 190 # principle, stop using the mixin. This will ease the transition to the
191 191 # chainsaw branch.
192 192
193 193 # For reference, the following is the list of 'self.foo' uses in the Magic
194 194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
195 195 # class, to prevent clashes.
196 196
197 197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
198 198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
199 199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
200 200 # 'self.value']
201 201
202 202 class InteractiveShell(object,Magic):
203 203 """An enhanced console for Python."""
204 204
205 205 # class attribute to indicate whether the class supports threads or not.
206 206 # Subclasses with thread support should override this as needed.
207 207 isthreaded = False
208 208
209 209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
210 210 user_ns=None,user_global_ns=None,banner2='',
211 211 custom_exceptions=((),None),embedded=False):
212 212
213 213 # log system
214 214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
215 215
216 216 # Job manager (for jobs run as background threads)
217 217 self.jobs = BackgroundJobManager()
218 218
219 219 # Store the actual shell's name
220 220 self.name = name
221 221 self.more = False
222 222
223 223 # We need to know whether the instance is meant for embedding, since
224 224 # global/local namespaces need to be handled differently in that case
225 225 self.embedded = embedded
226 226 if embedded:
227 227 # Control variable so users can, from within the embedded instance,
228 228 # permanently deactivate it.
229 229 self.embedded_active = True
230 230
231 231 # command compiler
232 232 self.compile = codeop.CommandCompiler()
233 233
234 234 # User input buffer
235 235 self.buffer = []
236 236
237 237 # Default name given in compilation of code
238 238 self.filename = '<ipython console>'
239 239
240 240 # Install our own quitter instead of the builtins. For python2.3-2.4,
241 241 # this brings in behavior like 2.5, and for 2.5 it's identical.
242 242 __builtin__.exit = Quitter(self,'exit')
243 243 __builtin__.quit = Quitter(self,'quit')
244 244
245 245 # Make an empty namespace, which extension writers can rely on both
246 246 # existing and NEVER being used by ipython itself. This gives them a
247 247 # convenient location for storing additional information and state
248 248 # their extensions may require, without fear of collisions with other
249 249 # ipython names that may develop later.
250 250 self.meta = Struct()
251 251
252 252 # Create the namespace where the user will operate. user_ns is
253 253 # normally the only one used, and it is passed to the exec calls as
254 254 # the locals argument. But we do carry a user_global_ns namespace
255 255 # given as the exec 'globals' argument, This is useful in embedding
256 256 # situations where the ipython shell opens in a context where the
257 257 # distinction between locals and globals is meaningful. For
258 258 # non-embedded contexts, it is just the same object as the user_ns dict.
259 259
260 260 # FIXME. For some strange reason, __builtins__ is showing up at user
261 261 # level as a dict instead of a module. This is a manual fix, but I
262 262 # should really track down where the problem is coming from. Alex
263 263 # Schmolck reported this problem first.
264 264
265 265 # A useful post by Alex Martelli on this topic:
266 266 # Re: inconsistent value from __builtins__
267 267 # Von: Alex Martelli <aleaxit@yahoo.com>
268 268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
269 269 # Gruppen: comp.lang.python
270 270
271 271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
272 272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
273 273 # > <type 'dict'>
274 274 # > >>> print type(__builtins__)
275 275 # > <type 'module'>
276 276 # > Is this difference in return value intentional?
277 277
278 278 # Well, it's documented that '__builtins__' can be either a dictionary
279 279 # or a module, and it's been that way for a long time. Whether it's
280 280 # intentional (or sensible), I don't know. In any case, the idea is
281 281 # that if you need to access the built-in namespace directly, you
282 282 # should start with "import __builtin__" (note, no 's') which will
283 283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
284 284
285 285 # These routines return properly built dicts as needed by the rest of
286 286 # the code, and can also be used by extension writers to generate
287 287 # properly initialized namespaces.
288 288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
289 289 user_global_ns)
290 290
291 291 # Assign namespaces
292 292 # This is the namespace where all normal user variables live
293 293 self.user_ns = user_ns
294 294 self.user_global_ns = user_global_ns
295 295 # A namespace to keep track of internal data structures to prevent
296 296 # them from cluttering user-visible stuff. Will be updated later
297 297 self.internal_ns = {}
298 298
299 299 # Namespace of system aliases. Each entry in the alias
300 300 # table must be a 2-tuple of the form (N,name), where N is the number
301 301 # of positional arguments of the alias.
302 302 self.alias_table = {}
303 303
304 304 # A table holding all the namespaces IPython deals with, so that
305 305 # introspection facilities can search easily.
306 306 self.ns_table = {'user':user_ns,
307 307 'user_global':user_global_ns,
308 308 'alias':self.alias_table,
309 309 'internal':self.internal_ns,
310 310 'builtin':__builtin__.__dict__
311 311 }
312 312 # The user namespace MUST have a pointer to the shell itself.
313 313 self.user_ns[name] = self
314 314
315 315 # We need to insert into sys.modules something that looks like a
316 316 # module but which accesses the IPython namespace, for shelve and
317 317 # pickle to work interactively. Normally they rely on getting
318 318 # everything out of __main__, but for embedding purposes each IPython
319 319 # instance has its own private namespace, so we can't go shoving
320 320 # everything into __main__.
321 321
322 322 # note, however, that we should only do this for non-embedded
323 323 # ipythons, which really mimic the __main__.__dict__ with their own
324 324 # namespace. Embedded instances, on the other hand, should not do
325 325 # this because they need to manage the user local/global namespaces
326 326 # only, but they live within a 'normal' __main__ (meaning, they
327 327 # shouldn't overtake the execution environment of the script they're
328 328 # embedded in).
329 329
330 330 if not embedded:
331 331 try:
332 332 main_name = self.user_ns['__name__']
333 333 except KeyError:
334 334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 335 else:
336 336 #print "pickle hack in place" # dbg
337 337 #print 'main_name:',main_name # dbg
338 338 sys.modules[main_name] = FakeModule(self.user_ns)
339 339
340 340 # Now that FakeModule produces a real module, we've run into a nasty
341 341 # problem: after script execution (via %run), the module where the user
342 342 # code ran is deleted. Now that this object is a true module (needed
343 343 # so docetst and other tools work correctly), the Python module
344 344 # teardown mechanism runs over it, and sets to None every variable
345 345 # present in that module. This means that later calls to functions
346 346 # defined in the script (which have become interactively visible after
347 347 # script exit) fail, because they hold references to objects that have
348 348 # become overwritten into None. The only solution I see right now is
349 349 # to protect every FakeModule used by %run by holding an internal
350 350 # reference to it. This private list will be used for that. The
351 351 # %reset command will flush it as well.
352 352 self._user_main_modules = []
353 353
354 354 # List of input with multi-line handling.
355 355 # Fill its zero entry, user counter starts at 1
356 356 self.input_hist = InputList(['\n'])
357 357 # This one will hold the 'raw' input history, without any
358 358 # pre-processing. This will allow users to retrieve the input just as
359 359 # it was exactly typed in by the user, with %hist -r.
360 360 self.input_hist_raw = InputList(['\n'])
361 361
362 362 # list of visited directories
363 363 try:
364 364 self.dir_hist = [os.getcwd()]
365 365 except OSError:
366 366 self.dir_hist = []
367 367
368 368 # dict of output history
369 369 self.output_hist = {}
370 370
371 371 # Get system encoding at startup time. Certain terminals (like Emacs
372 372 # under Win32 have it set to None, and we need to have a known valid
373 373 # encoding to use in the raw_input() method
374 374 try:
375 375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
376 376 except AttributeError:
377 377 self.stdin_encoding = 'ascii'
378 378
379 379 # dict of things NOT to alias (keywords, builtins and some magics)
380 380 no_alias = {}
381 381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
382 382 for key in keyword.kwlist + no_alias_magics:
383 383 no_alias[key] = 1
384 384 no_alias.update(__builtin__.__dict__)
385 385 self.no_alias = no_alias
386 386
387 387 # make global variables for user access to these
388 388 self.user_ns['_ih'] = self.input_hist
389 389 self.user_ns['_oh'] = self.output_hist
390 390 self.user_ns['_dh'] = self.dir_hist
391 391
392 392 # user aliases to input and output histories
393 393 self.user_ns['In'] = self.input_hist
394 394 self.user_ns['Out'] = self.output_hist
395 395
396 396 self.user_ns['_sh'] = IPython.shadowns
397 397 # Object variable to store code object waiting execution. This is
398 398 # used mainly by the multithreaded shells, but it can come in handy in
399 399 # other situations. No need to use a Queue here, since it's a single
400 400 # item which gets cleared once run.
401 401 self.code_to_run = None
402 402
403 403 # escapes for automatic behavior on the command line
404 404 self.ESC_SHELL = '!'
405 405 self.ESC_SH_CAP = '!!'
406 406 self.ESC_HELP = '?'
407 407 self.ESC_MAGIC = '%'
408 408 self.ESC_QUOTE = ','
409 409 self.ESC_QUOTE2 = ';'
410 410 self.ESC_PAREN = '/'
411 411
412 412 # And their associated handlers
413 413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
414 414 self.ESC_QUOTE : self.handle_auto,
415 415 self.ESC_QUOTE2 : self.handle_auto,
416 416 self.ESC_MAGIC : self.handle_magic,
417 417 self.ESC_HELP : self.handle_help,
418 418 self.ESC_SHELL : self.handle_shell_escape,
419 419 self.ESC_SH_CAP : self.handle_shell_escape,
420 420 }
421 421
422 422 # class initializations
423 423 Magic.__init__(self,self)
424 424
425 425 # Python source parser/formatter for syntax highlighting
426 426 pyformat = PyColorize.Parser().format
427 427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
428 428
429 429 # hooks holds pointers used for user-side customizations
430 430 self.hooks = Struct()
431 431
432 432 self.strdispatchers = {}
433 433
434 434 # Set all default hooks, defined in the IPython.hooks module.
435 435 hooks = IPython.hooks
436 436 for hook_name in hooks.__all__:
437 437 # default hooks have priority 100, i.e. low; user hooks should have
438 438 # 0-100 priority
439 439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
440 440 #print "bound hook",hook_name
441 441
442 442 # Flag to mark unconditional exit
443 443 self.exit_now = False
444 444
445 445 self.usage_min = """\
446 446 An enhanced console for Python.
447 447 Some of its features are:
448 448 - Readline support if the readline library is present.
449 449 - Tab completion in the local namespace.
450 450 - Logging of input, see command-line options.
451 451 - System shell escape via ! , eg !ls.
452 452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
453 453 - Keeps track of locally defined variables via %who, %whos.
454 454 - Show object information with a ? eg ?x or x? (use ?? for more info).
455 455 """
456 456 if usage: self.usage = usage
457 457 else: self.usage = self.usage_min
458 458
459 459 # Storage
460 460 self.rc = rc # This will hold all configuration information
461 461 self.pager = 'less'
462 462 # temporary files used for various purposes. Deleted at exit.
463 463 self.tempfiles = []
464 464
465 465 # Keep track of readline usage (later set by init_readline)
466 466 self.has_readline = False
467 467
468 468 # template for logfile headers. It gets resolved at runtime by the
469 469 # logstart method.
470 470 self.loghead_tpl = \
471 471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
472 472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
473 473 #log# opts = %s
474 474 #log# args = %s
475 475 #log# It is safe to make manual edits below here.
476 476 #log#-----------------------------------------------------------------------
477 477 """
478 478 # for pushd/popd management
479 479 try:
480 480 self.home_dir = get_home_dir()
481 481 except HomeDirError,msg:
482 482 fatal(msg)
483 483
484 484 self.dir_stack = []
485 485
486 486 # Functions to call the underlying shell.
487 487
488 488 # The first is similar to os.system, but it doesn't return a value,
489 489 # and it allows interpolation of variables in the user's namespace.
490 490 self.system = lambda cmd: \
491 491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
492 492
493 493 # These are for getoutput and getoutputerror:
494 494 self.getoutput = lambda cmd: \
495 495 getoutput(self.var_expand(cmd,depth=2),
496 496 header=self.rc.system_header,
497 497 verbose=self.rc.system_verbose)
498 498
499 499 self.getoutputerror = lambda cmd: \
500 500 getoutputerror(self.var_expand(cmd,depth=2),
501 501 header=self.rc.system_header,
502 502 verbose=self.rc.system_verbose)
503 503
504 504
505 505 # keep track of where we started running (mainly for crash post-mortem)
506 506 self.starting_dir = os.getcwd()
507 507
508 508 # Various switches which can be set
509 509 self.CACHELENGTH = 5000 # this is cheap, it's just text
510 510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
511 511 self.banner2 = banner2
512 512
513 513 # TraceBack handlers:
514 514
515 515 # Syntax error handler.
516 516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
517 517
518 518 # The interactive one is initialized with an offset, meaning we always
519 519 # want to remove the topmost item in the traceback, which is our own
520 520 # internal code. Valid modes: ['Plain','Context','Verbose']
521 521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
522 522 color_scheme='NoColor',
523 523 tb_offset = 1)
524 524
525 525 # IPython itself shouldn't crash. This will produce a detailed
526 526 # post-mortem if it does. But we only install the crash handler for
527 527 # non-threaded shells, the threaded ones use a normal verbose reporter
528 528 # and lose the crash handler. This is because exceptions in the main
529 529 # thread (such as in GUI code) propagate directly to sys.excepthook,
530 530 # and there's no point in printing crash dumps for every user exception.
531 531 if self.isthreaded:
532 532 ipCrashHandler = ultraTB.FormattedTB()
533 533 else:
534 534 from IPython import CrashHandler
535 535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
536 536 self.set_crash_handler(ipCrashHandler)
537 537
538 538 # and add any custom exception handlers the user may have specified
539 539 self.set_custom_exc(*custom_exceptions)
540 540
541 541 # indentation management
542 542 self.autoindent = False
543 543 self.indent_current_nsp = 0
544 544
545 545 # Make some aliases automatically
546 546 # Prepare list of shell aliases to auto-define
547 547 if os.name == 'posix':
548 548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
549 549 'mv mv -i','rm rm -i','cp cp -i',
550 550 'cat cat','less less','clear clear',
551 551 # a better ls
552 552 'ls ls -F',
553 553 # long ls
554 554 'll ls -lF')
555 555 # Extra ls aliases with color, which need special treatment on BSD
556 556 # variants
557 557 ls_extra = ( # color ls
558 558 'lc ls -F -o --color',
559 559 # ls normal files only
560 560 'lf ls -F -o --color %l | grep ^-',
561 561 # ls symbolic links
562 562 'lk ls -F -o --color %l | grep ^l',
563 563 # directories or links to directories,
564 564 'ldir ls -F -o --color %l | grep /$',
565 565 # things which are executable
566 566 'lx ls -F -o --color %l | grep ^-..x',
567 567 )
568 568 # The BSDs don't ship GNU ls, so they don't understand the
569 569 # --color switch out of the box
570 570 if 'bsd' in sys.platform:
571 571 ls_extra = ( # ls normal files only
572 572 'lf ls -lF | grep ^-',
573 573 # ls symbolic links
574 574 'lk ls -lF | grep ^l',
575 575 # directories or links to directories,
576 576 'ldir ls -lF | grep /$',
577 577 # things which are executable
578 578 'lx ls -lF | grep ^-..x',
579 579 )
580 580 auto_alias = auto_alias + ls_extra
581 581 elif os.name in ['nt','dos']:
582 582 auto_alias = ('ls dir /on',
583 583 'ddir dir /ad /on', 'ldir dir /ad /on',
584 584 'mkdir mkdir','rmdir rmdir','echo echo',
585 585 'ren ren','cls cls','copy copy')
586 586 else:
587 587 auto_alias = ()
588 588 self.auto_alias = [s.split(None,1) for s in auto_alias]
589 589
590 590
591 591 # Produce a public API instance
592 592 self.api = IPython.ipapi.IPApi(self)
593 593
594 594 # Call the actual (public) initializer
595 595 self.init_auto_alias()
596 596
597 597 # track which builtins we add, so we can clean up later
598 598 self.builtins_added = {}
599 599 # This method will add the necessary builtins for operation, but
600 600 # tracking what it did via the builtins_added dict.
601 601
602 602 #TODO: remove this, redundant
603 603 self.add_builtins()
604 604
605 605
606 606
607 607
608 608 # end __init__
609 609
610 610 def var_expand(self,cmd,depth=0):
611 611 """Expand python variables in a string.
612 612
613 613 The depth argument indicates how many frames above the caller should
614 614 be walked to look for the local namespace where to expand variables.
615 615
616 616 The global namespace for expansion is always the user's interactive
617 617 namespace.
618 618 """
619 619
620 620 return str(ItplNS(cmd,
621 621 self.user_ns, # globals
622 622 # Skip our own frame in searching for locals:
623 623 sys._getframe(depth+1).f_locals # locals
624 624 ))
625 625
626 626 def pre_config_initialization(self):
627 627 """Pre-configuration init method
628 628
629 629 This is called before the configuration files are processed to
630 630 prepare the services the config files might need.
631 631
632 632 self.rc already has reasonable default values at this point.
633 633 """
634 634 rc = self.rc
635 635 try:
636 636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
637 637 except exceptions.UnicodeDecodeError:
638 638 print "Your ipythondir can't be decoded to unicode!"
639 639 print "Please set HOME environment variable to something that"
640 640 print r"only has ASCII characters, e.g. c:\home"
641 641 print "Now it is",rc.ipythondir
642 642 sys.exit()
643 643 self.shadowhist = IPython.history.ShadowHist(self.db)
644 644
645 645
646 646 def post_config_initialization(self):
647 647 """Post configuration init method
648 648
649 649 This is called after the configuration files have been processed to
650 650 'finalize' the initialization."""
651 651
652 652 rc = self.rc
653 653
654 654 # Object inspector
655 655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
656 656 PyColorize.ANSICodeColors,
657 657 'NoColor',
658 658 rc.object_info_string_level)
659 659
660 660 self.rl_next_input = None
661 661 self.rl_do_indent = False
662 662 # Load readline proper
663 663 if rc.readline:
664 664 self.init_readline()
665 665
666 666
667 667 # local shortcut, this is used a LOT
668 668 self.log = self.logger.log
669 669
670 670 # Initialize cache, set in/out prompts and printing system
671 671 self.outputcache = CachedOutput(self,
672 672 rc.cache_size,
673 673 rc.pprint,
674 674 input_sep = rc.separate_in,
675 675 output_sep = rc.separate_out,
676 676 output_sep2 = rc.separate_out2,
677 677 ps1 = rc.prompt_in1,
678 678 ps2 = rc.prompt_in2,
679 679 ps_out = rc.prompt_out,
680 680 pad_left = rc.prompts_pad_left)
681 681
682 682 # user may have over-ridden the default print hook:
683 683 try:
684 684 self.outputcache.__class__.display = self.hooks.display
685 685 except AttributeError:
686 686 pass
687 687
688 688 # I don't like assigning globally to sys, because it means when
689 689 # embedding instances, each embedded instance overrides the previous
690 690 # choice. But sys.displayhook seems to be called internally by exec,
691 691 # so I don't see a way around it. We first save the original and then
692 692 # overwrite it.
693 693 self.sys_displayhook = sys.displayhook
694 694 sys.displayhook = self.outputcache
695 695
696 696 # Do a proper resetting of doctest, including the necessary displayhook
697 697 # monkeypatching
698 698 try:
699 699 doctest_reload()
700 700 except ImportError:
701 701 warn("doctest module does not exist.")
702 702
703 703 # Set user colors (don't do it in the constructor above so that it
704 704 # doesn't crash if colors option is invalid)
705 705 self.magic_colors(rc.colors)
706 706
707 707 # Set calling of pdb on exceptions
708 708 self.call_pdb = rc.pdb
709 709
710 710 # Load user aliases
711 711 for alias in rc.alias:
712 712 self.magic_alias(alias)
713 713
714 714 self.hooks.late_startup_hook()
715 715
716 716 for cmd in self.rc.autoexec:
717 717 #print "autoexec>",cmd #dbg
718 718 self.api.runlines(cmd)
719 719
720 720 batchrun = False
721 721 for batchfile in [path(arg) for arg in self.rc.args
722 722 if arg.lower().endswith('.ipy')]:
723 723 if not batchfile.isfile():
724 724 print "No such batch file:", batchfile
725 725 continue
726 726 self.api.runlines(batchfile.text())
727 727 batchrun = True
728 728 # without -i option, exit after running the batch file
729 729 if batchrun and not self.rc.interact:
730 730 self.ask_exit()
731 731
732 732 def add_builtins(self):
733 733 """Store ipython references into the builtin namespace.
734 734
735 735 Some parts of ipython operate via builtins injected here, which hold a
736 736 reference to IPython itself."""
737 737
738 738 # TODO: deprecate all of these, they are unsafe
739 739 builtins_new = dict(__IPYTHON__ = self,
740 740 ip_set_hook = self.set_hook,
741 741 jobs = self.jobs,
742 742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
743 743 ipalias = wrap_deprecated(self.ipalias),
744 744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
745 745 #_ip = self.api
746 746 )
747 747 for biname,bival in builtins_new.items():
748 748 try:
749 749 # store the orignal value so we can restore it
750 750 self.builtins_added[biname] = __builtin__.__dict__[biname]
751 751 except KeyError:
752 752 # or mark that it wasn't defined, and we'll just delete it at
753 753 # cleanup
754 754 self.builtins_added[biname] = Undefined
755 755 __builtin__.__dict__[biname] = bival
756 756
757 757 # Keep in the builtins a flag for when IPython is active. We set it
758 758 # with setdefault so that multiple nested IPythons don't clobber one
759 759 # another. Each will increase its value by one upon being activated,
760 760 # which also gives us a way to determine the nesting level.
761 761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
762 762
763 763 def clean_builtins(self):
764 764 """Remove any builtins which might have been added by add_builtins, or
765 765 restore overwritten ones to their previous values."""
766 766 for biname,bival in self.builtins_added.items():
767 767 if bival is Undefined:
768 768 del __builtin__.__dict__[biname]
769 769 else:
770 770 __builtin__.__dict__[biname] = bival
771 771 self.builtins_added.clear()
772 772
773 773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
774 774 """set_hook(name,hook) -> sets an internal IPython hook.
775 775
776 776 IPython exposes some of its internal API as user-modifiable hooks. By
777 777 adding your function to one of these hooks, you can modify IPython's
778 778 behavior to call at runtime your own routines."""
779 779
780 780 # At some point in the future, this should validate the hook before it
781 781 # accepts it. Probably at least check that the hook takes the number
782 782 # of args it's supposed to.
783 783
784 784 f = new.instancemethod(hook,self,self.__class__)
785 785
786 786 # check if the hook is for strdispatcher first
787 787 if str_key is not None:
788 788 sdp = self.strdispatchers.get(name, StrDispatch())
789 789 sdp.add_s(str_key, f, priority )
790 790 self.strdispatchers[name] = sdp
791 791 return
792 792 if re_key is not None:
793 793 sdp = self.strdispatchers.get(name, StrDispatch())
794 794 sdp.add_re(re.compile(re_key), f, priority )
795 795 self.strdispatchers[name] = sdp
796 796 return
797 797
798 798 dp = getattr(self.hooks, name, None)
799 799 if name not in IPython.hooks.__all__:
800 800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
801 801 if not dp:
802 802 dp = IPython.hooks.CommandChainDispatcher()
803 803
804 804 try:
805 805 dp.add(f,priority)
806 806 except AttributeError:
807 807 # it was not commandchain, plain old func - replace
808 808 dp = f
809 809
810 810 setattr(self.hooks,name, dp)
811 811
812 812
813 813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
814 814
815 815 def set_crash_handler(self,crashHandler):
816 816 """Set the IPython crash handler.
817 817
818 818 This must be a callable with a signature suitable for use as
819 819 sys.excepthook."""
820 820
821 821 # Install the given crash handler as the Python exception hook
822 822 sys.excepthook = crashHandler
823 823
824 824 # The instance will store a pointer to this, so that runtime code
825 825 # (such as magics) can access it. This is because during the
826 826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
827 827 # frameworks).
828 828 self.sys_excepthook = sys.excepthook
829 829
830 830
831 831 def set_custom_exc(self,exc_tuple,handler):
832 832 """set_custom_exc(exc_tuple,handler)
833 833
834 834 Set a custom exception handler, which will be called if any of the
835 835 exceptions in exc_tuple occur in the mainloop (specifically, in the
836 836 runcode() method.
837 837
838 838 Inputs:
839 839
840 840 - exc_tuple: a *tuple* of valid exceptions to call the defined
841 841 handler for. It is very important that you use a tuple, and NOT A
842 842 LIST here, because of the way Python's except statement works. If
843 843 you only want to trap a single exception, use a singleton tuple:
844 844
845 845 exc_tuple == (MyCustomException,)
846 846
847 847 - handler: this must be defined as a function with the following
848 848 basic interface: def my_handler(self,etype,value,tb).
849 849
850 850 This will be made into an instance method (via new.instancemethod)
851 851 of IPython itself, and it will be called if any of the exceptions
852 852 listed in the exc_tuple are caught. If the handler is None, an
853 853 internal basic one is used, which just prints basic info.
854 854
855 855 WARNING: by putting in your own exception handler into IPython's main
856 856 execution loop, you run a very good chance of nasty crashes. This
857 857 facility should only be used if you really know what you are doing."""
858 858
859 859 assert type(exc_tuple)==type(()) , \
860 860 "The custom exceptions must be given AS A TUPLE."
861 861
862 862 def dummy_handler(self,etype,value,tb):
863 863 print '*** Simple custom exception handler ***'
864 864 print 'Exception type :',etype
865 865 print 'Exception value:',value
866 866 print 'Traceback :',tb
867 867 print 'Source code :','\n'.join(self.buffer)
868 868
869 869 if handler is None: handler = dummy_handler
870 870
871 871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
872 872 self.custom_exceptions = exc_tuple
873 873
874 874 def set_custom_completer(self,completer,pos=0):
875 875 """set_custom_completer(completer,pos=0)
876 876
877 877 Adds a new custom completer function.
878 878
879 879 The position argument (defaults to 0) is the index in the completers
880 880 list where you want the completer to be inserted."""
881 881
882 882 newcomp = new.instancemethod(completer,self.Completer,
883 883 self.Completer.__class__)
884 884 self.Completer.matchers.insert(pos,newcomp)
885 885
886 886 def set_completer(self):
887 887 """reset readline's completer to be our own."""
888 888 self.readline.set_completer(self.Completer.complete)
889 889
890 890 def _get_call_pdb(self):
891 891 return self._call_pdb
892 892
893 893 def _set_call_pdb(self,val):
894 894
895 895 if val not in (0,1,False,True):
896 896 raise ValueError,'new call_pdb value must be boolean'
897 897
898 898 # store value in instance
899 899 self._call_pdb = val
900 900
901 901 # notify the actual exception handlers
902 902 self.InteractiveTB.call_pdb = val
903 903 if self.isthreaded:
904 904 try:
905 905 self.sys_excepthook.call_pdb = val
906 906 except:
907 907 warn('Failed to activate pdb for threaded exception handler')
908 908
909 909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
910 910 'Control auto-activation of pdb at exceptions')
911 911
912 912
913 913 # These special functions get installed in the builtin namespace, to
914 914 # provide programmatic (pure python) access to magics, aliases and system
915 915 # calls. This is important for logging, user scripting, and more.
916 916
917 917 # We are basically exposing, via normal python functions, the three
918 918 # mechanisms in which ipython offers special call modes (magics for
919 919 # internal control, aliases for direct system access via pre-selected
920 920 # names, and !cmd for calling arbitrary system commands).
921 921
922 922 def ipmagic(self,arg_s):
923 923 """Call a magic function by name.
924 924
925 925 Input: a string containing the name of the magic function to call and any
926 926 additional arguments to be passed to the magic.
927 927
928 928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
929 929 prompt:
930 930
931 931 In[1]: %name -opt foo bar
932 932
933 933 To call a magic without arguments, simply use ipmagic('name').
934 934
935 935 This provides a proper Python function to call IPython's magics in any
936 936 valid Python code you can type at the interpreter, including loops and
937 937 compound statements. It is added by IPython to the Python builtin
938 938 namespace upon initialization."""
939 939
940 940 args = arg_s.split(' ',1)
941 941 magic_name = args[0]
942 942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
943 943
944 944 try:
945 945 magic_args = args[1]
946 946 except IndexError:
947 947 magic_args = ''
948 948 fn = getattr(self,'magic_'+magic_name,None)
949 949 if fn is None:
950 950 error("Magic function `%s` not found." % magic_name)
951 951 else:
952 952 magic_args = self.var_expand(magic_args,1)
953 953 return fn(magic_args)
954 954
955 955 def ipalias(self,arg_s):
956 956 """Call an alias by name.
957 957
958 958 Input: a string containing the name of the alias to call and any
959 959 additional arguments to be passed to the magic.
960 960
961 961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
962 962 prompt:
963 963
964 964 In[1]: name -opt foo bar
965 965
966 966 To call an alias without arguments, simply use ipalias('name').
967 967
968 968 This provides a proper Python function to call IPython's aliases in any
969 969 valid Python code you can type at the interpreter, including loops and
970 970 compound statements. It is added by IPython to the Python builtin
971 971 namespace upon initialization."""
972 972
973 973 args = arg_s.split(' ',1)
974 974 alias_name = args[0]
975 975 try:
976 976 alias_args = args[1]
977 977 except IndexError:
978 978 alias_args = ''
979 979 if alias_name in self.alias_table:
980 980 self.call_alias(alias_name,alias_args)
981 981 else:
982 982 error("Alias `%s` not found." % alias_name)
983 983
984 984 def ipsystem(self,arg_s):
985 985 """Make a system call, using IPython."""
986 986
987 987 self.system(arg_s)
988 988
989 989 def complete(self,text):
990 990 """Return a sorted list of all possible completions on text.
991 991
992 992 Inputs:
993 993
994 994 - text: a string of text to be completed on.
995 995
996 996 This is a wrapper around the completion mechanism, similar to what
997 997 readline does at the command line when the TAB key is hit. By
998 998 exposing it as a method, it can be used by other non-readline
999 999 environments (such as GUIs) for text completion.
1000 1000
1001 1001 Simple usage example:
1002 1002
1003 1003 In [7]: x = 'hello'
1004 1004
1005 1005 In [8]: x
1006 1006 Out[8]: 'hello'
1007 1007
1008 1008 In [9]: print x
1009 1009 hello
1010 1010
1011 1011 In [10]: _ip.IP.complete('x.l')
1012 1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1013 1013 """
1014 1014
1015 1015 complete = self.Completer.complete
1016 1016 state = 0
1017 1017 # use a dict so we get unique keys, since ipyhton's multiple
1018 1018 # completers can return duplicates. When we make 2.4 a requirement,
1019 1019 # start using sets instead, which are faster.
1020 1020 comps = {}
1021 1021 while True:
1022 1022 newcomp = complete(text,state,line_buffer=text)
1023 1023 if newcomp is None:
1024 1024 break
1025 1025 comps[newcomp] = 1
1026 1026 state += 1
1027 1027 outcomps = comps.keys()
1028 1028 outcomps.sort()
1029 1029 #print "T:",text,"OC:",outcomps # dbg
1030 1030 #print "vars:",self.user_ns.keys()
1031 1031 return outcomps
1032 1032
1033 1033 def set_completer_frame(self, frame=None):
1034 1034 if frame:
1035 1035 self.Completer.namespace = frame.f_locals
1036 1036 self.Completer.global_namespace = frame.f_globals
1037 1037 else:
1038 1038 self.Completer.namespace = self.user_ns
1039 1039 self.Completer.global_namespace = self.user_global_ns
1040 1040
1041 1041 def init_auto_alias(self):
1042 1042 """Define some aliases automatically.
1043 1043
1044 1044 These are ALL parameter-less aliases"""
1045 1045
1046 1046 for alias,cmd in self.auto_alias:
1047 1047 self.getapi().defalias(alias,cmd)
1048 1048
1049 1049
1050 1050 def alias_table_validate(self,verbose=0):
1051 1051 """Update information about the alias table.
1052 1052
1053 1053 In particular, make sure no Python keywords/builtins are in it."""
1054 1054
1055 1055 no_alias = self.no_alias
1056 1056 for k in self.alias_table.keys():
1057 1057 if k in no_alias:
1058 1058 del self.alias_table[k]
1059 1059 if verbose:
1060 1060 print ("Deleting alias <%s>, it's a Python "
1061 1061 "keyword or builtin." % k)
1062 1062
1063 1063 def set_autoindent(self,value=None):
1064 1064 """Set the autoindent flag, checking for readline support.
1065 1065
1066 1066 If called with no arguments, it acts as a toggle."""
1067 1067
1068 1068 if not self.has_readline:
1069 1069 if os.name == 'posix':
1070 1070 warn("The auto-indent feature requires the readline library")
1071 1071 self.autoindent = 0
1072 1072 return
1073 1073 if value is None:
1074 1074 self.autoindent = not self.autoindent
1075 1075 else:
1076 1076 self.autoindent = value
1077 1077
1078 1078 def rc_set_toggle(self,rc_field,value=None):
1079 1079 """Set or toggle a field in IPython's rc config. structure.
1080 1080
1081 1081 If called with no arguments, it acts as a toggle.
1082 1082
1083 1083 If called with a non-existent field, the resulting AttributeError
1084 1084 exception will propagate out."""
1085 1085
1086 1086 rc_val = getattr(self.rc,rc_field)
1087 1087 if value is None:
1088 1088 value = not rc_val
1089 1089 setattr(self.rc,rc_field,value)
1090 1090
1091 1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1092 1092 """Install the user configuration directory.
1093 1093
1094 1094 Can be called when running for the first time or to upgrade the user's
1095 1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1096 1096 and 'upgrade'."""
1097 1097
1098 1098 def wait():
1099 1099 try:
1100 1100 raw_input("Please press <RETURN> to start IPython.")
1101 1101 except EOFError:
1102 1102 print >> Term.cout
1103 1103 print '*'*70
1104 1104
1105 1105 cwd = os.getcwd() # remember where we started
1106 1106 glb = glob.glob
1107 1107 print '*'*70
1108 1108 if mode == 'install':
1109 1109 print \
1110 1110 """Welcome to IPython. I will try to create a personal configuration directory
1111 1111 where you can customize many aspects of IPython's functionality in:\n"""
1112 1112 else:
1113 1113 print 'I am going to upgrade your configuration in:'
1114 1114
1115 1115 print ipythondir
1116 1116
1117 1117 rcdirend = os.path.join('IPython','UserConfig')
1118 1118 cfg = lambda d: os.path.join(d,rcdirend)
1119 1119 try:
1120 1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1121 1121 print "Initializing from configuration",rcdir
1122 1122 except IndexError:
1123 1123 warning = """
1124 1124 Installation error. IPython's directory was not found.
1125 1125
1126 1126 Check the following:
1127 1127
1128 1128 The ipython/IPython directory should be in a directory belonging to your
1129 1129 PYTHONPATH environment variable (that is, it should be in a directory
1130 1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1131 1131
1132 1132 IPython will create a minimal default configuration for you.
1133 1133
1134 1134 """
1135 1135 warn(warning)
1136 1136 wait()
1137 1137
1138 1138 if sys.platform =='win32':
1139 1139 inif = 'ipythonrc.ini'
1140 1140 else:
1141 1141 inif = 'ipythonrc'
1142 1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1143 1143 os.makedirs(ipythondir, mode = 0777)
1144 1144 for f, cont in minimal_setup.items():
1145 1145 open(ipythondir + '/' + f,'w').write(cont)
1146 1146
1147 1147 return
1148 1148
1149 1149 if mode == 'install':
1150 1150 try:
1151 1151 shutil.copytree(rcdir,ipythondir)
1152 1152 os.chdir(ipythondir)
1153 1153 rc_files = glb("ipythonrc*")
1154 1154 for rc_file in rc_files:
1155 1155 os.rename(rc_file,rc_file+rc_suffix)
1156 1156 except:
1157 1157 warning = """
1158 1158
1159 1159 There was a problem with the installation:
1160 1160 %s
1161 1161 Try to correct it or contact the developers if you think it's a bug.
1162 1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1163 1163 warn(warning)
1164 1164 wait()
1165 1165 return
1166 1166
1167 1167 elif mode == 'upgrade':
1168 1168 try:
1169 1169 os.chdir(ipythondir)
1170 1170 except:
1171 1171 print """
1172 1172 Can not upgrade: changing to directory %s failed. Details:
1173 1173 %s
1174 1174 """ % (ipythondir,sys.exc_info()[1])
1175 1175 wait()
1176 1176 return
1177 1177 else:
1178 1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1179 1179 for new_full_path in sources:
1180 1180 new_filename = os.path.basename(new_full_path)
1181 1181 if new_filename.startswith('ipythonrc'):
1182 1182 new_filename = new_filename + rc_suffix
1183 1183 # The config directory should only contain files, skip any
1184 1184 # directories which may be there (like CVS)
1185 1185 if os.path.isdir(new_full_path):
1186 1186 continue
1187 1187 if os.path.exists(new_filename):
1188 1188 old_file = new_filename+'.old'
1189 1189 if os.path.exists(old_file):
1190 1190 os.remove(old_file)
1191 1191 os.rename(new_filename,old_file)
1192 1192 shutil.copy(new_full_path,new_filename)
1193 1193 else:
1194 1194 raise ValueError,'unrecognized mode for install:',`mode`
1195 1195
1196 1196 # Fix line-endings to those native to each platform in the config
1197 1197 # directory.
1198 1198 try:
1199 1199 os.chdir(ipythondir)
1200 1200 except:
1201 1201 print """
1202 1202 Problem: changing to directory %s failed.
1203 1203 Details:
1204 1204 %s
1205 1205
1206 1206 Some configuration files may have incorrect line endings. This should not
1207 1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1208 1208 wait()
1209 1209 else:
1210 1210 for fname in glb('ipythonrc*'):
1211 1211 try:
1212 1212 native_line_ends(fname,backup=0)
1213 1213 except IOError:
1214 1214 pass
1215 1215
1216 1216 if mode == 'install':
1217 1217 print """
1218 1218 Successful installation!
1219 1219
1220 1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1221 1221 IPython manual (there are both HTML and PDF versions supplied with the
1222 1222 distribution) to make sure that your system environment is properly configured
1223 1223 to take advantage of IPython's features.
1224 1224
1225 1225 Important note: the configuration system has changed! The old system is
1226 1226 still in place, but its setting may be partly overridden by the settings in
1227 1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1228 1228 if some of the new settings bother you.
1229 1229
1230 1230 """
1231 1231 else:
1232 1232 print """
1233 1233 Successful upgrade!
1234 1234
1235 1235 All files in your directory:
1236 1236 %(ipythondir)s
1237 1237 which would have been overwritten by the upgrade were backed up with a .old
1238 1238 extension. If you had made particular customizations in those files you may
1239 1239 want to merge them back into the new files.""" % locals()
1240 1240 wait()
1241 1241 os.chdir(cwd)
1242 1242 # end user_setup()
1243 1243
1244 1244 def atexit_operations(self):
1245 1245 """This will be executed at the time of exit.
1246 1246
1247 1247 Saving of persistent data should be performed here. """
1248 1248
1249 1249 #print '*** IPython exit cleanup ***' # dbg
1250 1250 # input history
1251 1251 self.savehist()
1252 1252
1253 1253 # Cleanup all tempfiles left around
1254 1254 for tfile in self.tempfiles:
1255 1255 try:
1256 1256 os.unlink(tfile)
1257 1257 except OSError:
1258 1258 pass
1259 1259
1260 1260 self.hooks.shutdown_hook()
1261 1261
1262 1262 def savehist(self):
1263 1263 """Save input history to a file (via readline library)."""
1264 1264
1265 1265 if not self.has_readline:
1266 1266 return
1267 1267
1268 1268 try:
1269 1269 self.readline.write_history_file(self.histfile)
1270 1270 except:
1271 1271 print 'Unable to save IPython command history to file: ' + \
1272 1272 `self.histfile`
1273 1273
1274 1274 def reloadhist(self):
1275 1275 """Reload the input history from disk file."""
1276 1276
1277 1277 if self.has_readline:
1278 1278 try:
1279 1279 self.readline.clear_history()
1280 1280 self.readline.read_history_file(self.shell.histfile)
1281 1281 except AttributeError:
1282 1282 pass
1283 1283
1284 1284
1285 1285 def history_saving_wrapper(self, func):
1286 1286 """ Wrap func for readline history saving
1287 1287
1288 1288 Convert func into callable that saves & restores
1289 1289 history around the call """
1290 1290
1291 1291 if not self.has_readline:
1292 1292 return func
1293 1293
1294 1294 def wrapper():
1295 1295 self.savehist()
1296 1296 try:
1297 1297 func()
1298 1298 finally:
1299 1299 readline.read_history_file(self.histfile)
1300 1300 return wrapper
1301 1301
1302 1302
1303 1303 def pre_readline(self):
1304 1304 """readline hook to be used at the start of each line.
1305 1305
1306 1306 Currently it handles auto-indent only."""
1307 1307
1308 1308 #debugx('self.indent_current_nsp','pre_readline:')
1309 1309
1310 1310 if self.rl_do_indent:
1311 1311 self.readline.insert_text(self.indent_current_str())
1312 1312 if self.rl_next_input is not None:
1313 1313 self.readline.insert_text(self.rl_next_input)
1314 1314 self.rl_next_input = None
1315 1315
1316 1316 def init_readline(self):
1317 1317 """Command history completion/saving/reloading."""
1318 1318
1319 1319
1320 1320 import IPython.rlineimpl as readline
1321 1321
1322 1322 if not readline.have_readline:
1323 1323 self.has_readline = 0
1324 1324 self.readline = None
1325 1325 # no point in bugging windows users with this every time:
1326 1326 warn('Readline services not available on this platform.')
1327 1327 else:
1328 1328 sys.modules['readline'] = readline
1329 1329 import atexit
1330 1330 from IPython.completer import IPCompleter
1331 1331 self.Completer = IPCompleter(self,
1332 1332 self.user_ns,
1333 1333 self.user_global_ns,
1334 1334 self.rc.readline_omit__names,
1335 1335 self.alias_table)
1336 1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1337 1337 self.strdispatchers['complete_command'] = sdisp
1338 1338 self.Completer.custom_completers = sdisp
1339 1339 # Platform-specific configuration
1340 1340 if os.name == 'nt':
1341 1341 self.readline_startup_hook = readline.set_pre_input_hook
1342 1342 else:
1343 1343 self.readline_startup_hook = readline.set_startup_hook
1344 1344
1345 1345 # Load user's initrc file (readline config)
1346 1346 # Or if libedit is used, load editrc.
1347 1347 inputrc_name = os.environ.get('INPUTRC')
1348 1348 if inputrc_name is None:
1349 1349 home_dir = get_home_dir()
1350 1350 if home_dir is not None:
1351 1351 inputrc_name = '.inputrc'
1352 1352 if readline.uses_libedit:
1353 1353 inputrc_name = '.editrc'
1354 1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1355 1355 if os.path.isfile(inputrc_name):
1356 1356 try:
1357 1357 readline.read_init_file(inputrc_name)
1358 1358 except:
1359 1359 warn('Problems reading readline initialization file <%s>'
1360 1360 % inputrc_name)
1361 1361
1362 1362 self.has_readline = 1
1363 1363 self.readline = readline
1364 1364 # save this in sys so embedded copies can restore it properly
1365 1365 sys.ipcompleter = self.Completer.complete
1366 1366 self.set_completer()
1367 1367
1368 1368 # Configure readline according to user's prefs
1369 1369 # This is only done if GNU readline is being used. If libedit
1370 1370 # is being used (as on Leopard) the readline config is
1371 1371 # not run as the syntax for libedit is different.
1372 1372 if not readline.uses_libedit:
1373 1373 for rlcommand in self.rc.readline_parse_and_bind:
1374 1374 readline.parse_and_bind(rlcommand)
1375 1375
1376 1376 # remove some chars from the delimiters list
1377 1377 delims = readline.get_completer_delims()
1378 1378 delims = delims.translate(string._idmap,
1379 1379 self.rc.readline_remove_delims)
1380 1380 readline.set_completer_delims(delims)
1381 1381 # otherwise we end up with a monster history after a while:
1382 1382 readline.set_history_length(1000)
1383 1383 try:
1384 1384 #print '*** Reading readline history' # dbg
1385 1385 readline.read_history_file(self.histfile)
1386 1386 except IOError:
1387 1387 pass # It doesn't exist yet.
1388 1388
1389 1389 atexit.register(self.atexit_operations)
1390 1390 del atexit
1391 1391
1392 1392 # Configure auto-indent for all platforms
1393 1393 self.set_autoindent(self.rc.autoindent)
1394 1394
1395 1395 def ask_yes_no(self,prompt,default=True):
1396 1396 if self.rc.quiet:
1397 1397 return True
1398 1398 return ask_yes_no(prompt,default)
1399 1399
1400 1400 def _should_recompile(self,e):
1401 1401 """Utility routine for edit_syntax_error"""
1402 1402
1403 1403 if e.filename in ('<ipython console>','<input>','<string>',
1404 1404 '<console>','<BackgroundJob compilation>',
1405 1405 None):
1406 1406
1407 1407 return False
1408 1408 try:
1409 1409 if (self.rc.autoedit_syntax and
1410 1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1411 1411 '[Y/n] ','y')):
1412 1412 return False
1413 1413 except EOFError:
1414 1414 return False
1415 1415
1416 1416 def int0(x):
1417 1417 try:
1418 1418 return int(x)
1419 1419 except TypeError:
1420 1420 return 0
1421 1421 # always pass integer line and offset values to editor hook
1422 self.hooks.fix_error_editor(e.filename,
1423 int0(e.lineno),int0(e.offset),e.msg)
1422 try:
1423 self.hooks.fix_error_editor(e.filename,
1424 int0(e.lineno),int0(e.offset),e.msg)
1425 except IPython.ipapi.TryNext:
1426 warn('Could not open editor')
1427 return False
1424 1428 return True
1425 1429
1426 1430 def edit_syntax_error(self):
1427 1431 """The bottom half of the syntax error handler called in the main loop.
1428 1432
1429 1433 Loop until syntax error is fixed or user cancels.
1430 1434 """
1431 1435
1432 1436 while self.SyntaxTB.last_syntax_error:
1433 1437 # copy and clear last_syntax_error
1434 1438 err = self.SyntaxTB.clear_err_state()
1435 1439 if not self._should_recompile(err):
1436 1440 return
1437 1441 try:
1438 1442 # may set last_syntax_error again if a SyntaxError is raised
1439 1443 self.safe_execfile(err.filename,self.user_ns)
1440 1444 except:
1441 1445 self.showtraceback()
1442 1446 else:
1443 1447 try:
1444 1448 f = file(err.filename)
1445 1449 try:
1446 1450 sys.displayhook(f.read())
1447 1451 finally:
1448 1452 f.close()
1449 1453 except:
1450 1454 self.showtraceback()
1451 1455
1452 1456 def showsyntaxerror(self, filename=None):
1453 1457 """Display the syntax error that just occurred.
1454 1458
1455 1459 This doesn't display a stack trace because there isn't one.
1456 1460
1457 1461 If a filename is given, it is stuffed in the exception instead
1458 1462 of what was there before (because Python's parser always uses
1459 1463 "<string>" when reading from a string).
1460 1464 """
1461 1465 etype, value, last_traceback = sys.exc_info()
1462 1466
1463 1467 # See note about these variables in showtraceback() below
1464 1468 sys.last_type = etype
1465 1469 sys.last_value = value
1466 1470 sys.last_traceback = last_traceback
1467 1471
1468 1472 if filename and etype is SyntaxError:
1469 1473 # Work hard to stuff the correct filename in the exception
1470 1474 try:
1471 1475 msg, (dummy_filename, lineno, offset, line) = value
1472 1476 except:
1473 1477 # Not the format we expect; leave it alone
1474 1478 pass
1475 1479 else:
1476 1480 # Stuff in the right filename
1477 1481 try:
1478 1482 # Assume SyntaxError is a class exception
1479 1483 value = SyntaxError(msg, (filename, lineno, offset, line))
1480 1484 except:
1481 1485 # If that failed, assume SyntaxError is a string
1482 1486 value = msg, (filename, lineno, offset, line)
1483 1487 self.SyntaxTB(etype,value,[])
1484 1488
1485 1489 def debugger(self,force=False):
1486 1490 """Call the pydb/pdb debugger.
1487 1491
1488 1492 Keywords:
1489 1493
1490 1494 - force(False): by default, this routine checks the instance call_pdb
1491 1495 flag and does not actually invoke the debugger if the flag is false.
1492 1496 The 'force' option forces the debugger to activate even if the flag
1493 1497 is false.
1494 1498 """
1495 1499
1496 1500 if not (force or self.call_pdb):
1497 1501 return
1498 1502
1499 1503 if not hasattr(sys,'last_traceback'):
1500 1504 error('No traceback has been produced, nothing to debug.')
1501 1505 return
1502 1506
1503 1507 # use pydb if available
1504 1508 if Debugger.has_pydb:
1505 1509 from pydb import pm
1506 1510 else:
1507 1511 # fallback to our internal debugger
1508 1512 pm = lambda : self.InteractiveTB.debugger(force=True)
1509 1513 self.history_saving_wrapper(pm)()
1510 1514
1511 1515 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1512 1516 """Display the exception that just occurred.
1513 1517
1514 1518 If nothing is known about the exception, this is the method which
1515 1519 should be used throughout the code for presenting user tracebacks,
1516 1520 rather than directly invoking the InteractiveTB object.
1517 1521
1518 1522 A specific showsyntaxerror() also exists, but this method can take
1519 1523 care of calling it if needed, so unless you are explicitly catching a
1520 1524 SyntaxError exception, don't try to analyze the stack manually and
1521 1525 simply call this method."""
1522 1526
1523 1527
1524 1528 # Though this won't be called by syntax errors in the input line,
1525 1529 # there may be SyntaxError cases whith imported code.
1526 1530
1527 1531 try:
1528 1532 if exc_tuple is None:
1529 1533 etype, value, tb = sys.exc_info()
1530 1534 else:
1531 1535 etype, value, tb = exc_tuple
1532 1536
1533 1537 if etype is SyntaxError:
1534 1538 self.showsyntaxerror(filename)
1535 1539 elif etype is IPython.ipapi.UsageError:
1536 1540 print "UsageError:", value
1537 1541 else:
1538 1542 # WARNING: these variables are somewhat deprecated and not
1539 1543 # necessarily safe to use in a threaded environment, but tools
1540 1544 # like pdb depend on their existence, so let's set them. If we
1541 1545 # find problems in the field, we'll need to revisit their use.
1542 1546 sys.last_type = etype
1543 1547 sys.last_value = value
1544 1548 sys.last_traceback = tb
1545 1549
1546 1550 if etype in self.custom_exceptions:
1547 1551 self.CustomTB(etype,value,tb)
1548 1552 else:
1549 1553 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1550 1554 if self.InteractiveTB.call_pdb and self.has_readline:
1551 1555 # pdb mucks up readline, fix it back
1552 1556 self.set_completer()
1553 1557 except KeyboardInterrupt:
1554 1558 self.write("\nKeyboardInterrupt\n")
1555 1559
1556 1560
1557 1561
1558 1562 def mainloop(self,banner=None):
1559 1563 """Creates the local namespace and starts the mainloop.
1560 1564
1561 1565 If an optional banner argument is given, it will override the
1562 1566 internally created default banner."""
1563 1567
1564 1568 if self.rc.c: # Emulate Python's -c option
1565 1569 self.exec_init_cmd()
1566 1570 if banner is None:
1567 1571 if not self.rc.banner:
1568 1572 banner = ''
1569 1573 # banner is string? Use it directly!
1570 1574 elif isinstance(self.rc.banner,basestring):
1571 1575 banner = self.rc.banner
1572 1576 else:
1573 1577 banner = self.BANNER+self.banner2
1574 1578
1579 # if you run stuff with -c <cmd>, raw hist is not updated
1580 # ensure that it's in sync
1581 if len(self.input_hist) != len (self.input_hist_raw):
1582 self.input_hist_raw = InputList(self.input_hist)
1583
1575 1584 while 1:
1576 1585 try:
1577 1586 self.interact(banner)
1578 1587 #self.interact_with_readline()
1579 1588 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1580 1589
1581 1590 break
1582 1591 except KeyboardInterrupt:
1583 1592 # this should not be necessary, but KeyboardInterrupt
1584 1593 # handling seems rather unpredictable...
1585 1594 self.write("\nKeyboardInterrupt in interact()\n")
1586 1595
1587 1596 def exec_init_cmd(self):
1588 1597 """Execute a command given at the command line.
1589 1598
1590 1599 This emulates Python's -c option."""
1591 1600
1592 1601 #sys.argv = ['-c']
1593 1602 self.push(self.prefilter(self.rc.c, False))
1594 1603 if not self.rc.interact:
1595 1604 self.ask_exit()
1596 1605
1597 1606 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1598 1607 """Embeds IPython into a running python program.
1599 1608
1600 1609 Input:
1601 1610
1602 1611 - header: An optional header message can be specified.
1603 1612
1604 1613 - local_ns, global_ns: working namespaces. If given as None, the
1605 1614 IPython-initialized one is updated with __main__.__dict__, so that
1606 1615 program variables become visible but user-specific configuration
1607 1616 remains possible.
1608 1617
1609 1618 - stack_depth: specifies how many levels in the stack to go to
1610 1619 looking for namespaces (when local_ns and global_ns are None). This
1611 1620 allows an intermediate caller to make sure that this function gets
1612 1621 the namespace from the intended level in the stack. By default (0)
1613 1622 it will get its locals and globals from the immediate caller.
1614 1623
1615 1624 Warning: it's possible to use this in a program which is being run by
1616 1625 IPython itself (via %run), but some funny things will happen (a few
1617 1626 globals get overwritten). In the future this will be cleaned up, as
1618 1627 there is no fundamental reason why it can't work perfectly."""
1619 1628
1620 1629 # Get locals and globals from caller
1621 1630 if local_ns is None or global_ns is None:
1622 1631 call_frame = sys._getframe(stack_depth).f_back
1623 1632
1624 1633 if local_ns is None:
1625 1634 local_ns = call_frame.f_locals
1626 1635 if global_ns is None:
1627 1636 global_ns = call_frame.f_globals
1628 1637
1629 1638 # Update namespaces and fire up interpreter
1630 1639
1631 1640 # The global one is easy, we can just throw it in
1632 1641 self.user_global_ns = global_ns
1633 1642
1634 1643 # but the user/local one is tricky: ipython needs it to store internal
1635 1644 # data, but we also need the locals. We'll copy locals in the user
1636 1645 # one, but will track what got copied so we can delete them at exit.
1637 1646 # This is so that a later embedded call doesn't see locals from a
1638 1647 # previous call (which most likely existed in a separate scope).
1639 1648 local_varnames = local_ns.keys()
1640 1649 self.user_ns.update(local_ns)
1641 1650 #self.user_ns['local_ns'] = local_ns # dbg
1642 1651
1643 1652 # Patch for global embedding to make sure that things don't overwrite
1644 1653 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1645 1654 # FIXME. Test this a bit more carefully (the if.. is new)
1646 1655 if local_ns is None and global_ns is None:
1647 1656 self.user_global_ns.update(__main__.__dict__)
1648 1657
1649 1658 # make sure the tab-completer has the correct frame information, so it
1650 1659 # actually completes using the frame's locals/globals
1651 1660 self.set_completer_frame()
1652 1661
1653 1662 # before activating the interactive mode, we need to make sure that
1654 1663 # all names in the builtin namespace needed by ipython point to
1655 1664 # ourselves, and not to other instances.
1656 1665 self.add_builtins()
1657 1666
1658 1667 self.interact(header)
1659 1668
1660 1669 # now, purge out the user namespace from anything we might have added
1661 1670 # from the caller's local namespace
1662 1671 delvar = self.user_ns.pop
1663 1672 for var in local_varnames:
1664 1673 delvar(var,None)
1665 1674 # and clean builtins we may have overridden
1666 1675 self.clean_builtins()
1667 1676
1668 1677 def interact_prompt(self):
1669 1678 """ Print the prompt (in read-eval-print loop)
1670 1679
1671 1680 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1672 1681 used in standard IPython flow.
1673 1682 """
1674 1683 if self.more:
1675 1684 try:
1676 1685 prompt = self.hooks.generate_prompt(True)
1677 1686 except:
1678 1687 self.showtraceback()
1679 1688 if self.autoindent:
1680 1689 self.rl_do_indent = True
1681 1690
1682 1691 else:
1683 1692 try:
1684 1693 prompt = self.hooks.generate_prompt(False)
1685 1694 except:
1686 1695 self.showtraceback()
1687 1696 self.write(prompt)
1688 1697
1689 1698 def interact_handle_input(self,line):
1690 1699 """ Handle the input line (in read-eval-print loop)
1691 1700
1692 1701 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1693 1702 used in standard IPython flow.
1694 1703 """
1695 1704 if line.lstrip() == line:
1696 1705 self.shadowhist.add(line.strip())
1697 1706 lineout = self.prefilter(line,self.more)
1698 1707
1699 1708 if line.strip():
1700 1709 if self.more:
1701 1710 self.input_hist_raw[-1] += '%s\n' % line
1702 1711 else:
1703 1712 self.input_hist_raw.append('%s\n' % line)
1704 1713
1705 1714
1706 1715 self.more = self.push(lineout)
1707 1716 if (self.SyntaxTB.last_syntax_error and
1708 1717 self.rc.autoedit_syntax):
1709 1718 self.edit_syntax_error()
1710 1719
1711 1720 def interact_with_readline(self):
1712 1721 """ Demo of using interact_handle_input, interact_prompt
1713 1722
1714 1723 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1715 1724 it should work like this.
1716 1725 """
1717 1726 self.readline_startup_hook(self.pre_readline)
1718 1727 while not self.exit_now:
1719 1728 self.interact_prompt()
1720 1729 if self.more:
1721 1730 self.rl_do_indent = True
1722 1731 else:
1723 1732 self.rl_do_indent = False
1724 1733 line = raw_input_original().decode(self.stdin_encoding)
1725 1734 self.interact_handle_input(line)
1726 1735
1727 1736
1728 1737 def interact(self, banner=None):
1729 1738 """Closely emulate the interactive Python console.
1730 1739
1731 1740 The optional banner argument specify the banner to print
1732 1741 before the first interaction; by default it prints a banner
1733 1742 similar to the one printed by the real Python interpreter,
1734 1743 followed by the current class name in parentheses (so as not
1735 1744 to confuse this with the real interpreter -- since it's so
1736 1745 close!).
1737 1746
1738 1747 """
1739 1748
1740 1749 if self.exit_now:
1741 1750 # batch run -> do not interact
1742 1751 return
1743 1752 cprt = 'Type "copyright", "credits" or "license" for more information.'
1744 1753 if banner is None:
1745 1754 self.write("Python %s on %s\n%s\n(%s)\n" %
1746 1755 (sys.version, sys.platform, cprt,
1747 1756 self.__class__.__name__))
1748 1757 else:
1749 1758 self.write(banner)
1750 1759
1751 1760 more = 0
1752 1761
1753 1762 # Mark activity in the builtins
1754 1763 __builtin__.__dict__['__IPYTHON__active'] += 1
1755 1764
1756 1765 if self.has_readline:
1757 1766 self.readline_startup_hook(self.pre_readline)
1758 1767 # exit_now is set by a call to %Exit or %Quit, through the
1759 1768 # ask_exit callback.
1760 1769
1761 1770 while not self.exit_now:
1762 1771 self.hooks.pre_prompt_hook()
1763 1772 if more:
1764 1773 try:
1765 1774 prompt = self.hooks.generate_prompt(True)
1766 1775 except:
1767 1776 self.showtraceback()
1768 1777 if self.autoindent:
1769 1778 self.rl_do_indent = True
1770 1779
1771 1780 else:
1772 1781 try:
1773 1782 prompt = self.hooks.generate_prompt(False)
1774 1783 except:
1775 1784 self.showtraceback()
1776 1785 try:
1777 1786 line = self.raw_input(prompt,more)
1778 1787 if self.exit_now:
1779 1788 # quick exit on sys.std[in|out] close
1780 1789 break
1781 1790 if self.autoindent:
1782 1791 self.rl_do_indent = False
1783 1792
1784 1793 except KeyboardInterrupt:
1785 1794 #double-guard against keyboardinterrupts during kbdint handling
1786 1795 try:
1787 1796 self.write('\nKeyboardInterrupt\n')
1788 1797 self.resetbuffer()
1789 1798 # keep cache in sync with the prompt counter:
1790 1799 self.outputcache.prompt_count -= 1
1791 1800
1792 1801 if self.autoindent:
1793 1802 self.indent_current_nsp = 0
1794 1803 more = 0
1795 1804 except KeyboardInterrupt:
1796 1805 pass
1797 1806 except EOFError:
1798 1807 if self.autoindent:
1799 1808 self.rl_do_indent = False
1800 1809 self.readline_startup_hook(None)
1801 1810 self.write('\n')
1802 1811 self.exit()
1803 1812 except bdb.BdbQuit:
1804 1813 warn('The Python debugger has exited with a BdbQuit exception.\n'
1805 1814 'Because of how pdb handles the stack, it is impossible\n'
1806 1815 'for IPython to properly format this particular exception.\n'
1807 1816 'IPython will resume normal operation.')
1808 1817 except:
1809 1818 # exceptions here are VERY RARE, but they can be triggered
1810 1819 # asynchronously by signal handlers, for example.
1811 1820 self.showtraceback()
1812 1821 else:
1813 1822 more = self.push(line)
1814 1823 if (self.SyntaxTB.last_syntax_error and
1815 1824 self.rc.autoedit_syntax):
1816 1825 self.edit_syntax_error()
1817 1826
1818 1827 # We are off again...
1819 1828 __builtin__.__dict__['__IPYTHON__active'] -= 1
1820 1829
1821 1830 def excepthook(self, etype, value, tb):
1822 1831 """One more defense for GUI apps that call sys.excepthook.
1823 1832
1824 1833 GUI frameworks like wxPython trap exceptions and call
1825 1834 sys.excepthook themselves. I guess this is a feature that
1826 1835 enables them to keep running after exceptions that would
1827 1836 otherwise kill their mainloop. This is a bother for IPython
1828 1837 which excepts to catch all of the program exceptions with a try:
1829 1838 except: statement.
1830 1839
1831 1840 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1832 1841 any app directly invokes sys.excepthook, it will look to the user like
1833 1842 IPython crashed. In order to work around this, we can disable the
1834 1843 CrashHandler and replace it with this excepthook instead, which prints a
1835 1844 regular traceback using our InteractiveTB. In this fashion, apps which
1836 1845 call sys.excepthook will generate a regular-looking exception from
1837 1846 IPython, and the CrashHandler will only be triggered by real IPython
1838 1847 crashes.
1839 1848
1840 1849 This hook should be used sparingly, only in places which are not likely
1841 1850 to be true IPython errors.
1842 1851 """
1843 1852 self.showtraceback((etype,value,tb),tb_offset=0)
1844 1853
1845 1854 def expand_aliases(self,fn,rest):
1846 1855 """ Expand multiple levels of aliases:
1847 1856
1848 1857 if:
1849 1858
1850 1859 alias foo bar /tmp
1851 1860 alias baz foo
1852 1861
1853 1862 then:
1854 1863
1855 1864 baz huhhahhei -> bar /tmp huhhahhei
1856 1865
1857 1866 """
1858 1867 line = fn + " " + rest
1859 1868
1860 1869 done = Set()
1861 1870 while 1:
1862 1871 pre,fn,rest = prefilter.splitUserInput(line,
1863 1872 prefilter.shell_line_split)
1864 1873 if fn in self.alias_table:
1865 1874 if fn in done:
1866 1875 warn("Cyclic alias definition, repeated '%s'" % fn)
1867 1876 return ""
1868 1877 done.add(fn)
1869 1878
1870 1879 l2 = self.transform_alias(fn,rest)
1871 1880 # dir -> dir
1872 1881 # print "alias",line, "->",l2 #dbg
1873 1882 if l2 == line:
1874 1883 break
1875 1884 # ls -> ls -F should not recurse forever
1876 1885 if l2.split(None,1)[0] == line.split(None,1)[0]:
1877 1886 line = l2
1878 1887 break
1879 1888
1880 1889 line=l2
1881 1890
1882 1891
1883 1892 # print "al expand to",line #dbg
1884 1893 else:
1885 1894 break
1886 1895
1887 1896 return line
1888 1897
1889 1898 def transform_alias(self, alias,rest=''):
1890 1899 """ Transform alias to system command string.
1891 1900 """
1892 1901 trg = self.alias_table[alias]
1893 1902
1894 1903 nargs,cmd = trg
1895 1904 # print trg #dbg
1896 1905 if ' ' in cmd and os.path.isfile(cmd):
1897 1906 cmd = '"%s"' % cmd
1898 1907
1899 1908 # Expand the %l special to be the user's input line
1900 1909 if cmd.find('%l') >= 0:
1901 1910 cmd = cmd.replace('%l',rest)
1902 1911 rest = ''
1903 1912 if nargs==0:
1904 1913 # Simple, argument-less aliases
1905 1914 cmd = '%s %s' % (cmd,rest)
1906 1915 else:
1907 1916 # Handle aliases with positional arguments
1908 1917 args = rest.split(None,nargs)
1909 1918 if len(args)< nargs:
1910 1919 error('Alias <%s> requires %s arguments, %s given.' %
1911 1920 (alias,nargs,len(args)))
1912 1921 return None
1913 1922 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1914 1923 # Now call the macro, evaluating in the user's namespace
1915 1924 #print 'new command: <%r>' % cmd # dbg
1916 1925 return cmd
1917 1926
1918 1927 def call_alias(self,alias,rest=''):
1919 1928 """Call an alias given its name and the rest of the line.
1920 1929
1921 1930 This is only used to provide backwards compatibility for users of
1922 1931 ipalias(), use of which is not recommended for anymore."""
1923 1932
1924 1933 # Now call the macro, evaluating in the user's namespace
1925 1934 cmd = self.transform_alias(alias, rest)
1926 1935 try:
1927 1936 self.system(cmd)
1928 1937 except:
1929 1938 self.showtraceback()
1930 1939
1931 1940 def indent_current_str(self):
1932 1941 """return the current level of indentation as a string"""
1933 1942 return self.indent_current_nsp * ' '
1934 1943
1935 1944 def autoindent_update(self,line):
1936 1945 """Keep track of the indent level."""
1937 1946
1938 1947 #debugx('line')
1939 1948 #debugx('self.indent_current_nsp')
1940 1949 if self.autoindent:
1941 1950 if line:
1942 1951 inisp = num_ini_spaces(line)
1943 1952 if inisp < self.indent_current_nsp:
1944 1953 self.indent_current_nsp = inisp
1945 1954
1946 1955 if line[-1] == ':':
1947 1956 self.indent_current_nsp += 4
1948 1957 elif dedent_re.match(line):
1949 1958 self.indent_current_nsp -= 4
1950 1959 else:
1951 1960 self.indent_current_nsp = 0
1952 1961
1953 1962 def runlines(self,lines):
1954 1963 """Run a string of one or more lines of source.
1955 1964
1956 1965 This method is capable of running a string containing multiple source
1957 1966 lines, as if they had been entered at the IPython prompt. Since it
1958 1967 exposes IPython's processing machinery, the given strings can contain
1959 1968 magic calls (%magic), special shell access (!cmd), etc."""
1960 1969
1961 1970 # We must start with a clean buffer, in case this is run from an
1962 1971 # interactive IPython session (via a magic, for example).
1963 1972 self.resetbuffer()
1964 1973 lines = lines.split('\n')
1965 1974 more = 0
1966 1975
1967 1976 for line in lines:
1968 1977 # skip blank lines so we don't mess up the prompt counter, but do
1969 1978 # NOT skip even a blank line if we are in a code block (more is
1970 1979 # true)
1971 1980
1972 1981
1973 1982 if line or more:
1974 1983 # push to raw history, so hist line numbers stay in sync
1975 1984 self.input_hist_raw.append("# " + line + "\n")
1976 1985 more = self.push(self.prefilter(line,more))
1977 1986 # IPython's runsource returns None if there was an error
1978 1987 # compiling the code. This allows us to stop processing right
1979 1988 # away, so the user gets the error message at the right place.
1980 1989 if more is None:
1981 1990 break
1982 1991 else:
1983 1992 self.input_hist_raw.append("\n")
1984 1993 # final newline in case the input didn't have it, so that the code
1985 1994 # actually does get executed
1986 1995 if more:
1987 1996 self.push('\n')
1988 1997
1989 1998 def runsource(self, source, filename='<input>', symbol='single'):
1990 1999 """Compile and run some source in the interpreter.
1991 2000
1992 2001 Arguments are as for compile_command().
1993 2002
1994 2003 One several things can happen:
1995 2004
1996 2005 1) The input is incorrect; compile_command() raised an
1997 2006 exception (SyntaxError or OverflowError). A syntax traceback
1998 2007 will be printed by calling the showsyntaxerror() method.
1999 2008
2000 2009 2) The input is incomplete, and more input is required;
2001 2010 compile_command() returned None. Nothing happens.
2002 2011
2003 2012 3) The input is complete; compile_command() returned a code
2004 2013 object. The code is executed by calling self.runcode() (which
2005 2014 also handles run-time exceptions, except for SystemExit).
2006 2015
2007 2016 The return value is:
2008 2017
2009 2018 - True in case 2
2010 2019
2011 2020 - False in the other cases, unless an exception is raised, where
2012 2021 None is returned instead. This can be used by external callers to
2013 2022 know whether to continue feeding input or not.
2014 2023
2015 2024 The return value can be used to decide whether to use sys.ps1 or
2016 2025 sys.ps2 to prompt the next line."""
2017 2026
2018 2027 # if the source code has leading blanks, add 'if 1:\n' to it
2019 2028 # this allows execution of indented pasted code. It is tempting
2020 2029 # to add '\n' at the end of source to run commands like ' a=1'
2021 2030 # directly, but this fails for more complicated scenarios
2022 2031 source=source.encode(self.stdin_encoding)
2023 2032 if source[:1] in [' ', '\t']:
2024 2033 source = 'if 1:\n%s' % source
2025 2034
2026 2035 try:
2027 2036 code = self.compile(source,filename,symbol)
2028 2037 except (OverflowError, SyntaxError, ValueError, TypeError):
2029 2038 # Case 1
2030 2039 self.showsyntaxerror(filename)
2031 2040 return None
2032 2041
2033 2042 if code is None:
2034 2043 # Case 2
2035 2044 return True
2036 2045
2037 2046 # Case 3
2038 2047 # We store the code object so that threaded shells and
2039 2048 # custom exception handlers can access all this info if needed.
2040 2049 # The source corresponding to this can be obtained from the
2041 2050 # buffer attribute as '\n'.join(self.buffer).
2042 2051 self.code_to_run = code
2043 2052 # now actually execute the code object
2044 2053 if self.runcode(code) == 0:
2045 2054 return False
2046 2055 else:
2047 2056 return None
2048 2057
2049 2058 def runcode(self,code_obj):
2050 2059 """Execute a code object.
2051 2060
2052 2061 When an exception occurs, self.showtraceback() is called to display a
2053 2062 traceback.
2054 2063
2055 2064 Return value: a flag indicating whether the code to be run completed
2056 2065 successfully:
2057 2066
2058 2067 - 0: successful execution.
2059 2068 - 1: an error occurred.
2060 2069 """
2061 2070
2062 2071 # Set our own excepthook in case the user code tries to call it
2063 2072 # directly, so that the IPython crash handler doesn't get triggered
2064 2073 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2065 2074
2066 2075 # we save the original sys.excepthook in the instance, in case config
2067 2076 # code (such as magics) needs access to it.
2068 2077 self.sys_excepthook = old_excepthook
2069 2078 outflag = 1 # happens in more places, so it's easier as default
2070 2079 try:
2071 2080 try:
2072 2081 self.hooks.pre_runcode_hook()
2073 2082 exec code_obj in self.user_global_ns, self.user_ns
2074 2083 finally:
2075 2084 # Reset our crash handler in place
2076 2085 sys.excepthook = old_excepthook
2077 2086 except SystemExit:
2078 2087 self.resetbuffer()
2079 2088 self.showtraceback()
2080 2089 warn("Type %exit or %quit to exit IPython "
2081 2090 "(%Exit or %Quit do so unconditionally).",level=1)
2082 2091 except self.custom_exceptions:
2083 2092 etype,value,tb = sys.exc_info()
2084 2093 self.CustomTB(etype,value,tb)
2085 2094 except:
2086 2095 self.showtraceback()
2087 2096 else:
2088 2097 outflag = 0
2089 2098 if softspace(sys.stdout, 0):
2090 2099 print
2091 2100 # Flush out code object which has been run (and source)
2092 2101 self.code_to_run = None
2093 2102 return outflag
2094 2103
2095 2104 def push(self, line):
2096 2105 """Push a line to the interpreter.
2097 2106
2098 2107 The line should not have a trailing newline; it may have
2099 2108 internal newlines. The line is appended to a buffer and the
2100 2109 interpreter's runsource() method is called with the
2101 2110 concatenated contents of the buffer as source. If this
2102 2111 indicates that the command was executed or invalid, the buffer
2103 2112 is reset; otherwise, the command is incomplete, and the buffer
2104 2113 is left as it was after the line was appended. The return
2105 2114 value is 1 if more input is required, 0 if the line was dealt
2106 2115 with in some way (this is the same as runsource()).
2107 2116 """
2108 2117
2109 2118 # autoindent management should be done here, and not in the
2110 2119 # interactive loop, since that one is only seen by keyboard input. We
2111 2120 # need this done correctly even for code run via runlines (which uses
2112 2121 # push).
2113 2122
2114 2123 #print 'push line: <%s>' % line # dbg
2115 2124 for subline in line.splitlines():
2116 2125 self.autoindent_update(subline)
2117 2126 self.buffer.append(line)
2118 2127 more = self.runsource('\n'.join(self.buffer), self.filename)
2119 2128 if not more:
2120 2129 self.resetbuffer()
2121 2130 return more
2122 2131
2123 2132 def split_user_input(self, line):
2124 2133 # This is really a hold-over to support ipapi and some extensions
2125 2134 return prefilter.splitUserInput(line)
2126 2135
2127 2136 def resetbuffer(self):
2128 2137 """Reset the input buffer."""
2129 2138 self.buffer[:] = []
2130 2139
2131 2140 def raw_input(self,prompt='',continue_prompt=False):
2132 2141 """Write a prompt and read a line.
2133 2142
2134 2143 The returned line does not include the trailing newline.
2135 2144 When the user enters the EOF key sequence, EOFError is raised.
2136 2145
2137 2146 Optional inputs:
2138 2147
2139 2148 - prompt(''): a string to be printed to prompt the user.
2140 2149
2141 2150 - continue_prompt(False): whether this line is the first one or a
2142 2151 continuation in a sequence of inputs.
2143 2152 """
2144 2153
2145 2154 # Code run by the user may have modified the readline completer state.
2146 2155 # We must ensure that our completer is back in place.
2147 2156 if self.has_readline:
2148 2157 self.set_completer()
2149 2158
2150 2159 try:
2151 2160 line = raw_input_original(prompt).decode(self.stdin_encoding)
2152 2161 except ValueError:
2153 2162 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2154 2163 " or sys.stdout.close()!\nExiting IPython!")
2155 2164 self.ask_exit()
2156 2165 return ""
2157 2166
2158 2167 # Try to be reasonably smart about not re-indenting pasted input more
2159 2168 # than necessary. We do this by trimming out the auto-indent initial
2160 2169 # spaces, if the user's actual input started itself with whitespace.
2161 2170 #debugx('self.buffer[-1]')
2162 2171
2163 2172 if self.autoindent:
2164 2173 if num_ini_spaces(line) > self.indent_current_nsp:
2165 2174 line = line[self.indent_current_nsp:]
2166 2175 self.indent_current_nsp = 0
2167 2176
2168 2177 # store the unfiltered input before the user has any chance to modify
2169 2178 # it.
2170 2179 if line.strip():
2171 2180 if continue_prompt:
2172 2181 self.input_hist_raw[-1] += '%s\n' % line
2173 2182 if self.has_readline: # and some config option is set?
2174 2183 try:
2175 2184 histlen = self.readline.get_current_history_length()
2176 2185 if histlen > 1:
2177 2186 newhist = self.input_hist_raw[-1].rstrip()
2178 2187 self.readline.remove_history_item(histlen-1)
2179 2188 self.readline.replace_history_item(histlen-2,
2180 2189 newhist.encode(self.stdin_encoding))
2181 2190 except AttributeError:
2182 2191 pass # re{move,place}_history_item are new in 2.4.
2183 2192 else:
2184 2193 self.input_hist_raw.append('%s\n' % line)
2185 2194 # only entries starting at first column go to shadow history
2186 2195 if line.lstrip() == line:
2187 2196 self.shadowhist.add(line.strip())
2188 2197 elif not continue_prompt:
2189 2198 self.input_hist_raw.append('\n')
2190 2199 try:
2191 2200 lineout = self.prefilter(line,continue_prompt)
2192 2201 except:
2193 2202 # blanket except, in case a user-defined prefilter crashes, so it
2194 2203 # can't take all of ipython with it.
2195 2204 self.showtraceback()
2196 2205 return ''
2197 2206 else:
2198 2207 return lineout
2199 2208
2200 2209 def _prefilter(self, line, continue_prompt):
2201 2210 """Calls different preprocessors, depending on the form of line."""
2202 2211
2203 2212 # All handlers *must* return a value, even if it's blank ('').
2204 2213
2205 2214 # Lines are NOT logged here. Handlers should process the line as
2206 2215 # needed, update the cache AND log it (so that the input cache array
2207 2216 # stays synced).
2208 2217
2209 2218 #.....................................................................
2210 2219 # Code begins
2211 2220
2212 2221 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2213 2222
2214 2223 # save the line away in case we crash, so the post-mortem handler can
2215 2224 # record it
2216 2225 self._last_input_line = line
2217 2226
2218 2227 #print '***line: <%s>' % line # dbg
2219 2228
2220 2229 if not line:
2221 2230 # Return immediately on purely empty lines, so that if the user
2222 2231 # previously typed some whitespace that started a continuation
2223 2232 # prompt, he can break out of that loop with just an empty line.
2224 2233 # This is how the default python prompt works.
2225 2234
2226 2235 # Only return if the accumulated input buffer was just whitespace!
2227 2236 if ''.join(self.buffer).isspace():
2228 2237 self.buffer[:] = []
2229 2238 return ''
2230 2239
2231 2240 line_info = prefilter.LineInfo(line, continue_prompt)
2232 2241
2233 2242 # the input history needs to track even empty lines
2234 2243 stripped = line.strip()
2235 2244
2236 2245 if not stripped:
2237 2246 if not continue_prompt:
2238 2247 self.outputcache.prompt_count -= 1
2239 2248 return self.handle_normal(line_info)
2240 2249
2241 2250 # print '***cont',continue_prompt # dbg
2242 2251 # special handlers are only allowed for single line statements
2243 2252 if continue_prompt and not self.rc.multi_line_specials:
2244 2253 return self.handle_normal(line_info)
2245 2254
2246 2255
2247 2256 # See whether any pre-existing handler can take care of it
2248 2257 rewritten = self.hooks.input_prefilter(stripped)
2249 2258 if rewritten != stripped: # ok, some prefilter did something
2250 2259 rewritten = line_info.pre + rewritten # add indentation
2251 2260 return self.handle_normal(prefilter.LineInfo(rewritten,
2252 2261 continue_prompt))
2253 2262
2254 2263 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2255 2264
2256 2265 return prefilter.prefilter(line_info, self)
2257 2266
2258 2267
2259 2268 def _prefilter_dumb(self, line, continue_prompt):
2260 2269 """simple prefilter function, for debugging"""
2261 2270 return self.handle_normal(line,continue_prompt)
2262 2271
2263 2272
2264 2273 def multiline_prefilter(self, line, continue_prompt):
2265 2274 """ Run _prefilter for each line of input
2266 2275
2267 2276 Covers cases where there are multiple lines in the user entry,
2268 2277 which is the case when the user goes back to a multiline history
2269 2278 entry and presses enter.
2270 2279
2271 2280 """
2272 2281 out = []
2273 2282 for l in line.rstrip('\n').split('\n'):
2274 2283 out.append(self._prefilter(l, continue_prompt))
2275 2284 return '\n'.join(out)
2276 2285
2277 2286 # Set the default prefilter() function (this can be user-overridden)
2278 2287 prefilter = multiline_prefilter
2279 2288
2280 2289 def handle_normal(self,line_info):
2281 2290 """Handle normal input lines. Use as a template for handlers."""
2282 2291
2283 2292 # With autoindent on, we need some way to exit the input loop, and I
2284 2293 # don't want to force the user to have to backspace all the way to
2285 2294 # clear the line. The rule will be in this case, that either two
2286 2295 # lines of pure whitespace in a row, or a line of pure whitespace but
2287 2296 # of a size different to the indent level, will exit the input loop.
2288 2297 line = line_info.line
2289 2298 continue_prompt = line_info.continue_prompt
2290 2299
2291 2300 if (continue_prompt and self.autoindent and line.isspace() and
2292 2301 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2293 2302 (self.buffer[-1]).isspace() )):
2294 2303 line = ''
2295 2304
2296 2305 self.log(line,line,continue_prompt)
2297 2306 return line
2298 2307
2299 2308 def handle_alias(self,line_info):
2300 2309 """Handle alias input lines. """
2301 2310 tgt = self.alias_table[line_info.iFun]
2302 2311 # print "=>",tgt #dbg
2303 2312 if callable(tgt):
2304 2313 if '$' in line_info.line:
2305 2314 call_meth = '(_ip, _ip.itpl(%s))'
2306 2315 else:
2307 2316 call_meth = '(_ip,%s)'
2308 2317 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2309 2318 line_info.iFun,
2310 2319 make_quoted_expr(line_info.line))
2311 2320 else:
2312 2321 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2313 2322
2314 2323 # pre is needed, because it carries the leading whitespace. Otherwise
2315 2324 # aliases won't work in indented sections.
2316 2325 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2317 2326 make_quoted_expr( transformed ))
2318 2327
2319 2328 self.log(line_info.line,line_out,line_info.continue_prompt)
2320 2329 #print 'line out:',line_out # dbg
2321 2330 return line_out
2322 2331
2323 2332 def handle_shell_escape(self, line_info):
2324 2333 """Execute the line in a shell, empty return value"""
2325 2334 #print 'line in :', `line` # dbg
2326 2335 line = line_info.line
2327 2336 if line.lstrip().startswith('!!'):
2328 2337 # rewrite LineInfo's line, iFun and theRest to properly hold the
2329 2338 # call to %sx and the actual command to be executed, so
2330 2339 # handle_magic can work correctly. Note that this works even if
2331 2340 # the line is indented, so it handles multi_line_specials
2332 2341 # properly.
2333 2342 new_rest = line.lstrip()[2:]
2334 2343 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2335 2344 line_info.iFun = 'sx'
2336 2345 line_info.theRest = new_rest
2337 2346 return self.handle_magic(line_info)
2338 2347 else:
2339 2348 cmd = line.lstrip().lstrip('!')
2340 2349 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2341 2350 make_quoted_expr(cmd))
2342 2351 # update cache/log and return
2343 2352 self.log(line,line_out,line_info.continue_prompt)
2344 2353 return line_out
2345 2354
2346 2355 def handle_magic(self, line_info):
2347 2356 """Execute magic functions."""
2348 2357 iFun = line_info.iFun
2349 2358 theRest = line_info.theRest
2350 2359 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2351 2360 make_quoted_expr(iFun + " " + theRest))
2352 2361 self.log(line_info.line,cmd,line_info.continue_prompt)
2353 2362 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2354 2363 return cmd
2355 2364
2356 2365 def handle_auto(self, line_info):
2357 2366 """Hande lines which can be auto-executed, quoting if requested."""
2358 2367
2359 2368 line = line_info.line
2360 2369 iFun = line_info.iFun
2361 2370 theRest = line_info.theRest
2362 2371 pre = line_info.pre
2363 2372 continue_prompt = line_info.continue_prompt
2364 2373 obj = line_info.ofind(self)['obj']
2365 2374
2366 2375 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2367 2376
2368 2377 # This should only be active for single-line input!
2369 2378 if continue_prompt:
2370 2379 self.log(line,line,continue_prompt)
2371 2380 return line
2372 2381
2373 2382 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2374 2383 auto_rewrite = True
2375 2384
2376 2385 if pre == self.ESC_QUOTE:
2377 2386 # Auto-quote splitting on whitespace
2378 2387 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2379 2388 elif pre == self.ESC_QUOTE2:
2380 2389 # Auto-quote whole string
2381 2390 newcmd = '%s("%s")' % (iFun,theRest)
2382 2391 elif pre == self.ESC_PAREN:
2383 2392 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2384 2393 else:
2385 2394 # Auto-paren.
2386 2395 # We only apply it to argument-less calls if the autocall
2387 2396 # parameter is set to 2. We only need to check that autocall is <
2388 2397 # 2, since this function isn't called unless it's at least 1.
2389 2398 if not theRest and (self.rc.autocall < 2) and not force_auto:
2390 2399 newcmd = '%s %s' % (iFun,theRest)
2391 2400 auto_rewrite = False
2392 2401 else:
2393 2402 if not force_auto and theRest.startswith('['):
2394 2403 if hasattr(obj,'__getitem__'):
2395 2404 # Don't autocall in this case: item access for an object
2396 2405 # which is BOTH callable and implements __getitem__.
2397 2406 newcmd = '%s %s' % (iFun,theRest)
2398 2407 auto_rewrite = False
2399 2408 else:
2400 2409 # if the object doesn't support [] access, go ahead and
2401 2410 # autocall
2402 2411 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2403 2412 elif theRest.endswith(';'):
2404 2413 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2405 2414 else:
2406 2415 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2407 2416
2408 2417 if auto_rewrite:
2409 2418 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2410 2419
2411 2420 try:
2412 2421 # plain ascii works better w/ pyreadline, on some machines, so
2413 2422 # we use it and only print uncolored rewrite if we have unicode
2414 2423 rw = str(rw)
2415 2424 print >>Term.cout, rw
2416 2425 except UnicodeEncodeError:
2417 2426 print "-------------->" + newcmd
2418 2427
2419 2428 # log what is now valid Python, not the actual user input (without the
2420 2429 # final newline)
2421 2430 self.log(line,newcmd,continue_prompt)
2422 2431 return newcmd
2423 2432
2424 2433 def handle_help(self, line_info):
2425 2434 """Try to get some help for the object.
2426 2435
2427 2436 obj? or ?obj -> basic information.
2428 2437 obj?? or ??obj -> more details.
2429 2438 """
2430 2439
2431 2440 line = line_info.line
2432 2441 # We need to make sure that we don't process lines which would be
2433 2442 # otherwise valid python, such as "x=1 # what?"
2434 2443 try:
2435 2444 codeop.compile_command(line)
2436 2445 except SyntaxError:
2437 2446 # We should only handle as help stuff which is NOT valid syntax
2438 2447 if line[0]==self.ESC_HELP:
2439 2448 line = line[1:]
2440 2449 elif line[-1]==self.ESC_HELP:
2441 2450 line = line[:-1]
2442 2451 self.log(line,'#?'+line,line_info.continue_prompt)
2443 2452 if line:
2444 2453 #print 'line:<%r>' % line # dbg
2445 2454 self.magic_pinfo(line)
2446 2455 else:
2447 2456 page(self.usage,screen_lines=self.rc.screen_length)
2448 2457 return '' # Empty string is needed here!
2449 2458 except:
2450 2459 # Pass any other exceptions through to the normal handler
2451 2460 return self.handle_normal(line_info)
2452 2461 else:
2453 2462 # If the code compiles ok, we should handle it normally
2454 2463 return self.handle_normal(line_info)
2455 2464
2456 2465 def getapi(self):
2457 2466 """ Get an IPApi object for this shell instance
2458 2467
2459 2468 Getting an IPApi object is always preferable to accessing the shell
2460 2469 directly, but this holds true especially for extensions.
2461 2470
2462 2471 It should always be possible to implement an extension with IPApi
2463 2472 alone. If not, contact maintainer to request an addition.
2464 2473
2465 2474 """
2466 2475 return self.api
2467 2476
2468 2477 def handle_emacs(self, line_info):
2469 2478 """Handle input lines marked by python-mode."""
2470 2479
2471 2480 # Currently, nothing is done. Later more functionality can be added
2472 2481 # here if needed.
2473 2482
2474 2483 # The input cache shouldn't be updated
2475 2484 return line_info.line
2476 2485
2477 2486
2478 2487 def mktempfile(self,data=None):
2479 2488 """Make a new tempfile and return its filename.
2480 2489
2481 2490 This makes a call to tempfile.mktemp, but it registers the created
2482 2491 filename internally so ipython cleans it up at exit time.
2483 2492
2484 2493 Optional inputs:
2485 2494
2486 2495 - data(None): if data is given, it gets written out to the temp file
2487 2496 immediately, and the file is closed again."""
2488 2497
2489 2498 filename = tempfile.mktemp('.py','ipython_edit_')
2490 2499 self.tempfiles.append(filename)
2491 2500
2492 2501 if data:
2493 2502 tmp_file = open(filename,'w')
2494 2503 tmp_file.write(data)
2495 2504 tmp_file.close()
2496 2505 return filename
2497 2506
2498 2507 def write(self,data):
2499 2508 """Write a string to the default output"""
2500 2509 Term.cout.write(data)
2501 2510
2502 2511 def write_err(self,data):
2503 2512 """Write a string to the default error output"""
2504 2513 Term.cerr.write(data)
2505 2514
2506 2515 def ask_exit(self):
2507 2516 """ Call for exiting. Can be overiden and used as a callback. """
2508 2517 self.exit_now = True
2509 2518
2510 2519 def exit(self):
2511 2520 """Handle interactive exit.
2512 2521
2513 2522 This method calls the ask_exit callback."""
2514 2523
2515 2524 if self.rc.confirm_exit:
2516 2525 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2517 2526 self.ask_exit()
2518 2527 else:
2519 2528 self.ask_exit()
2520 2529
2521 2530 def safe_execfile(self,fname,*where,**kw):
2522 2531 """A safe version of the builtin execfile().
2523 2532
2524 2533 This version will never throw an exception, and knows how to handle
2525 2534 ipython logs as well.
2526 2535
2527 2536 :Parameters:
2528 2537 fname : string
2529 2538 Name of the file to be executed.
2530 2539
2531 2540 where : tuple
2532 2541 One or two namespaces, passed to execfile() as (globals,locals).
2533 2542 If only one is given, it is passed as both.
2534 2543
2535 2544 :Keywords:
2536 2545 islog : boolean (False)
2537 2546
2538 2547 quiet : boolean (True)
2539 2548
2540 2549 exit_ignore : boolean (False)
2541 2550 """
2542 2551
2543 2552 def syspath_cleanup():
2544 2553 """Internal cleanup routine for sys.path."""
2545 2554 if add_dname:
2546 2555 try:
2547 2556 sys.path.remove(dname)
2548 2557 except ValueError:
2549 2558 # For some reason the user has already removed it, ignore.
2550 2559 pass
2551 2560
2552 2561 fname = os.path.expanduser(fname)
2553 2562
2554 2563 # Find things also in current directory. This is needed to mimic the
2555 2564 # behavior of running a script from the system command line, where
2556 2565 # Python inserts the script's directory into sys.path
2557 2566 dname = os.path.dirname(os.path.abspath(fname))
2558 2567 add_dname = False
2559 2568 if dname not in sys.path:
2560 2569 sys.path.insert(0,dname)
2561 2570 add_dname = True
2562 2571
2563 2572 try:
2564 2573 xfile = open(fname)
2565 2574 except:
2566 2575 print >> Term.cerr, \
2567 2576 'Could not open file <%s> for safe execution.' % fname
2568 2577 syspath_cleanup()
2569 2578 return None
2570 2579
2571 2580 kw.setdefault('islog',0)
2572 2581 kw.setdefault('quiet',1)
2573 2582 kw.setdefault('exit_ignore',0)
2574 2583
2575 2584 first = xfile.readline()
2576 2585 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2577 2586 xfile.close()
2578 2587 # line by line execution
2579 2588 if first.startswith(loghead) or kw['islog']:
2580 2589 print 'Loading log file <%s> one line at a time...' % fname
2581 2590 if kw['quiet']:
2582 2591 stdout_save = sys.stdout
2583 2592 sys.stdout = StringIO.StringIO()
2584 2593 try:
2585 2594 globs,locs = where[0:2]
2586 2595 except:
2587 2596 try:
2588 2597 globs = locs = where[0]
2589 2598 except:
2590 2599 globs = locs = globals()
2591 2600 badblocks = []
2592 2601
2593 2602 # we also need to identify indented blocks of code when replaying
2594 2603 # logs and put them together before passing them to an exec
2595 2604 # statement. This takes a bit of regexp and look-ahead work in the
2596 2605 # file. It's easiest if we swallow the whole thing in memory
2597 2606 # first, and manually walk through the lines list moving the
2598 2607 # counter ourselves.
2599 2608 indent_re = re.compile('\s+\S')
2600 2609 xfile = open(fname)
2601 2610 filelines = xfile.readlines()
2602 2611 xfile.close()
2603 2612 nlines = len(filelines)
2604 2613 lnum = 0
2605 2614 while lnum < nlines:
2606 2615 line = filelines[lnum]
2607 2616 lnum += 1
2608 2617 # don't re-insert logger status info into cache
2609 2618 if line.startswith('#log#'):
2610 2619 continue
2611 2620 else:
2612 2621 # build a block of code (maybe a single line) for execution
2613 2622 block = line
2614 2623 try:
2615 2624 next = filelines[lnum] # lnum has already incremented
2616 2625 except:
2617 2626 next = None
2618 2627 while next and indent_re.match(next):
2619 2628 block += next
2620 2629 lnum += 1
2621 2630 try:
2622 2631 next = filelines[lnum]
2623 2632 except:
2624 2633 next = None
2625 2634 # now execute the block of one or more lines
2626 2635 try:
2627 2636 exec block in globs,locs
2628 2637 except SystemExit:
2629 2638 pass
2630 2639 except:
2631 2640 badblocks.append(block.rstrip())
2632 2641 if kw['quiet']: # restore stdout
2633 2642 sys.stdout.close()
2634 2643 sys.stdout = stdout_save
2635 2644 print 'Finished replaying log file <%s>' % fname
2636 2645 if badblocks:
2637 2646 print >> sys.stderr, ('\nThe following lines/blocks in file '
2638 2647 '<%s> reported errors:' % fname)
2639 2648
2640 2649 for badline in badblocks:
2641 2650 print >> sys.stderr, badline
2642 2651 else: # regular file execution
2643 2652 try:
2644 2653 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2645 2654 # Work around a bug in Python for Windows. The bug was
2646 2655 # fixed in in Python 2.5 r54159 and 54158, but that's still
2647 2656 # SVN Python as of March/07. For details, see:
2648 2657 # http://projects.scipy.org/ipython/ipython/ticket/123
2649 2658 try:
2650 2659 globs,locs = where[0:2]
2651 2660 except:
2652 2661 try:
2653 2662 globs = locs = where[0]
2654 2663 except:
2655 2664 globs = locs = globals()
2656 2665 exec file(fname) in globs,locs
2657 2666 else:
2658 2667 execfile(fname,*where)
2659 2668 except SyntaxError:
2660 2669 self.showsyntaxerror()
2661 2670 warn('Failure executing file: <%s>' % fname)
2662 2671 except SystemExit,status:
2663 2672 # Code that correctly sets the exit status flag to success (0)
2664 2673 # shouldn't be bothered with a traceback. Note that a plain
2665 2674 # sys.exit() does NOT set the message to 0 (it's empty) so that
2666 2675 # will still get a traceback. Note that the structure of the
2667 2676 # SystemExit exception changed between Python 2.4 and 2.5, so
2668 2677 # the checks must be done in a version-dependent way.
2669 2678 show = False
2670 2679
2671 2680 if sys.version_info[:2] > (2,5):
2672 2681 if status.message!=0 and not kw['exit_ignore']:
2673 2682 show = True
2674 2683 else:
2675 2684 if status.code and not kw['exit_ignore']:
2676 2685 show = True
2677 2686 if show:
2678 2687 self.showtraceback()
2679 2688 warn('Failure executing file: <%s>' % fname)
2680 2689 except:
2681 2690 self.showtraceback()
2682 2691 warn('Failure executing file: <%s>' % fname)
2683 2692
2684 2693 syspath_cleanup()
2685 2694
2686 2695 #************************* end of file <iplib.py> *****************************
@@ -1,123 +1,124 b''
1 1 # encoding: utf-8
2 2
3 3 """Default kernel configuration."""
4 4
5 5 __docformat__ = "restructuredtext en"
6 6
7 7 #-------------------------------------------------------------------------------
8 8 # Copyright (C) 2008 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 from os.path import join as pjoin
19 19
20 20 from IPython.external.configobj import ConfigObj
21 21 from IPython.config.api import ConfigObjManager
22 22 from IPython.genutils import get_ipython_dir, get_security_dir
23 23
24 24 default_kernel_config = ConfigObj()
25 25
26 26 security_dir = get_security_dir()
27 27
28 28 #-------------------------------------------------------------------------------
29 29 # Engine Configuration
30 30 #-------------------------------------------------------------------------------
31 31
32 32 engine_config = dict(
33 33 logfile = '', # Empty means log to stdout
34 34 furl_file = pjoin(security_dir, 'ipcontroller-engine.furl')
35 35 )
36 36
37 37 #-------------------------------------------------------------------------------
38 38 # MPI Configuration
39 39 #-------------------------------------------------------------------------------
40 40
41 41 mpi_config = dict(
42 42 mpi4py = """from mpi4py import MPI as mpi
43 43 mpi.size = mpi.COMM_WORLD.Get_size()
44 44 mpi.rank = mpi.COMM_WORLD.Get_rank()
45 45 """,
46 46 pytrilinos = """from PyTrilinos import Epetra
47 47 class SimpleStruct:
48 48 pass
49 49 mpi = SimpleStruct()
50 50 mpi.rank = 0
51 51 mpi.size = 0
52 52 """,
53 53 default = ''
54 54 )
55 55
56 56 #-------------------------------------------------------------------------------
57 57 # Controller Configuration
58 58 #-------------------------------------------------------------------------------
59 59
60 60 controller_config = dict(
61 61
62 62 logfile = '', # Empty means log to stdout
63 63 import_statement = '',
64 reuse_furls = False, # If False, old furl files are deleted
64 65
65 66 engine_tub = dict(
66 67 ip = '', # Empty string means all interfaces
67 68 port = 0, # 0 means pick a port for me
68 69 location = '', # Empty string means try to set automatically
69 70 secure = True,
70 71 cert_file = pjoin(security_dir, 'ipcontroller-engine.pem'),
71 72 ),
72 73 engine_fc_interface = 'IPython.kernel.enginefc.IFCControllerBase',
73 74 engine_furl_file = pjoin(security_dir, 'ipcontroller-engine.furl'),
74 75
75 76 controller_interfaces = dict(
76 77 # multiengine = dict(
77 78 # controller_interface = 'IPython.kernel.multiengine.IMultiEngine',
78 79 # fc_interface = 'IPython.kernel.multienginefc.IFCMultiEngine',
79 80 # furl_file = 'ipcontroller-mec.furl'
80 81 # ),
81 82 task = dict(
82 83 controller_interface = 'IPython.kernel.task.ITaskController',
83 84 fc_interface = 'IPython.kernel.taskfc.IFCTaskController',
84 85 furl_file = pjoin(security_dir, 'ipcontroller-tc.furl')
85 86 ),
86 87 multiengine = dict(
87 88 controller_interface = 'IPython.kernel.multiengine.IMultiEngine',
88 89 fc_interface = 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine',
89 90 furl_file = pjoin(security_dir, 'ipcontroller-mec.furl')
90 91 )
91 92 ),
92 93
93 94 client_tub = dict(
94 95 ip = '', # Empty string means all interfaces
95 96 port = 0, # 0 means pick a port for me
96 97 location = '', # Empty string means try to set automatically
97 98 secure = True,
98 99 cert_file = pjoin(security_dir, 'ipcontroller-client.pem')
99 100 )
100 101 )
101 102
102 103 #-------------------------------------------------------------------------------
103 104 # Client Configuration
104 105 #-------------------------------------------------------------------------------
105 106
106 107 client_config = dict(
107 108 client_interfaces = dict(
108 109 task = dict(
109 110 furl_file = pjoin(security_dir, 'ipcontroller-tc.furl')
110 111 ),
111 112 multiengine = dict(
112 113 furl_file = pjoin(security_dir, 'ipcontroller-mec.furl')
113 114 )
114 115 )
115 116 )
116 117
117 118 default_kernel_config['engine'] = engine_config
118 119 default_kernel_config['mpi'] = mpi_config
119 120 default_kernel_config['controller'] = controller_config
120 121 default_kernel_config['client'] = client_config
121 122
122 123
123 124 config_manager = ConfigObjManager(default_kernel_config, 'IPython.kernel.ini') No newline at end of file
@@ -1,68 +1,70 b''
1 1 # encoding: utf-8
2 2 """
3 3 Test the output capture at the OS level, using file descriptors.
4 4 """
5 5
6 6 __docformat__ = "restructuredtext en"
7 7
8 8 #-------------------------------------------------------------------------------
9 9 # Copyright (C) 2008 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is
12 12 # in the file COPYING, distributed as part of this software.
13 13 #-------------------------------------------------------------------------------
14 14
15 15
16 # Stdlib imports
16 17 import os
17 18 from cStringIO import StringIO
18 19
19 # FIXME:
20 import nose
21 import sys
22 if sys.platform == 'win32':
23 raise nose.SkipTest("These tests are not reliable under windows")
20 # Our own imports
21 from IPython.testing import decorators as dec
24 22
23 #-----------------------------------------------------------------------------
24 # Test functions
25
26 @dec.skip_win32
25 27 def test_redirector():
26 28 """ Checks that the redirector can be used to do synchronous capture.
27 29 """
28 30 from IPython.kernel.core.fd_redirector import FDRedirector
29 31 r = FDRedirector()
30 32 out = StringIO()
31 33 try:
32 34 r.start()
33 35 for i in range(10):
34 36 os.system('echo %ic' % i)
35 37 print >>out, r.getvalue(),
36 38 print >>out, i
37 39 except:
38 40 r.stop()
39 41 raise
40 42 r.stop()
41 43 result1 = out.getvalue()
42 44 result2 = "".join("%ic\n%i\n" %(i, i) for i in range(10))
43 45 assert result1 == result2
44 46
47
48 @dec.skip_win32
45 49 def test_redirector_output_trap():
46 50 """ This test check not only that the redirector_output_trap does
47 51 trap the output, but also that it does it in a gready way, that
48 52 is by calling the callback ASAP.
49 53 """
50 54 from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap
51 55 out = StringIO()
52 56 trap = RedirectorOutputTrap(out.write, out.write)
53 57 try:
54 58 trap.set()
55 59 for i in range(10):
56 60 os.system('echo %ic' % i)
57 61 print "%ip" % i
58 62 print >>out, i
59 63 except:
60 64 trap.unset()
61 65 raise
62 66 trap.unset()
63 67 result1 = out.getvalue()
64 68 result2 = "".join("%ic\n%ip\n%i\n" %(i, i, i) for i in range(10))
65 69 assert result1 == result2
66
67 70
68
@@ -1,87 +1,92 b''
1 1 # encoding: utf-8
2 2
3 3 """A class that manages the engines connection to the controller."""
4 4
5 5 __docformat__ = "restructuredtext en"
6 6
7 7 #-------------------------------------------------------------------------------
8 8 # Copyright (C) 2008 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 os
19 19 import cPickle as pickle
20 20
21 from twisted.python import log
21 from twisted.python import log, failure
22 from twisted.internet import defer
22 23
23 24 from IPython.kernel.fcutil import find_furl
24 25 from IPython.kernel.enginefc import IFCEngine
25 26
26 27 #-------------------------------------------------------------------------------
27 28 # The ClientConnector class
28 29 #-------------------------------------------------------------------------------
29 30
30 31 class EngineConnector(object):
31 32 """Manage an engines connection to a controller.
32 33
33 34 This class takes a foolscap `Tub` and provides a `connect_to_controller`
34 35 method that will use the `Tub` to connect to a controller and register
35 36 the engine with the controller.
36 37 """
37 38
38 39 def __init__(self, tub):
39 40 self.tub = tub
40 41
41 42 def connect_to_controller(self, engine_service, furl_or_file):
42 43 """
43 44 Make a connection to a controller specified by a furl.
44 45
45 46 This method takes an `IEngineBase` instance and a foolcap URL and uses
46 47 the `tub` attribute to make a connection to the controller. The
47 48 foolscap URL contains all the information needed to connect to the
48 49 controller, including the ip and port as well as any encryption and
49 50 authentication information needed for the connection.
50 51
51 52 After getting a reference to the controller, this method calls the
52 53 `register_engine` method of the controller to actually register the
53 54 engine.
54 55
55 56 :Parameters:
56 57 engine_service : IEngineBase
57 58 An instance of an `IEngineBase` implementer
58 59 furl_or_file : str
59 60 A furl or a filename containing a furl
60 61 """
61 62 if not self.tub.running:
62 63 self.tub.startService()
63 64 self.engine_service = engine_service
64 65 self.engine_reference = IFCEngine(self.engine_service)
65 self.furl = find_furl(furl_or_file)
66 try:
67 self.furl = find_furl(furl_or_file)
68 except ValueError:
69 return defer.fail(failure.Failure())
70 # return defer.fail(failure.Failure(ValueError('not a valid furl or furl file: %r' % furl_or_file)))
66 71 d = self.tub.getReference(self.furl)
67 72 d.addCallbacks(self._register, self._log_failure)
68 73 return d
69 74
70 75 def _log_failure(self, reason):
71 log.err('engine registration failed:')
76 log.err('EngineConnector: engine registration failed:')
72 77 log.err(reason)
73 78 return reason
74 79
75 80 def _register(self, rr):
76 81 self.remote_ref = rr
77 82 # Now register myself with the controller
78 83 desired_id = self.engine_service.id
79 84 d = self.remote_ref.callRemote('register_engine', self.engine_reference,
80 85 desired_id, os.getpid(), pickle.dumps(self.engine_service.properties,2))
81 86 return d.addCallbacks(self._reference_sent, self._log_failure)
82 87
83 88 def _reference_sent(self, registration_dict):
84 89 self.engine_service.id = registration_dict['id']
85 90 log.msg("engine registration succeeded, got id: %r" % self.engine_service.id)
86 91 return self.engine_service.id
87 92
This diff has been collapsed as it changes many lines, (749 lines changed) Show them Hide them
@@ -1,347 +1,486 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3
4 """Start an IPython cluster conveniently, either locally or remotely.
4 """Start an IPython cluster = (controller + engines)."""
5 5
6 Basic usage
7 -----------
8
9 For local operation, the simplest mode of usage is:
10
11 %prog -n N
12
13 where N is the number of engines you want started.
14
15 For remote operation, you must call it with a cluster description file:
16
17 %prog -f clusterfile.py
18
19 The cluster file is a normal Python script which gets run via execfile(). You
20 can have arbitrary logic in it, but all that matters is that at the end of the
21 execution, it declares the variables 'controller', 'engines', and optionally
22 'sshx'. See the accompanying examples for details on what these variables must
23 contain.
24
25
26 Notes
27 -----
28
29 WARNING: this code is still UNFINISHED and EXPERIMENTAL! It is incomplete,
30 some listed options are not really implemented, and all of its interfaces are
31 subject to change.
32
33 When operating over SSH for a remote cluster, this program relies on the
34 existence of a particular script called 'sshx'. This script must live in the
35 target systems where you'll be running your controller and engines, and is
36 needed to configure your PATH and PYTHONPATH variables for further execution of
37 python code at the other end of an SSH connection. The script can be as simple
38 as:
39
40 #!/bin/sh
41 . $HOME/.bashrc
42 "$@"
43
44 which is the default one provided by IPython. You can modify this or provide
45 your own. Since it's quite likely that for different clusters you may need
46 this script to configure things differently or that it may live in different
47 locations, its full path can be set in the same file where you define the
48 cluster setup. IPython's order of evaluation for this variable is the
49 following:
50
51 a) Internal default: 'sshx'. This only works if it is in the default system
52 path which SSH sets up in non-interactive mode.
53
54 b) Environment variable: if $IPYTHON_SSHX is defined, this overrides the
55 internal default.
56
57 c) Variable 'sshx' in the cluster configuration file: finally, this will
58 override the previous two values.
59
60 This code is Unix-only, with precious little hope of any of this ever working
61 under Windows, since we need SSH from the ground up, we background processes,
62 etc. Ports of this functionality to Windows are welcome.
63
64
65 Call summary
66 ------------
67
68 %prog [options]
69 """
70
71 __docformat__ = "restructuredtext en"
72
73 #-------------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
74 7 # Copyright (C) 2008 The IPython Development Team
75 8 #
76 9 # Distributed under the terms of the BSD License. The full license is in
77 10 # the file COPYING, distributed as part of this software.
78 #-------------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
79 12
80 #-------------------------------------------------------------------------------
81 # Stdlib imports
82 #-------------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
83 16
84 17 import os
85 import signal
18 import re
86 19 import sys
87 import time
20 import signal
21 pjoin = os.path.join
88 22
89 from optparse import OptionParser
90 from subprocess import Popen,call
23 from twisted.internet import reactor, defer
24 from twisted.internet.protocol import ProcessProtocol
25 from twisted.python import failure, log
26 from twisted.internet.error import ProcessDone, ProcessTerminated
27 from twisted.internet.utils import getProcessOutput
91 28
92 #---------------------------------------------------------------------------
93 # IPython imports
94 #---------------------------------------------------------------------------
95 from IPython.tools import utils
96 from IPython.genutils import get_ipython_dir
29 from IPython.external import argparse
30 from IPython.external import Itpl
31 from IPython.kernel.twistedutil import gatherBoth
32 from IPython.kernel.util import printer
33 from IPython.genutils import get_ipython_dir, num_cpus
97 34
98 #---------------------------------------------------------------------------
99 # Normal code begins
100 #---------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # General process handling code
37 #-----------------------------------------------------------------------------
101 38
102 def parse_args():
103 """Parse command line and return opts,args."""
39 def find_exe(cmd):
40 try:
41 import win32api
42 except ImportError:
43 raise ImportError('you need to have pywin32 installed for this to work')
44 else:
45 (path, offest) = win32api.SearchPath(os.environ['PATH'],cmd)
46 return path
104 47
105 parser = OptionParser(usage=__doc__)
106 newopt = parser.add_option # shorthand
48 class ProcessStateError(Exception):
49 pass
107 50
108 newopt("--controller-port", type="int", dest="controllerport",
109 help="the TCP port the controller is listening on")
51 class UnknownStatus(Exception):
52 pass
110 53
111 newopt("--controller-ip", type="string", dest="controllerip",
112 help="the TCP ip address of the controller")
54 class LauncherProcessProtocol(ProcessProtocol):
55 """
56 A ProcessProtocol to go with the ProcessLauncher.
57 """
58 def __init__(self, process_launcher):
59 self.process_launcher = process_launcher
60
61 def connectionMade(self):
62 self.process_launcher.fire_start_deferred(self.transport.pid)
63
64 def processEnded(self, status):
65 value = status.value
66 if isinstance(value, ProcessDone):
67 self.process_launcher.fire_stop_deferred(0)
68 elif isinstance(value, ProcessTerminated):
69 self.process_launcher.fire_stop_deferred(
70 {'exit_code':value.exitCode,
71 'signal':value.signal,
72 'status':value.status
73 }
74 )
75 else:
76 raise UnknownStatus("unknown exit status, this is probably a bug in Twisted")
113 77
114 newopt("-n", "--num", type="int", dest="n",default=2,
115 help="the number of engines to start")
78 def outReceived(self, data):
79 log.msg(data)
116 80
117 newopt("--engine-port", type="int", dest="engineport",
118 help="the TCP port the controller will listen on for engine "
119 "connections")
120
121 newopt("--engine-ip", type="string", dest="engineip",
122 help="the TCP ip address the controller will listen on "
123 "for engine connections")
81 def errReceived(self, data):
82 log.err(data)
124 83
125 newopt("--mpi", type="string", dest="mpi",
126 help="use mpi with package: for instance --mpi=mpi4py")
84 class ProcessLauncher(object):
85 """
86 Start and stop an external process in an asynchronous manner.
87
88 Currently this uses deferreds to notify other parties of process state
89 changes. This is an awkward design and should be moved to using
90 a formal NotificationCenter.
91 """
92 def __init__(self, cmd_and_args):
93 self.cmd = cmd_and_args[0]
94 self.args = cmd_and_args
95 self._reset()
96
97 def _reset(self):
98 self.process_protocol = None
99 self.pid = None
100 self.start_deferred = None
101 self.stop_deferreds = []
102 self.state = 'before' # before, running, or after
103
104 @property
105 def running(self):
106 if self.state == 'running':
107 return True
108 else:
109 return False
110
111 def fire_start_deferred(self, pid):
112 self.pid = pid
113 self.state = 'running'
114 log.msg('Process %r has started with pid=%i' % (self.args, pid))
115 self.start_deferred.callback(pid)
116
117 def start(self):
118 if self.state == 'before':
119 self.process_protocol = LauncherProcessProtocol(self)
120 self.start_deferred = defer.Deferred()
121 self.process_transport = reactor.spawnProcess(
122 self.process_protocol,
123 self.cmd,
124 self.args,
125 env=os.environ
126 )
127 return self.start_deferred
128 else:
129 s = 'the process has already been started and has state: %r' % \
130 self.state
131 return defer.fail(ProcessStateError(s))
132
133 def get_stop_deferred(self):
134 if self.state == 'running' or self.state == 'before':
135 d = defer.Deferred()
136 self.stop_deferreds.append(d)
137 return d
138 else:
139 s = 'this process is already complete'
140 return defer.fail(ProcessStateError(s))
141
142 def fire_stop_deferred(self, exit_code):
143 log.msg('Process %r has stopped with %r' % (self.args, exit_code))
144 self.state = 'after'
145 for d in self.stop_deferreds:
146 d.callback(exit_code)
147
148 def signal(self, sig):
149 """
150 Send a signal to the process.
151
152 The argument sig can be ('KILL','INT', etc.) or any signal number.
153 """
154 if self.state == 'running':
155 self.process_transport.signalProcess(sig)
127 156
128 newopt("-l", "--logfile", type="string", dest="logfile",
129 help="log file name")
157 # def __del__(self):
158 # self.signal('KILL')
159
160 def interrupt_then_kill(self, delay=1.0):
161 self.signal('INT')
162 reactor.callLater(delay, self.signal, 'KILL')
163
130 164
131 newopt('-f','--cluster-file',dest='clusterfile',
132 help='file describing a remote cluster')
165 #-----------------------------------------------------------------------------
166 # Code for launching controller and engines
167 #-----------------------------------------------------------------------------
133 168
134 return parser.parse_args()
135 169
136 def numAlive(controller,engines):
137 """Return the number of processes still alive."""
138 retcodes = [controller.poll()] + \
139 [e.poll() for e in engines]
140 return retcodes.count(None)
170 class ControllerLauncher(ProcessLauncher):
171
172 def __init__(self, extra_args=None):
173 if sys.platform == 'win32':
174 args = [find_exe('ipcontroller.bat')]
175 else:
176 args = ['ipcontroller']
177 self.extra_args = extra_args
178 if extra_args is not None:
179 args.extend(extra_args)
180
181 ProcessLauncher.__init__(self, args)
141 182
142 stop = lambda pid: os.kill(pid,signal.SIGINT)
143 kill = lambda pid: os.kill(pid,signal.SIGTERM)
144 183
145 def cleanup(clean,controller,engines):
146 """Stop the controller and engines with the given cleanup method."""
184 class EngineLauncher(ProcessLauncher):
147 185
148 for e in engines:
149 if e.poll() is None:
150 print 'Stopping engine, pid',e.pid
151 clean(e.pid)
152 if controller.poll() is None:
153 print 'Stopping controller, pid',controller.pid
154 clean(controller.pid)
155
156
157 def ensureDir(path):
158 """Ensure a directory exists or raise an exception."""
159 if not os.path.isdir(path):
160 os.makedirs(path)
161
162
163 def startMsg(control_host,control_port=10105):
164 """Print a startup message"""
165 print
166 print 'Your cluster is up and running.'
167 print
168 print 'For interactive use, you can make a MultiEngineClient with:'
169 print
170 print 'from IPython.kernel import client'
171 print "mec = client.MultiEngineClient()"
172 print
173 print 'You can then cleanly stop the cluster from IPython using:'
174 print
175 print 'mec.kill(controller=True)'
176 print
186 def __init__(self, extra_args=None):
187 if sys.platform == 'win32':
188 args = [find_exe('ipengine.bat')]
189 else:
190 args = ['ipengine']
191 self.extra_args = extra_args
192 if extra_args is not None:
193 args.extend(extra_args)
194
195 ProcessLauncher.__init__(self, args)
177 196
197
198 class LocalEngineSet(object):
178 199
179 def clusterLocal(opt,arg):
180 """Start a cluster on the local machine."""
200 def __init__(self, extra_args=None):
201 self.extra_args = extra_args
202 self.launchers = []
181 203
182 # Store all logs inside the ipython directory
183 ipdir = get_ipython_dir()
184 pjoin = os.path.join
185
186 logfile = opt.logfile
187 if logfile is None:
188 logdir_base = pjoin(ipdir,'log')
189 ensureDir(logdir_base)
190 logfile = pjoin(logdir_base,'ipcluster-')
191
192 print 'Starting controller:',
193 controller = Popen(['ipcontroller','--logfile',logfile,'-x','-y'])
194 print 'Controller PID:',controller.pid
195
196 print 'Starting engines: ',
197 time.sleep(5)
198
199 englogfile = '%s%s-' % (logfile,controller.pid)
200 mpi = opt.mpi
201 if mpi: # start with mpi - killing the engines with sigterm will not work if you do this
202 engines = [Popen(['mpirun', '-np', str(opt.n), 'ipengine', '--mpi',
203 mpi, '--logfile',englogfile])]
204 # engines = [Popen(['mpirun', '-np', str(opt.n), 'ipengine', '--mpi', mpi])]
205 else: # do what we would normally do
206 engines = [ Popen(['ipengine','--logfile',englogfile])
207 for i in range(opt.n) ]
208 eids = [e.pid for e in engines]
209 print 'Engines PIDs: ',eids
210 print 'Log files: %s*' % englogfile
204 def start(self, n):
205 dlist = []
206 for i in range(n):
207 el = EngineLauncher(extra_args=self.extra_args)
208 d = el.start()
209 self.launchers.append(el)
210 dlist.append(d)
211 dfinal = gatherBoth(dlist, consumeErrors=True)
212 dfinal.addCallback(self._handle_start)
213 return dfinal
211 214
212 proc_ids = eids + [controller.pid]
213 procs = engines + [controller]
214
215 grpid = os.getpgrp()
216 try:
217 startMsg('127.0.0.1')
218 print 'You can also hit Ctrl-C to stop it, or use from the cmd line:'
219 print
220 print 'kill -INT',grpid
221 print
222 try:
223 while True:
224 time.sleep(5)
225 except:
226 pass
227 finally:
228 print 'Stopping cluster. Cleaning up...'
229 cleanup(stop,controller,engines)
230 for i in range(4):
231 time.sleep(i+2)
232 nZombies = numAlive(controller,engines)
233 if nZombies== 0:
234 print 'OK: All processes cleaned up.'
235 break
236 print 'Trying again, %d processes did not stop...' % nZombies
237 cleanup(kill,controller,engines)
238 if numAlive(controller,engines) == 0:
239 print 'OK: All processes cleaned up.'
240 break
241 else:
242 print '*'*75
243 print 'ERROR: could not kill some processes, try to do it',
244 print 'manually.'
245 zombies = []
246 if controller.returncode is None:
247 print 'Controller is alive: pid =',controller.pid
248 zombies.append(controller.pid)
249 liveEngines = [ e for e in engines if e.returncode is None ]
250 for e in liveEngines:
251 print 'Engine is alive: pid =',e.pid
252 zombies.append(e.pid)
253 print
254 print 'Zombie summary:',' '.join(map(str,zombies))
255
256 def clusterRemote(opt,arg):
257 """Start a remote cluster over SSH"""
258
259 # B. Granger, 9/3/08
260 # The launching of a remote cluster using SSH and a clusterfile
261 # is broken. Because it won't be fixed before the 0.9 release,
262 # we are removing it. For now, we just print a message to the
263 # user and abort.
215 def _handle_start(self, r):
216 log.msg('Engines started with pids: %r' % r)
217 return r
264 218
265 print """The launching of a remote IPython cluster using SSL
266 and a clusterfile has been removed in this release.
267 It has been broken for a while and we are in the process
268 of building a new process management system that will be
269 used to provide a more robust way of starting an IPython
270 cluster.
271
272 For now remote clusters have to be launched using ipcontroller
273 and ipengine separately.
274 """
275 sys.exit(1)
276
277 # Load the remote cluster configuration
278 clConfig = {}
279 execfile(opt.clusterfile,clConfig)
280 contConfig = clConfig['controller']
281 engConfig = clConfig['engines']
282 # Determine where to find sshx:
283 sshx = clConfig.get('sshx',os.environ.get('IPYTHON_SSHX','sshx'))
219 def _handle_stop(self, r):
220 log.msg('Engines received signal: %r' % r)
221 return r
222
223 def signal(self, sig):
224 dlist = []
225 for el in self.launchers:
226 d = el.get_stop_deferred()
227 dlist.append(d)
228 el.signal(sig)
229 dfinal = gatherBoth(dlist, consumeErrors=True)
230 dfinal.addCallback(self._handle_stop)
231 return dfinal
232
233 def interrupt_then_kill(self, delay=1.0):
234 dlist = []
235 for el in self.launchers:
236 d = el.get_stop_deferred()
237 dlist.append(d)
238 el.interrupt_then_kill(delay)
239 dfinal = gatherBoth(dlist, consumeErrors=True)
240 dfinal.addCallback(self._handle_stop)
241 return dfinal
242
243
244 class BatchEngineSet(object):
284 245
285 # Store all logs inside the ipython directory
286 ipdir = get_ipython_dir()
287 pjoin = os.path.join
288
289 logfile = opt.logfile
290 if logfile is None:
291 logdir_base = pjoin(ipdir,'log')
292 ensureDir(logdir_base)
293 logfile = pjoin(logdir_base,'ipcluster')
294
295 # Append this script's PID to the logfile name always
296 logfile = '%s-%s' % (logfile,os.getpid())
246 # Subclasses must fill these in. See PBSEngineSet
247 submit_command = ''
248 delete_command = ''
249 job_id_regexp = ''
297 250
298 print 'Starting controller:'
299 # Controller data:
300 xsys = os.system
301
302 contHost = contConfig['host']
303 contLog = '%s-con-%s-' % (logfile,contHost)
304 cmd = "ssh %s '%s' 'ipcontroller --logfile %s' &" % \
305 (contHost,sshx,contLog)
306 #print 'cmd:<%s>' % cmd # dbg
307 xsys(cmd)
308 time.sleep(2)
309
310 print 'Starting engines: '
311 for engineHost,engineData in engConfig.iteritems():
312 if isinstance(engineData,int):
313 numEngines = engineData
251 def __init__(self, template_file, **kwargs):
252 self.template_file = template_file
253 self.context = {}
254 self.context.update(kwargs)
255 self.batch_file = self.template_file+'-run'
256
257 def parse_job_id(self, output):
258 m = re.match(self.job_id_regexp, output)
259 if m is not None:
260 job_id = m.group()
314 261 else:
315 raise NotImplementedError('port configuration not finished for engines')
316
317 print 'Sarting %d engines on %s' % (numEngines,engineHost)
318 engLog = '%s-eng-%s-' % (logfile,engineHost)
319 for i in range(numEngines):
320 cmd = "ssh %s '%s' 'ipengine --controller-ip %s --logfile %s' &" % \
321 (engineHost,sshx,contHost,engLog)
322 #print 'cmd:<%s>' % cmd # dbg
323 xsys(cmd)
324 # Wait after each host a little bit
325 time.sleep(1)
326
327 startMsg(contConfig['host'])
262 raise Exception("job id couldn't be determined: %s" % output)
263 self.job_id = job_id
264 log.msg('Job started with job id: %r' % job_id)
265 return job_id
266
267 def write_batch_script(self, n):
268 self.context['n'] = n
269 template = open(self.template_file, 'r').read()
270 log.msg('Using template for batch script: %s' % self.template_file)
271 script_as_string = Itpl.itplns(template, self.context)
272 log.msg('Writing instantiated batch script: %s' % self.batch_file)
273 f = open(self.batch_file,'w')
274 f.write(script_as_string)
275 f.close()
276
277 def handle_error(self, f):
278 f.printTraceback()
279 f.raiseException()
280
281 def start(self, n):
282 self.write_batch_script(n)
283 d = getProcessOutput(self.submit_command,
284 [self.batch_file],env=os.environ)
285 d.addCallback(self.parse_job_id)
286 d.addErrback(self.handle_error)
287 return d
328 288
329 def main():
330 """Main driver for the two big options: local or remote cluster."""
289 def kill(self):
290 d = getProcessOutput(self.delete_command,
291 [self.job_id],env=os.environ)
292 return d
293
294 class PBSEngineSet(BatchEngineSet):
331 295
332 if sys.platform=='win32':
333 print """ipcluster does not work on Microsoft Windows. Please start
334 your IPython cluster using the ipcontroller and ipengine scripts."""
335 sys.exit(1)
296 submit_command = 'qsub'
297 delete_command = 'qdel'
298 job_id_regexp = '\d+'
336 299
337 opt,arg = parse_args()
300 def __init__(self, template_file, **kwargs):
301 BatchEngineSet.__init__(self, template_file, **kwargs)
302
303
304 #-----------------------------------------------------------------------------
305 # Main functions for the different types of clusters
306 #-----------------------------------------------------------------------------
307
308 # TODO:
309 # The logic in these codes should be moved into classes like LocalCluster
310 # MpirunCluster, PBSCluster, etc. This would remove alot of the duplications.
311 # The main functions should then just parse the command line arguments, create
312 # the appropriate class and call a 'start' method.
313
314 def main_local(args):
315 cont_args = []
316 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
317 if args.x:
318 cont_args.append('-x')
319 if args.y:
320 cont_args.append('-y')
321 cl = ControllerLauncher(extra_args=cont_args)
322 dstart = cl.start()
323 def start_engines(cont_pid):
324 engine_args = []
325 engine_args.append('--logfile=%s' % \
326 pjoin(args.logdir,'ipengine%s-' % cont_pid))
327 eset = LocalEngineSet(extra_args=engine_args)
328 def shutdown(signum, frame):
329 log.msg('Stopping local cluster')
330 # We are still playing with the times here, but these seem
331 # to be reliable in allowing everything to exit cleanly.
332 eset.interrupt_then_kill(0.5)
333 cl.interrupt_then_kill(0.5)
334 reactor.callLater(1.0, reactor.stop)
335 signal.signal(signal.SIGINT,shutdown)
336 d = eset.start(args.n)
337 return d
338 def delay_start(cont_pid):
339 # This is needed because the controller doesn't start listening
340 # right when it starts and the controller needs to write
341 # furl files for the engine to pick up
342 reactor.callLater(1.0, start_engines, cont_pid)
343 dstart.addCallback(delay_start)
344 dstart.addErrback(lambda f: f.raiseException())
345
346 def main_mpirun(args):
347 cont_args = []
348 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
349 if args.x:
350 cont_args.append('-x')
351 if args.y:
352 cont_args.append('-y')
353 cl = ControllerLauncher(extra_args=cont_args)
354 dstart = cl.start()
355 def start_engines(cont_pid):
356 raw_args = ['mpirun']
357 raw_args.extend(['-n',str(args.n)])
358 raw_args.append('ipengine')
359 raw_args.append('-l')
360 raw_args.append(pjoin(args.logdir,'ipengine%s-' % cont_pid))
361 if args.mpi:
362 raw_args.append('--mpi=%s' % args.mpi)
363 eset = ProcessLauncher(raw_args)
364 def shutdown(signum, frame):
365 log.msg('Stopping local cluster')
366 # We are still playing with the times here, but these seem
367 # to be reliable in allowing everything to exit cleanly.
368 eset.interrupt_then_kill(1.0)
369 cl.interrupt_then_kill(1.0)
370 reactor.callLater(2.0, reactor.stop)
371 signal.signal(signal.SIGINT,shutdown)
372 d = eset.start()
373 return d
374 def delay_start(cont_pid):
375 # This is needed because the controller doesn't start listening
376 # right when it starts and the controller needs to write
377 # furl files for the engine to pick up
378 reactor.callLater(1.0, start_engines, cont_pid)
379 dstart.addCallback(delay_start)
380 dstart.addErrback(lambda f: f.raiseException())
381
382 def main_pbs(args):
383 cont_args = []
384 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
385 if args.x:
386 cont_args.append('-x')
387 if args.y:
388 cont_args.append('-y')
389 cl = ControllerLauncher(extra_args=cont_args)
390 dstart = cl.start()
391 def start_engines(r):
392 pbs_set = PBSEngineSet(args.pbsscript)
393 def shutdown(signum, frame):
394 log.msg('Stopping pbs cluster')
395 d = pbs_set.kill()
396 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
397 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
398 signal.signal(signal.SIGINT,shutdown)
399 d = pbs_set.start(args.n)
400 return d
401 dstart.addCallback(start_engines)
402 dstart.addErrback(lambda f: f.raiseException())
403
404
405 def get_args():
406 base_parser = argparse.ArgumentParser(add_help=False)
407 base_parser.add_argument(
408 '-x',
409 action='store_true',
410 dest='x',
411 help='turn off client security'
412 )
413 base_parser.add_argument(
414 '-y',
415 action='store_true',
416 dest='y',
417 help='turn off engine security'
418 )
419 base_parser.add_argument(
420 "--logdir",
421 type=str,
422 dest="logdir",
423 help="directory to put log files (default=$IPYTHONDIR/log)",
424 default=pjoin(get_ipython_dir(),'log')
425 )
426 base_parser.add_argument(
427 "-n",
428 "--num",
429 type=int,
430 dest="n",
431 default=2,
432 help="the number of engines to start"
433 )
434
435 parser = argparse.ArgumentParser(
436 description='IPython cluster startup. This starts a controller and\
437 engines using various approaches. THIS IS A TECHNOLOGY PREVIEW AND\
438 THE API WILL CHANGE SIGNIFICANTLY BEFORE THE FINAL RELEASE.'
439 )
440 subparsers = parser.add_subparsers(
441 help='available cluster types. For help, do "ipcluster TYPE --help"')
442
443 parser_local = subparsers.add_parser(
444 'local',
445 help='run a local cluster',
446 parents=[base_parser]
447 )
448 parser_local.set_defaults(func=main_local)
449
450 parser_mpirun = subparsers.add_parser(
451 'mpirun',
452 help='run a cluster using mpirun',
453 parents=[base_parser]
454 )
455 parser_mpirun.add_argument(
456 "--mpi",
457 type=str,
458 dest="mpi", # Don't put a default here to allow no MPI support
459 help="how to call MPI_Init (default=mpi4py)"
460 )
461 parser_mpirun.set_defaults(func=main_mpirun)
462
463 parser_pbs = subparsers.add_parser(
464 'pbs',
465 help='run a pbs cluster',
466 parents=[base_parser]
467 )
468 parser_pbs.add_argument(
469 '--pbs-script',
470 type=str,
471 dest='pbsscript',
472 help='PBS script template',
473 default='pbs.template'
474 )
475 parser_pbs.set_defaults(func=main_pbs)
476 args = parser.parse_args()
477 return args
338 478
339 clusterfile = opt.clusterfile
340 if clusterfile:
341 clusterRemote(opt,arg)
342 else:
343 clusterLocal(opt,arg)
344
345
346 if __name__=='__main__':
479 def main():
480 args = get_args()
481 reactor.callWhenRunning(args.func, args)
482 log.startLogging(sys.stdout)
483 reactor.run()
484
485 if __name__ == '__main__':
347 486 main()
@@ -1,366 +1,388 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3
4 4 """The IPython controller."""
5 5
6 6 __docformat__ = "restructuredtext en"
7 7
8 8 #-------------------------------------------------------------------------------
9 9 # Copyright (C) 2008 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-------------------------------------------------------------------------------
14 14
15 15 #-------------------------------------------------------------------------------
16 16 # Imports
17 17 #-------------------------------------------------------------------------------
18 18
19 19 # Python looks for an empty string at the beginning of sys.path to enable
20 20 # importing from the cwd.
21 21 import sys
22 22 sys.path.insert(0, '')
23 23
24 24 import sys, time, os
25 25 from optparse import OptionParser
26 26
27 27 from twisted.application import internet, service
28 28 from twisted.internet import reactor, error, defer
29 29 from twisted.python import log
30 30
31 31 from IPython.kernel.fcutil import Tub, UnauthenticatedTub, have_crypto
32 32
33 33 # from IPython.tools import growl
34 34 # growl.start("IPython1 Controller")
35 35
36 36 from IPython.kernel.error import SecurityError
37 37 from IPython.kernel import controllerservice
38 38 from IPython.kernel.fcutil import check_furl_file_security
39 39
40 40 from IPython.kernel.config import config_manager as kernel_config_manager
41 41 from IPython.config.cutils import import_item
42 42
43 43
44 44 #-------------------------------------------------------------------------------
45 45 # Code
46 46 #-------------------------------------------------------------------------------
47 47
48 48 def make_tub(ip, port, secure, cert_file):
49 49 """
50 50 Create a listening tub given an ip, port, and cert_file location.
51 51
52 52 :Parameters:
53 53 ip : str
54 54 The ip address that the tub should listen on. Empty means all
55 55 port : int
56 56 The port that the tub should listen on. A value of 0 means
57 57 pick a random port
58 58 secure: boolean
59 59 Will the connection be secure (in the foolscap sense)
60 60 cert_file:
61 61 A filename of a file to be used for theSSL certificate
62 62 """
63 63 if secure:
64 64 if have_crypto:
65 65 tub = Tub(certFile=cert_file)
66 66 else:
67 raise SecurityError("OpenSSL is not available, so we can't run in secure mode, aborting")
67 raise SecurityError("""
68 OpenSSL/pyOpenSSL is not available, so we can't run in secure mode.
69 Try running without security using 'ipcontroller -xy'.
70 """)
68 71 else:
69 72 tub = UnauthenticatedTub()
70 73
71 74 # Set the strport based on the ip and port and start listening
72 75 if ip == '':
73 76 strport = "tcp:%i" % port
74 77 else:
75 78 strport = "tcp:%i:interface=%s" % (port, ip)
76 79 listener = tub.listenOn(strport)
77 80
78 81 return tub, listener
79 82
80 83 def make_client_service(controller_service, config):
81 84 """
82 85 Create a service that will listen for clients.
83 86
84 87 This service is simply a `foolscap.Tub` instance that has a set of Referenceables
85 88 registered with it.
86 89 """
87 90
88 91 # Now create the foolscap tub
89 92 ip = config['controller']['client_tub']['ip']
90 93 port = config['controller']['client_tub'].as_int('port')
91 94 location = config['controller']['client_tub']['location']
92 95 secure = config['controller']['client_tub']['secure']
93 96 cert_file = config['controller']['client_tub']['cert_file']
94 97 client_tub, client_listener = make_tub(ip, port, secure, cert_file)
95 98
96 99 # Set the location in the trivial case of localhost
97 100 if ip == 'localhost' or ip == '127.0.0.1':
98 101 location = "127.0.0.1"
99 102
100 103 if not secure:
101 104 log.msg("WARNING: you are running the controller with no client security")
102 105
103 106 def set_location_and_register():
104 107 """Set the location for the tub and return a deferred."""
105 108
106 109 def register(empty, ref, furl_file):
107 110 client_tub.registerReference(ref, furlFile=furl_file)
108 111
109 112 if location == '':
110 113 d = client_tub.setLocationAutomatically()
111 114 else:
112 115 d = defer.maybeDeferred(client_tub.setLocation, "%s:%i" % (location, client_listener.getPortnum()))
113 116
114 117 for ciname, ci in config['controller']['controller_interfaces'].iteritems():
115 118 log.msg("Adapting Controller to interface: %s" % ciname)
116 119 furl_file = ci['furl_file']
117 120 log.msg("Saving furl for interface [%s] to file: %s" % (ciname, furl_file))
118 121 check_furl_file_security(furl_file, secure)
119 122 adapted_controller = import_item(ci['controller_interface'])(controller_service)
120 123 d.addCallback(register, import_item(ci['fc_interface'])(adapted_controller),
121 124 furl_file=ci['furl_file'])
122 125
123 126 reactor.callWhenRunning(set_location_and_register)
124 127 return client_tub
125 128
126 129
127 130 def make_engine_service(controller_service, config):
128 131 """
129 132 Create a service that will listen for engines.
130 133
131 134 This service is simply a `foolscap.Tub` instance that has a set of Referenceables
132 135 registered with it.
133 136 """
134 137
135 138 # Now create the foolscap tub
136 139 ip = config['controller']['engine_tub']['ip']
137 140 port = config['controller']['engine_tub'].as_int('port')
138 141 location = config['controller']['engine_tub']['location']
139 142 secure = config['controller']['engine_tub']['secure']
140 143 cert_file = config['controller']['engine_tub']['cert_file']
141 144 engine_tub, engine_listener = make_tub(ip, port, secure, cert_file)
142 145
143 146 # Set the location in the trivial case of localhost
144 147 if ip == 'localhost' or ip == '127.0.0.1':
145 148 location = "127.0.0.1"
146 149
147 150 if not secure:
148 151 log.msg("WARNING: you are running the controller with no engine security")
149 152
150 153 def set_location_and_register():
151 154 """Set the location for the tub and return a deferred."""
152 155
153 156 def register(empty, ref, furl_file):
154 157 engine_tub.registerReference(ref, furlFile=furl_file)
155 158
156 159 if location == '':
157 160 d = engine_tub.setLocationAutomatically()
158 161 else:
159 162 d = defer.maybeDeferred(engine_tub.setLocation, "%s:%i" % (location, engine_listener.getPortnum()))
160 163
161 164 furl_file = config['controller']['engine_furl_file']
162 165 engine_fc_interface = import_item(config['controller']['engine_fc_interface'])
163 166 log.msg("Saving furl for the engine to file: %s" % furl_file)
164 167 check_furl_file_security(furl_file, secure)
165 168 fc_controller = engine_fc_interface(controller_service)
166 169 d.addCallback(register, fc_controller, furl_file=furl_file)
167 170
168 171 reactor.callWhenRunning(set_location_and_register)
169 172 return engine_tub
170 173
171 174 def start_controller():
172 175 """
173 176 Start the controller by creating the service hierarchy and starting the reactor.
174 177
175 178 This method does the following:
176 179
177 180 * It starts the controller logging
178 181 * In execute an import statement for the controller
179 182 * It creates 2 `foolscap.Tub` instances for the client and the engines
180 183 and registers `foolscap.Referenceables` with the tubs to expose the
181 184 controller to engines and clients.
182 185 """
183 186 config = kernel_config_manager.get_config_obj()
184 187
185 188 # Start logging
186 189 logfile = config['controller']['logfile']
187 190 if logfile:
188 191 logfile = logfile + str(os.getpid()) + '.log'
189 192 try:
190 193 openLogFile = open(logfile, 'w')
191 194 except:
192 195 openLogFile = sys.stdout
193 196 else:
194 197 openLogFile = sys.stdout
195 198 log.startLogging(openLogFile)
196 199
197 200 # Execute any user defined import statements
198 201 cis = config['controller']['import_statement']
199 202 if cis:
200 203 try:
201 204 exec cis in globals(), locals()
202 205 except:
203 206 log.msg("Error running import_statement: %s" % cis)
204 207
208 # Delete old furl files unless the reuse_furls is set
209 reuse = config['controller']['reuse_furls']
210 if not reuse:
211 paths = (config['controller']['engine_furl_file'],
212 config['controller']['controller_interfaces']['task']['furl_file'],
213 config['controller']['controller_interfaces']['multiengine']['furl_file']
214 )
215 for p in paths:
216 if os.path.isfile(p):
217 os.remove(p)
218
205 219 # Create the service hierarchy
206 220 main_service = service.MultiService()
207 221 # The controller service
208 222 controller_service = controllerservice.ControllerService()
209 223 controller_service.setServiceParent(main_service)
210 224 # The client tub and all its refereceables
211 225 client_service = make_client_service(controller_service, config)
212 226 client_service.setServiceParent(main_service)
213 227 # The engine tub
214 228 engine_service = make_engine_service(controller_service, config)
215 229 engine_service.setServiceParent(main_service)
216 230 # Start the controller service and set things running
217 231 main_service.startService()
218 232 reactor.run()
219 233
220 234 def init_config():
221 235 """
222 236 Initialize the configuration using default and command line options.
223 237 """
224 238
225 239 parser = OptionParser()
226 240
227 241 # Client related options
228 242 parser.add_option(
229 243 "--client-ip",
230 244 type="string",
231 245 dest="client_ip",
232 246 help="the IP address or hostname the controller will listen on for client connections"
233 247 )
234 248 parser.add_option(
235 249 "--client-port",
236 250 type="int",
237 251 dest="client_port",
238 252 help="the port the controller will listen on for client connections"
239 253 )
240 254 parser.add_option(
241 255 '--client-location',
242 256 type="string",
243 257 dest="client_location",
244 258 help="hostname or ip for clients to connect to"
245 259 )
246 260 parser.add_option(
247 261 "-x",
248 262 action="store_false",
249 263 dest="client_secure",
250 264 help="turn off all client security"
251 265 )
252 266 parser.add_option(
253 267 '--client-cert-file',
254 268 type="string",
255 269 dest="client_cert_file",
256 270 help="file to store the client SSL certificate"
257 271 )
258 272 parser.add_option(
259 273 '--task-furl-file',
260 274 type="string",
261 275 dest="task_furl_file",
262 276 help="file to store the FURL for task clients to connect with"
263 277 )
264 278 parser.add_option(
265 279 '--multiengine-furl-file',
266 280 type="string",
267 281 dest="multiengine_furl_file",
268 282 help="file to store the FURL for multiengine clients to connect with"
269 283 )
270 284 # Engine related options
271 285 parser.add_option(
272 286 "--engine-ip",
273 287 type="string",
274 288 dest="engine_ip",
275 289 help="the IP address or hostname the controller will listen on for engine connections"
276 290 )
277 291 parser.add_option(
278 292 "--engine-port",
279 293 type="int",
280 294 dest="engine_port",
281 295 help="the port the controller will listen on for engine connections"
282 296 )
283 297 parser.add_option(
284 298 '--engine-location',
285 299 type="string",
286 300 dest="engine_location",
287 301 help="hostname or ip for engines to connect to"
288 302 )
289 303 parser.add_option(
290 304 "-y",
291 305 action="store_false",
292 306 dest="engine_secure",
293 307 help="turn off all engine security"
294 308 )
295 309 parser.add_option(
296 310 '--engine-cert-file',
297 311 type="string",
298 312 dest="engine_cert_file",
299 313 help="file to store the engine SSL certificate"
300 314 )
301 315 parser.add_option(
302 316 '--engine-furl-file',
303 317 type="string",
304 318 dest="engine_furl_file",
305 319 help="file to store the FURL for engines to connect with"
306 320 )
307 321 parser.add_option(
308 322 "-l", "--logfile",
309 323 type="string",
310 324 dest="logfile",
311 325 help="log file name (default is stdout)"
312 326 )
313 327 parser.add_option(
314 328 "--ipythondir",
315 329 type="string",
316 330 dest="ipythondir",
317 331 help="look for config files and profiles in this directory"
318 332 )
333 parser.add_option(
334 "-r",
335 action="store_true",
336 dest="reuse_furls",
337 help="try to reuse all furl files"
338 )
319 339
320 340 (options, args) = parser.parse_args()
321 341
322 342 kernel_config_manager.update_config_obj_from_default_file(options.ipythondir)
323 343 config = kernel_config_manager.get_config_obj()
324 344
325 345 # Update with command line options
326 346 if options.client_ip is not None:
327 347 config['controller']['client_tub']['ip'] = options.client_ip
328 348 if options.client_port is not None:
329 349 config['controller']['client_tub']['port'] = options.client_port
330 350 if options.client_location is not None:
331 351 config['controller']['client_tub']['location'] = options.client_location
332 352 if options.client_secure is not None:
333 353 config['controller']['client_tub']['secure'] = options.client_secure
334 354 if options.client_cert_file is not None:
335 355 config['controller']['client_tub']['cert_file'] = options.client_cert_file
336 356 if options.task_furl_file is not None:
337 357 config['controller']['controller_interfaces']['task']['furl_file'] = options.task_furl_file
338 358 if options.multiengine_furl_file is not None:
339 359 config['controller']['controller_interfaces']['multiengine']['furl_file'] = options.multiengine_furl_file
340 360 if options.engine_ip is not None:
341 361 config['controller']['engine_tub']['ip'] = options.engine_ip
342 362 if options.engine_port is not None:
343 363 config['controller']['engine_tub']['port'] = options.engine_port
344 364 if options.engine_location is not None:
345 365 config['controller']['engine_tub']['location'] = options.engine_location
346 366 if options.engine_secure is not None:
347 367 config['controller']['engine_tub']['secure'] = options.engine_secure
348 368 if options.engine_cert_file is not None:
349 369 config['controller']['engine_tub']['cert_file'] = options.engine_cert_file
350 370 if options.engine_furl_file is not None:
351 371 config['controller']['engine_furl_file'] = options.engine_furl_file
372 if options.reuse_furls is not None:
373 config['controller']['reuse_furls'] = options.reuse_furls
352 374
353 375 if options.logfile is not None:
354 376 config['controller']['logfile'] = options.logfile
355 377
356 378 kernel_config_manager.update_config_obj(config)
357 379
358 380 def main():
359 381 """
360 382 After creating the configuration information, start the controller.
361 383 """
362 384 init_config()
363 385 start_controller()
364 386
365 387 if __name__ == "__main__":
366 388 main()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/config/config.py to sandbox/config.py
1 NO CONTENT: file renamed from IPython/config/tests/sample_config.py to sandbox/sample_config.py
1 NO CONTENT: file renamed from IPython/config/tests/test_config.py to sandbox/test_config.py
1 NO CONTENT: file renamed from IPython/config/traitlets.py to sandbox/traitlets.py
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (660 lines changed) Show them Hide them
1 NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now