##// END OF EJS Templates
Wildcard system cleanup, ipmaker speedups, bugfix in globals handling...
fperez -
r41:47084614
parent child
Show More
@@ -1,7 +1,7
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 922 2005-11-13 10:21:08Z fperez $"""
4 $Id: Magic.py 923 2005-11-15 08:51:15Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -296,10 +296,9 license. To use profiling, please install"python2.3-profiler" from non-free.""")
296 Struct with the options as keys and the stripped argument string still
296 Struct with the options as keys and the stripped argument string still
297 as a string.
297 as a string.
298
298
299 arg_str is quoted as a true sys.argv vector by calling on the fly a
299 arg_str is quoted as a true sys.argv vector by using shlex.split.
300 python process in a subshell. This allows us to easily expand
300 This allows us to easily expand variables, glob files, quote
301 variables, glob files, quote arguments, etc, with all the power and
301 arguments, etc.
302 correctness of the underlying system shell.
303
302
304 Options:
303 Options:
305 -mode: default 'string'. If given as 'list', the argument string is
304 -mode: default 'string'. If given as 'list', the argument string is
@@ -665,55 +664,109 Currently the magic system has the following functions:\n"""
665 def magic_psearch(self, parameter_s=''):
664 def magic_psearch(self, parameter_s=''):
666 """Search for object in namespaces by wildcard.
665 """Search for object in namespaces by wildcard.
667
666
668 %psearch PATTERN [OBJECT TYPE] [-NAMESPACE]* [+NAMESPACE]* [-a] [-c]
667 %psearch [options] PATTERN [OBJECT TYPE]
669
668
670 Note: ? can be used as a synonym for %psearch, at the beginning or at
669 Note: ? can be used as a synonym for %psearch, at the beginning or at
671 the end: both a*? and ?a* are equivalent to '%psearch a*'.
670 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
672
671 rest of the command line must be unchanged (options come first), so
673 PATTERN
672 for example the following forms are equivalent
674
673
675 where PATTERN is a string containing * as a wildcard similar to its
674 %psearch -i a* function
676 use in a shell. The pattern is matched in all namespaces on the
675 -i a* function?
677 search path. By default objects starting with a single _ are not
676 ?-i a* function
678 matched, many IPython generated objects have a single underscore. The
677
679 default is case insensitive matching. Matching is also done on the
678 Arguments:
680 attributes of objects and not only on the objects in a module.
679
681
680 PATTERN
682 [OBJECT TYPE]
681
683 Is the name of a python type from the types module. The name is given
682 where PATTERN is a string containing * as a wildcard similar to its
684 in lowercase without the ending type, ex. StringType is written
683 use in a shell. The pattern is matched in all namespaces on the
685 string. By adding a type here only objects matching the given type are
684 search path. By default objects starting with a single _ are not
686 matched. Using all here makes the pattern match all types (this is the
685 matched, many IPython generated objects have a single
687 default).
686 underscore. The default is case insensitive matching. Matching is
688
687 also done on the attributes of objects and not only on the objects
689 [-NAMESPACE]* [+NAMESPACE]*
688 in a module.
690 The possible namespaces are builtin, user, internal, alias. Where
689
691 builtin and user are default. Builtin contains the python module
690 [OBJECT TYPE]
692 builtin, user contains all imported namespaces, alias only contain the
691
693 shell aliases and no python objects, internal contains objects used by
692 Is the name of a python type from the types module. The name is
694 IPython. The namespaces on the search path are removed by -namespace
693 given in lowercase without the ending type, ex. StringType is
695 and added by +namespace.
694 written string. By adding a type here only objects matching the
696
695 given type are matched. Using all here makes the pattern match all
697 [-a] makes the pattern match even objects with a single underscore.
696 types (this is the default).
698 [-c] makes the pattern case sensitive.
697
698 Options:
699
700 -a: makes the pattern match even objects whose names start with a
701 single underscore. These names are normally ommitted from the
702 search.
703
704 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 these options is given, the default is read from your ipythonrc
706 file. The option name which sets this value is
707 'wildcards_case_sensitive'. If this option is not specified in your
708 ipythonrc file, IPython's internal default is to do a case sensitive
709 search.
710
711 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 specifiy can be searched in any of the following namespaces:
713 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin' and 'user' are the search defaults. Note that you should
715 not use quotes when specifying namespaces.
716
717 'Builtin' contains the python module builtin, 'user' contains all
718 user data, 'alias' only contain the shell aliases and no python
719 objects, 'internal' contains objects used by IPython. The
720 'user_global' namespace is only used by embedded IPython instances,
721 and it contains module-level globals. You can add namespaces to the
722 search with -s or exclude them with -e (these options can be given
723 more than once).
699
724
700 Examples:
725 Examples:
701
726
702 %psearch a* list objects beginning with an a
727 %psearch a* -> objects beginning with an a
703 %psearch a* function list all functions beginning with an a
728 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
704 %psearch re.e* list objects beginning with an e in module re
729 %psearch a* function -> all functions beginning with an a
705 %psearch r*.e* list objects that starts with e in modules starting in r
730 %psearch re.e* -> objects beginning with an e in module re
706 %psearch r*.* string list all strings in modules beginning with r
731 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.* string -> all strings in modules beginning with r
707
733
708 Case sensitve search:
734 Case sensitve search:
709
735
710 %psearch a* -c list all object beginning with lower case a
736 %psearch -c a* list all object beginning with lower case a
711
737
712 Show objects beginning with a single _:
738 Show objects beginning with a single _:
713
739
714 %psearch _* -a list objects beginning with underscore"""
740 %psearch -a _* list objects beginning with a single underscore"""
741
742 # default namespaces to be searched
743 def_search = ['user','builtin']
744
745 # Process options/args
746 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opt = opts.get
748 shell = self.shell
749 psearch = shell.inspector.psearch
715
750
716 self.shell.inspector.psearch(parameter_s,shell=self.shell)
751 # select case options
752 if opts.has_key('i'):
753 ignore_case = True
754 elif opts.has_key('c'):
755 ignore_case = False
756 else:
757 ignore_case = not shell.rc.wildcards_case_sensitive
758
759 # Build list of namespaces to search from user options
760 def_search.extend(opt('s',[]))
761 ns_exclude = ns_exclude=opt('e',[])
762 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763
764 # Call the actual search
765 try:
766 psearch(args,shell.ns_table,ns_search,
767 show_all=opt('a'),ignore_case=ignore_case)
768 except:
769 shell.showtraceback()
717
770
718 def magic_who_ls(self, parameter_s=''):
771 def magic_who_ls(self, parameter_s=''):
719 """Return a sorted list of all interactive variables.
772 """Return a sorted list of all interactive variables.
@@ -6,7 +6,7 Uses syntax highlighting for presenting the various information elements.
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8
8
9 $Id: OInspect.py 922 2005-11-13 10:21:08Z fperez $
9 $Id: OInspect.py 923 2005-11-15 08:51:15Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
@@ -23,13 +23,14 __license__ = Release.license
23 __all__ = ['Inspector','InspectColors']
23 __all__ = ['Inspector','InspectColors']
24
24
25 # stdlib modules
25 # stdlib modules
26 import __builtin__
26 import inspect,linecache,types,StringIO,string
27 import inspect,linecache,types,StringIO,string
27
28
28 # IPython's own
29 # IPython's own
29 from IPython import PyColorize
30 from IPython import PyColorize
30 from IPython.Itpl import itpl
31 from IPython.Itpl import itpl
31 from IPython.wildcard import choose_namespaces,list_namespace
32 from IPython.wildcard import list_namespace
32 from IPython.genutils import page,indent,Term
33 from IPython.genutils import page,indent,Term,mkdict
33 from IPython.ColorANSI import *
34 from IPython.ColorANSI import *
34
35
35 #****************************************************************************
36 #****************************************************************************
@@ -398,44 +399,56 class Inspector:
398 page(output)
399 page(output)
399 # end pinfo
400 # end pinfo
400
401
401 def psearch(self,oname='',formatter=None,shell=None):
402 def psearch(self,pattern,ns_table,ns_search=[],
403 ignore_case=False,show_all=False):
402 """Search namespaces with wildcards for objects.
404 """Search namespaces with wildcards for objects.
403
405
406 Arguments:
407
408 - pattern: string containing shell-like wildcards to use in namespace
409 searches and optionally a type specification to narrow the search to
410 objects of that type.
411
412 - ns_table: dict of name->namespaces for search.
413
404 Optional arguments:
414 Optional arguments:
405
415
406 - oname: rest of the commandline containging pattern and options.
416 - ns_search: list of namespace names to include in search.
407
417
408 - formatter: Not used.
418 - ignore_case(False): make the search case-insensitive.
409
419
410 - shell: The shell object from the Magic class. Needed to access
420 - show_all(False): show all names, including those starting with
411 the namespaces.
421 underscores.
412 """
422 """
413 option_list = ['-c','-a']
423 # defaults
414 cmds = oname.split()
415 filter = ''
416 type_pattern = 'all'
424 type_pattern = 'all'
417 options = [x for x in cmds if x in option_list]
425 filter = ''
418 ignorecase = '-c' not in options
426
419 showhidden = '-a' in options
427 cmds = pattern.split()
420 ns_cmds = [x for x in cmds if x[0] in '-+' and x not in option_list]
421 cmds = [x for x in cmds if x[0] not in '-+']
422 len_cmds = len(cmds)
428 len_cmds = len(cmds)
423 if len_cmds == 1:
429 if len_cmds == 1:
424 filter = cmds[0].strip()
430 # Only filter pattern given
431 filter = cmds[0]
425 elif len_cmds == 2:
432 elif len_cmds == 2:
433 # Both filter and type specified
426 filter,type_pattern = cmds
434 filter,type_pattern = cmds
427 elif len_cmds>2:
435 else:
428 # assume we want to choose name spaces. Rather poor design forces
436 raise ValueError('invalid argument string for psearch: <%s>' %
429 #the use of a typepattern in order to choose name spaces
437 pattern)
430 cmds = cmds[:2]
431
438
432 do_list = choose_namespaces(shell,ns_cmds)
439 # filter search namespaces
440 for name in ns_search:
441 if name not in ns_table:
442 raise ValueError('invalid namespace <%s>. Valid names: %s' %
443 (name,ns_table.keys()))
433
444
445 #print 'type_pattern:',type_pattern # dbg
434 search_result = []
446 search_result = []
435 for ns in do_list:
447 for ns_name in ns_search:
448 ns = ns_table[ns_name]
436 tmp_res = list(list_namespace(ns,type_pattern,filter,
449 tmp_res = list(list_namespace(ns,type_pattern,filter,
437 ignorecase=ignorecase,
450 ignore_case=ignore_case,
438 showhidden=showhidden))
451 show_all=show_all))
439 search_result.extend(tmp_res)
452 search_result.extend(tmp_res)
440 search_result.sort()
453 search_result.sort()
441
454
@@ -4,7 +4,7
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 921 2005-11-13 06:51:34Z fperez $"""
7 $Id: Shell.py 923 2005-11-15 08:51:15Z fperez $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
@@ -132,9 +132,6 class IPShellEmbed:
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
134
135 # mark this as an embedded instance so we know if we get a crash
136 # post-mortem
137 self.IP.rc.embedded = 1
138 # copy our own displayhook also
135 # copy our own displayhook also
139 self.sys_displayhook_embed = sys.displayhook
136 self.sys_displayhook_embed = sys.displayhook
140 # and leave the system's display hook clean
137 # and leave the system's display hook clean
@@ -1,5 +1,5
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
1 # -*- Mode: Shell-Script -*- Not really, but shows comments correctly
2 # $Id: ipythonrc 633 2005-07-17 01:03:15Z tzanko $
2 # $Id: ipythonrc 923 2005-11-15 08:51:15Z fperez $
3
3
4 #***************************************************************************
4 #***************************************************************************
5 #
5 #
@@ -262,6 +262,14 separate_out2 0
262 # Simply removes all input/output separators, overriding the choices above.
262 # Simply removes all input/output separators, overriding the choices above.
263 nosep 0
263 nosep 0
264
264
265 # Wildcard searches - IPython has a system for searching names using
266 # shell-like wildcards; type %psearch? for details. This variables sets
267 # whether by default such searches should be case sensitive or not. You can
268 # always override the default at the system command line or the IPython
269 # prompt.
270
271 wildcards_case_sensitive 1
272
265 # xmode - Exception reporting mode.
273 # xmode - Exception reporting mode.
266
274
267 # Valid modes: Plain, Context and Verbose.
275 # Valid modes: Plain, Context and Verbose.
@@ -6,7 +6,7 Requires Python 2.1 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 $Id: iplib.py 921 2005-11-13 06:51:34Z fperez $
9 $Id: iplib.py 923 2005-11-15 08:51:15Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
@@ -508,7 +508,7 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
508
508
509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
510 user_ns = None,user_global_ns=None,banner2='',
510 user_ns = None,user_global_ns=None,banner2='',
511 custom_exceptions=((),None)):
511 custom_exceptions=((),None),embedded=False):
512
512
513 # Put a reference to self in builtins so that any form of embedded or
513 # Put a reference to self in builtins so that any form of embedded or
514 # imported code can test for being inside IPython.
514 # imported code can test for being inside IPython.
@@ -532,6 +532,10 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
532 __builtin__.exit += _exit
532 __builtin__.exit += _exit
533 __builtin__.quit += _exit
533 __builtin__.quit += _exit
534
534
535 # We need to know whether the instance is meant for embedding, since
536 # global/local namespaces need to be handled differently in that case
537 self.embedded = embedded
538
535 # compiler command
539 # compiler command
536 self.compile = CommandCompiler()
540 self.compile = CommandCompiler()
537
541
@@ -584,9 +588,29 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
584 if user_global_ns is None:
588 if user_global_ns is None:
585 user_global_ns = {}
589 user_global_ns = {}
586
590
587 # assign namespaces
591 # Assign namespaces
592 # This is the namespace where all normal user variables live
588 self.user_ns = user_ns
593 self.user_ns = user_ns
594 # Embedded instances require a separate namespace for globals.
595 # Normally this one is unused by non-embedded instances.
589 self.user_global_ns = user_global_ns
596 self.user_global_ns = user_global_ns
597 # A namespace to keep track of internal data structures to prevent
598 # them from cluttering user-visible stuff. Will be updated later
599 self.internal_ns = {}
600
601 # Namespace of system aliases. Each entry in the alias
602 # table must be a 2-tuple of the form (N,name), where N is the number
603 # of positional arguments of the alias.
604 self.alias_table = {}
605
606 # A table holding all the namespaces IPython deals with, so that
607 # introspection facilities can search easily.
608 self.ns_table = {'user':user_ns,
609 'user_global':user_global_ns,
610 'alias':self.alias_table,
611 'internal':self.internal_ns,
612 'builtin':__builtin__.__dict__
613 }
590
614
591 # The user namespace MUST have a pointer to the shell itself.
615 # The user namespace MUST have a pointer to the shell itself.
592 self.user_ns[name] = self
616 self.user_ns[name] = self
@@ -619,11 +643,6 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
619 # dict of output history
643 # dict of output history
620 self.output_hist = {}
644 self.output_hist = {}
621
645
622 # dict of names to be treated as system aliases. Each entry in the
623 # alias table must be a 2-tuple of the form (N,name), where N is the
624 # number of positional arguments of the alias.
625 self.alias_table = {}
626
627 # dict of things NOT to alias (keywords, builtins and some special magics)
646 # dict of things NOT to alias (keywords, builtins and some special magics)
628 no_alias = {}
647 no_alias = {}
629 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
648 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
@@ -956,7 +975,15 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
956
975
957 This is called after the configuration files have been processed to
976 This is called after the configuration files have been processed to
958 'finalize' the initialization."""
977 'finalize' the initialization."""
959
978
979 # Load readline proper
980 if self.rc.readline:
981 self.init_readline()
982
983 # Set user colors (don't do it in the constructor above so that it doesn't
984 # crash if colors option is invalid)
985 self.magic_colors(self.rc.colors)
986
960 # dynamic data that survives through sessions
987 # dynamic data that survives through sessions
961 # XXX make the filename a config option?
988 # XXX make the filename a config option?
962 persist_base = 'persist'
989 persist_base = 'persist'
@@ -1629,7 +1656,16 want to merge them back into the new files.""" % locals()
1629 outflag = 1 # happens in more places, so it's easier as default
1656 outflag = 1 # happens in more places, so it's easier as default
1630 try:
1657 try:
1631 try:
1658 try:
1632 exec code_obj in self.user_global_ns, self.user_ns
1659 # Embedded instances require separate global/local namespaces
1660 # so they can see both the surrounding (local) namespace and
1661 # the module-level globals when called inside another function.
1662 if self.embedded:
1663 exec code_obj in self.user_global_ns, self.user_ns
1664 # Normal (non-embedded) instances should only have a single
1665 # namespace for user code execution, otherwise functions won't
1666 # see interactive top-level globals.
1667 else:
1668 exec code_obj in self.user_ns
1633 finally:
1669 finally:
1634 # Reset our crash handler in place
1670 # Reset our crash handler in place
1635 sys.excepthook = old_excepthook
1671 sys.excepthook = old_excepthook
@@ -6,7 +6,7 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 911 2005-10-08 07:59:40Z fperez $"""
9 $Id: ipmaker.py 923 2005-11-15 08:51:15Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
@@ -82,7 +82,7 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
82 # __IP.name. We set its name via the first parameter passed to
82 # __IP.name. We set its name via the first parameter passed to
83 # InteractiveShell:
83 # InteractiveShell:
84
84
85 IP = shell_class('__IP',user_ns=user_ns,**kw)
85 IP = shell_class('__IP',user_ns=user_ns,embedded=embedded,**kw)
86
86
87 # Put 'help' in the user namespace
87 # Put 'help' in the user namespace
88 from site import _Helper
88 from site import _Helper
@@ -155,7 +155,7 object? -> Details about 'object'. ?object also works, ?? prints more.
155 'readline! readline_merge_completions! '
155 'readline! readline_merge_completions! '
156 'readline_omit__names! '
156 'readline_omit__names! '
157 'rcfile=s separate_in|si=s separate_out|so=s '
157 'rcfile=s separate_in|si=s separate_out|so=s '
158 'separate_out2|so2=s xmode=s '
158 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
159 'magic_docstrings system_verbose! '
159 'magic_docstrings system_verbose! '
160 'multi_line_specials!')
160 'multi_line_specials!')
161
161
@@ -218,6 +218,7 object? -> Details about 'object'. ?object also works, ?? prints more.
218 upgrade = 0,
218 upgrade = 0,
219 Version = 0,
219 Version = 0,
220 xmode = 'Verbose',
220 xmode = 'Verbose',
221 wildcards_case_sensitive = 1,
221 magic_docstrings = 0, # undocumented, for doc generation
222 magic_docstrings = 0, # undocumented, for doc generation
222 )
223 )
223
224
@@ -281,7 +282,7 object? -> Details about 'object'. ?object also works, ?? prints more.
281 except:
282 except:
282 print cmd_line_usage
283 print cmd_line_usage
283 warn('\nError in Arguments: ' + `sys.exc_value`)
284 warn('\nError in Arguments: ' + `sys.exc_value`)
284 sys.exit()
285 sys.exit(1)
285
286
286 # convert the options dict to a struct for much lighter syntax later
287 # convert the options dict to a struct for much lighter syntax later
287 opts = Struct(getopt.optionValues)
288 opts = Struct(getopt.optionValues)
@@ -445,73 +446,72 object? -> Details about 'object'. ?object also works, ?? prints more.
445 # Execute user config
446 # Execute user config
446
447
447 # first, create a valid config structure with the right precedence order:
448 # first, create a valid config structure with the right precedence order:
448 # defaults < rcfile < command line
449 # defaults < rcfile < command line. We make it as a local (IP_rc) to
449 IP.rc = rc_def.copy()
450 # avoid a zillion attribute accesses. Right before returning, this will
450 IP.rc.update(opts_def)
451 # be set as IP.rc.
452 IP_rc = rc_def.copy()
453 IP_rc.update(opts_def)
451 if rcfiledata:
454 if rcfiledata:
452 # now we can update
455 # now we can update
453 IP.rc.update(rcfiledata)
456 IP_rc.update(rcfiledata)
454 IP.rc.update(opts)
457 IP_rc.update(opts)
455 IP.rc.update(rc_override)
458 IP_rc.update(rc_override)
456
459
457 # Store the original cmd line for reference:
460 # Store the original cmd line for reference:
458 IP.rc.opts = opts
461 IP_rc.opts = opts
459 IP.rc.args = args
462 IP_rc.args = args
460
463
461 # create a *runtime* Struct like rc for holding parameters which may be
464 # create a *runtime* Struct like rc for holding parameters which may be
462 # created and/or modified by runtime user extensions.
465 # created and/or modified by runtime user extensions.
463 IP.runtime_rc = Struct()
466 IP.runtime_rc = Struct()
464
467
465 # from this point on, all config should be handled through IP.rc,
468 # from this point on, all config should be handled through IP_rc,
466 # opts* shouldn't be used anymore.
469 # opts* shouldn't be used anymore.
467
470
468 # add personal .ipython dir to sys.path so that users can put things in
471 # add personal .ipython dir to sys.path so that users can put things in
469 # there for customization
472 # there for customization
470 sys.path.append(IP.rc.ipythondir)
473 sys.path.append(IP_rc.ipythondir)
471 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
474 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
472
475
473 # update IP.rc with some special things that need manual
476 # update IP_rc with some special things that need manual
474 # tweaks. Basically options which affect other options. I guess this
477 # tweaks. Basically options which affect other options. I guess this
475 # should just be written so that options are fully orthogonal and we
478 # should just be written so that options are fully orthogonal and we
476 # wouldn't worry about this stuff!
479 # wouldn't worry about this stuff!
477
480
478 if IP.rc.classic:
481 if IP_rc.classic:
479 IP.rc.quick = 1
482 IP_rc.quick = 1
480 IP.rc.cache_size = 0
483 IP_rc.cache_size = 0
481 IP.rc.pprint = 0
484 IP_rc.pprint = 0
482 IP.rc.prompt_in1 = '>>> '
485 IP_rc.prompt_in1 = '>>> '
483 IP.rc.prompt_in2 = '... '
486 IP_rc.prompt_in2 = '... '
484 IP.rc.prompt_out = ''
487 IP_rc.prompt_out = ''
485 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
488 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
486 IP.rc.colors = 'NoColor'
489 IP_rc.colors = 'NoColor'
487 IP.rc.xmode = 'Plain'
490 IP_rc.xmode = 'Plain'
488
491
489 # configure readline
492 # configure readline
490 # Define the history file for saving commands in between sessions
493 # Define the history file for saving commands in between sessions
491 if IP.rc.profile:
494 if IP_rc.profile:
492 histfname = 'history-%s' % IP.rc.profile
495 histfname = 'history-%s' % IP_rc.profile
493 else:
496 else:
494 histfname = 'history'
497 histfname = 'history'
495 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
498 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
496 # Load readline proper
497 if IP.rc.readline:
498 IP.init_readline()
499
499
500 # update exception handlers with rc file status
500 # update exception handlers with rc file status
501 otrap.trap_out() # I don't want these messages ever.
501 otrap.trap_out() # I don't want these messages ever.
502 IP.magic_xmode(IP.rc.xmode)
502 IP.magic_xmode(IP_rc.xmode)
503 otrap.release_out()
503 otrap.release_out()
504
504
505 # activate logging if requested and not reloading a log
505 # activate logging if requested and not reloading a log
506 if IP.rc.logplay:
506 if IP_rc.logplay:
507 IP.magic_logstart(IP.rc.logplay + ' append')
507 IP.magic_logstart(IP_rc.logplay + ' append')
508 elif IP.rc.logfile:
508 elif IP_rc.logfile:
509 IP.magic_logstart(IP.rc.logfile)
509 IP.magic_logstart(IP_rc.logfile)
510 elif IP.rc.log:
510 elif IP_rc.log:
511 IP.magic_logstart()
511 IP.magic_logstart()
512
512
513 # find user editor so that it we don't have to look it up constantly
513 # find user editor so that it we don't have to look it up constantly
514 if IP.rc.editor.strip()=='0':
514 if IP_rc.editor.strip()=='0':
515 try:
515 try:
516 ed = os.environ['EDITOR']
516 ed = os.environ['EDITOR']
517 except KeyError:
517 except KeyError:
@@ -519,12 +519,16 object? -> Details about 'object'. ?object also works, ?? prints more.
519 ed = 'vi' # the only one guaranteed to be there!
519 ed = 'vi' # the only one guaranteed to be there!
520 else:
520 else:
521 ed = 'notepad' # same in Windows!
521 ed = 'notepad' # same in Windows!
522 IP.rc.editor = ed
522 IP_rc.editor = ed
523
524 # Keep track of whether this is an embedded instance or not (useful for
525 # post-mortems).
526 IP_rc.embedded = IP.embedded
523
527
524 # Recursive reload
528 # Recursive reload
525 try:
529 try:
526 from IPython import deep_reload
530 from IPython import deep_reload
527 if IP.rc.deep_reload:
531 if IP_rc.deep_reload:
528 __builtin__.reload = deep_reload.reload
532 __builtin__.reload = deep_reload.reload
529 else:
533 else:
530 __builtin__.dreload = deep_reload.reload
534 __builtin__.dreload = deep_reload.reload
@@ -538,25 +542,25 object? -> Details about 'object'. ?object also works, ?? prints more.
538 # defining things on the command line, and %who works as expected.
542 # defining things on the command line, and %who works as expected.
539
543
540 # DON'T do anything that affects the namespace beyond this point!
544 # DON'T do anything that affects the namespace beyond this point!
541 IP.internal_ns = __main__.__dict__.copy()
545 IP.internal_ns.update(__main__.__dict__)
542
546
543 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
547 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
544
548
545 # Now run through the different sections of the users's config
549 # Now run through the different sections of the users's config
546 if IP.rc.debug:
550 if IP_rc.debug:
547 print 'Trying to execute the following configuration structure:'
551 print 'Trying to execute the following configuration structure:'
548 print '(Things listed first are deeper in the inclusion tree and get'
552 print '(Things listed first are deeper in the inclusion tree and get'
549 print 'loaded first).\n'
553 print 'loaded first).\n'
550 pprint(IP.rc.__dict__)
554 pprint(IP_rc.__dict__)
551
555
552 for mod in IP.rc.import_mod:
556 for mod in IP_rc.import_mod:
553 try:
557 try:
554 exec 'import '+mod in IP.user_ns
558 exec 'import '+mod in IP.user_ns
555 except :
559 except :
556 IP.InteractiveTB()
560 IP.InteractiveTB()
557 import_fail_info(mod)
561 import_fail_info(mod)
558
562
559 for mod_fn in IP.rc.import_some:
563 for mod_fn in IP_rc.import_some:
560 if mod_fn == []: break
564 if mod_fn == []: break
561 mod,fn = mod_fn[0],','.join(mod_fn[1:])
565 mod,fn = mod_fn[0],','.join(mod_fn[1:])
562 try:
566 try:
@@ -565,14 +569,14 object? -> Details about 'object'. ?object also works, ?? prints more.
565 IP.InteractiveTB()
569 IP.InteractiveTB()
566 import_fail_info(mod,fn)
570 import_fail_info(mod,fn)
567
571
568 for mod in IP.rc.import_all:
572 for mod in IP_rc.import_all:
569 try:
573 try:
570 exec 'from '+mod+' import *' in IP.user_ns
574 exec 'from '+mod+' import *' in IP.user_ns
571 except :
575 except :
572 IP.InteractiveTB()
576 IP.InteractiveTB()
573 import_fail_info(mod)
577 import_fail_info(mod)
574
578
575 for code in IP.rc.execute:
579 for code in IP_rc.execute:
576 try:
580 try:
577 exec code in IP.user_ns
581 exec code in IP.user_ns
578 except:
582 except:
@@ -580,7 +584,7 object? -> Details about 'object'. ?object also works, ?? prints more.
580 warn('Failure executing code: ' + `code`)
584 warn('Failure executing code: ' + `code`)
581
585
582 # Execute the files the user wants in ipythonrc
586 # Execute the files the user wants in ipythonrc
583 for file in IP.rc.execfile:
587 for file in IP_rc.execfile:
584 try:
588 try:
585 file = filefind(file,sys.path+[IPython_dir])
589 file = filefind(file,sys.path+[IPython_dir])
586 except IOError:
590 except IOError:
@@ -589,12 +593,12 object? -> Details about 'object'. ?object also works, ?? prints more.
589 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
593 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
590
594
591 # Load user aliases
595 # Load user aliases
592 for alias in IP.rc.alias:
596 for alias in IP_rc.alias:
593 IP.magic_alias(alias)
597 IP.magic_alias(alias)
594
598
595 # release stdout and stderr and save config log into a global summary
599 # release stdout and stderr and save config log into a global summary
596 msg.config.release_all()
600 msg.config.release_all()
597 if IP.rc.messages:
601 if IP_rc.messages:
598 msg.summary += msg.config.summary_all()
602 msg.summary += msg.config.summary_all()
599
603
600 #------------------------------------------------------------------------
604 #------------------------------------------------------------------------
@@ -612,7 +616,7 object? -> Details about 'object'. ?object also works, ?? prints more.
612 if load_logplay:
616 if load_logplay:
613 print 'Replaying log...'
617 print 'Replaying log...'
614 try:
618 try:
615 if IP.rc.debug:
619 if IP_rc.debug:
616 logplay_quiet = 0
620 logplay_quiet = 0
617 else:
621 else:
618 logplay_quiet = 1
622 logplay_quiet = 1
@@ -621,7 +625,7 object? -> Details about 'object'. ?object also works, ?? prints more.
621 IP.safe_execfile(load_logplay,IP.user_ns,
625 IP.safe_execfile(load_logplay,IP.user_ns,
622 islog = 1, quiet = logplay_quiet)
626 islog = 1, quiet = logplay_quiet)
623 msg.logplay.release_all()
627 msg.logplay.release_all()
624 if IP.rc.messages:
628 if IP_rc.messages:
625 msg.summary += msg.logplay.summary_all()
629 msg.summary += msg.logplay.summary_all()
626 except:
630 except:
627 warn('Problems replaying logfile %s.' % load_logplay)
631 warn('Problems replaying logfile %s.' % load_logplay)
@@ -639,7 +643,7 object? -> Details about 'object'. ?object also works, ?? prints more.
639 # ipython prompt. This would also give them the benefit of ipython's
643 # ipython prompt. This would also give them the benefit of ipython's
640 # nice tracebacks.
644 # nice tracebacks.
641
645
642 if not embedded and IP.rc.args:
646 if not embedded and IP_rc.args:
643 name_save = IP.user_ns['__name__']
647 name_save = IP.user_ns['__name__']
644 IP.user_ns['__name__'] = '__main__'
648 IP.user_ns['__name__'] = '__main__'
645 try:
649 try:
@@ -655,40 +659,36 object? -> Details about 'object'. ?object also works, ?? prints more.
655 IP.user_ns['__name__'] = name_save
659 IP.user_ns['__name__'] = name_save
656
660
657 msg.user_exec.release_all()
661 msg.user_exec.release_all()
658 if IP.rc.messages:
662 if IP_rc.messages:
659 msg.summary += msg.user_exec.summary_all()
663 msg.summary += msg.user_exec.summary_all()
660
664
661 # since we can't specify a null string on the cmd line, 0 is the equivalent:
665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
662 if IP.rc.nosep:
666 if IP_rc.nosep:
663 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
664 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
665 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
666 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
667 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
668 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
669 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
670
674
671 # Determine how many lines at the bottom of the screen are needed for
675 # Determine how many lines at the bottom of the screen are needed for
672 # showing prompts, so we can know wheter long strings are to be printed or
676 # showing prompts, so we can know wheter long strings are to be printed or
673 # paged:
677 # paged:
674 num_lines_bot = IP.rc.separate_in.count('\n')+1
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
675 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
676 # Initialize cache, set in/out prompts and printing system
680 # Initialize cache, set in/out prompts and printing system
677 IP.outputcache = CachedOutput(IP.rc.cache_size,
681 IP.outputcache = CachedOutput(IP_rc.cache_size,
678 IP.rc.pprint,
682 IP_rc.pprint,
679 input_sep = IP.rc.separate_in,
683 input_sep = IP_rc.separate_in,
680 output_sep = IP.rc.separate_out,
684 output_sep = IP_rc.separate_out,
681 output_sep2 = IP.rc.separate_out2,
685 output_sep2 = IP_rc.separate_out2,
682 ps1 = IP.rc.prompt_in1,
686 ps1 = IP_rc.prompt_in1,
683 ps2 = IP.rc.prompt_in2,
687 ps2 = IP_rc.prompt_in2,
684 ps_out = IP.rc.prompt_out,
688 ps_out = IP_rc.prompt_out,
685 user_ns = IP.user_ns,
689 user_ns = IP.user_ns,
686 input_hist = IP.input_hist,
690 input_hist = IP.input_hist,
687 pad_left = IP.rc.prompts_pad_left)
691 pad_left = IP_rc.prompts_pad_left)
688
689 # Set user colors (don't do it in the constructor above so that it doesn't
690 # crash if colors option is invalid)
691 IP.magic_colors(IP.rc.colors)
692
692
693 # user may have over-ridden the default print hook:
693 # user may have over-ridden the default print hook:
694 try:
694 try:
@@ -697,7 +697,7 object? -> Details about 'object'. ?object also works, ?? prints more.
697 pass
697 pass
698
698
699 # Set calling of pdb on exceptions
699 # Set calling of pdb on exceptions
700 IP.InteractiveTB.call_pdb = IP.rc.pdb
700 IP.InteractiveTB.call_pdb = IP_rc.pdb
701
701
702 # I don't like assigning globally to sys, because it means when embedding
702 # I don't like assigning globally to sys, because it means when embedding
703 # instances, each embedded instance overrides the previous choice. But
703 # instances, each embedded instance overrides the previous choice. But
@@ -709,18 +709,25 object? -> Details about 'object'. ?object also works, ?? prints more.
709 IP.do_full_cache = IP.outputcache.do_full_cache
709 IP.do_full_cache = IP.outputcache.do_full_cache
710
710
711 # configure startup banner
711 # configure startup banner
712 if IP.rc.c: # regular python doesn't print the banner with -c
712 if IP_rc.c: # regular python doesn't print the banner with -c
713 IP.rc.banner = 0
713 IP_rc.banner = 0
714 if IP.rc.banner:
714 if IP_rc.banner:
715 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
715 BANN_P = IP.BANNER_PARTS
716 else:
716 else:
717 IP.BANNER = ''
717 BANN_P = []
718
718
719 if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n'
719 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
720
720
721 # add message log (possibly empty)
721 # add message log (possibly empty)
722 IP.BANNER += msg.summary
722 if msg.summary: BANN_P.append(msg.summary)
723 # Final banner is a string
724 IP.BANNER = '\n'.join(BANN_P)
725
726 # Assign the IP_rc object as an attribute of IP
727 IP.rc = IP_rc
723
728
729 # Finalize the IPython instance. This assumes the rc structure is fully
730 # in place.
724 IP.post_config_initialization()
731 IP.post_config_initialization()
725
732
726 return IP
733 return IP
@@ -21,7 +21,6 import re
21 import pprint
21 import pprint
22 import exceptions
22 import exceptions
23 import pdb
23 import pdb
24 import IPython.genutils as genutils
25