##// END OF EJS Templates
Wildcard system cleanup, ipmaker speedups, bugfix in globals handling...
fperez -
Show More
@@ -1,7 +1,7 b''
1 1 # -*- coding: utf-8 -*-
2 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 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
@@ -296,10 +296,9 b' license. To use profiling, please install"python2.3-profiler" from non-free.""")'
296 296 Struct with the options as keys and the stripped argument string still
297 297 as a string.
298 298
299 arg_str is quoted as a true sys.argv vector by calling on the fly a
300 python process in a subshell. This allows us to easily expand
301 variables, glob files, quote arguments, etc, with all the power and
302 correctness of the underlying system shell.
299 arg_str is quoted as a true sys.argv vector by using shlex.split.
300 This allows us to easily expand variables, glob files, quote
301 arguments, etc.
303 302
304 303 Options:
305 304 -mode: default 'string'. If given as 'list', the argument string is
@@ -665,55 +664,109 b' Currently the magic system has the following functions:\\n"""'
665 664 def magic_psearch(self, parameter_s=''):
666 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 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*'.
672
673 PATTERN
674
675 where PATTERN is a string containing * as a wildcard similar to its
676 use in a shell. The pattern is matched in all namespaces on the
677 search path. By default objects starting with a single _ are not
678 matched, many IPython generated objects have a single underscore. The
679 default is case insensitive matching. Matching is also done on the
680 attributes of objects and not only on the objects in a module.
681
682 [OBJECT TYPE]
683 Is the name of a python type from the types module. The name is given
684 in lowercase without the ending type, ex. StringType is written
685 string. By adding a type here only objects matching the given type are
686 matched. Using all here makes the pattern match all types (this is the
687 default).
688
689 [-NAMESPACE]* [+NAMESPACE]*
690 The possible namespaces are builtin, user, internal, alias. Where
691 builtin and user are default. Builtin contains the python module
692 builtin, user contains all imported namespaces, alias only contain the
693 shell aliases and no python objects, internal contains objects used by
694 IPython. The namespaces on the search path are removed by -namespace
695 and added by +namespace.
696
697 [-a] makes the pattern match even objects with a single underscore.
698 [-c] makes the pattern case sensitive.
670 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
671 rest of the command line must be unchanged (options come first), so
672 for example the following forms are equivalent
673
674 %psearch -i a* function
675 -i a* function?
676 ?-i a* function
677
678 Arguments:
679
680 PATTERN
681
682 where PATTERN is a string containing * as a wildcard similar to its
683 use in a shell. The pattern is matched in all namespaces on the
684 search path. By default objects starting with a single _ are not
685 matched, many IPython generated objects have a single
686 underscore. The default is case insensitive matching. Matching is
687 also done on the attributes of objects and not only on the objects
688 in a module.
689
690 [OBJECT TYPE]
691
692 Is the name of a python type from the types module. The name is
693 given in lowercase without the ending type, ex. StringType is
694 written string. By adding a type here only objects matching the
695 given type are matched. Using all here makes the pattern match all
696 types (this is the default).
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 725 Examples:
701 726
702 %psearch a* list objects beginning with an a
703 %psearch a* function list all functions beginning with an a
704 %psearch re.e* list objects beginning with an e in module re
705 %psearch r*.e* list objects that starts with e in modules starting in r
706 %psearch r*.* string list all strings in modules beginning with r
727 %psearch a* -> objects beginning with an a
728 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
729 %psearch a* function -> all functions beginning with an a
730 %psearch re.e* -> objects beginning with an e in module re
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 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 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 771 def magic_who_ls(self, parameter_s=''):
719 772 """Return a sorted list of all interactive variables.
@@ -6,7 +6,7 b' Uses syntax highlighting for presenting the various information elements.'
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 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 b' __license__ = Release.license'
23 23 __all__ = ['Inspector','InspectColors']
24 24
25 25 # stdlib modules
26 import __builtin__
26 27 import inspect,linecache,types,StringIO,string
27 28
28 29 # IPython's own
29 30 from IPython import PyColorize
30 31 from IPython.Itpl import itpl
31 from IPython.wildcard import choose_namespaces,list_namespace
32 from IPython.genutils import page,indent,Term
32 from IPython.wildcard import list_namespace
33 from IPython.genutils import page,indent,Term,mkdict
33 34 from IPython.ColorANSI import *
34 35
35 36 #****************************************************************************
@@ -398,44 +399,56 b' class Inspector:'
398 399 page(output)
399 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 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 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
411 the namespaces.
420 - show_all(False): show all names, including those starting with
421 underscores.
412 422 """
413 option_list = ['-c','-a']
414 cmds = oname.split()
415 filter = ''
423 # defaults
416 424 type_pattern = 'all'
417 options = [x for x in cmds if x in option_list]
418 ignorecase = '-c' not in options
419 showhidden = '-a' in options
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 '-+']
425 filter = ''
426
427 cmds = pattern.split()
422 428 len_cmds = len(cmds)
423 429 if len_cmds == 1:
424 filter = cmds[0].strip()
430 # Only filter pattern given
431 filter = cmds[0]
425 432 elif len_cmds == 2:
433 # Both filter and type specified
426 434 filter,type_pattern = cmds
427 elif len_cmds>2:
428 # assume we want to choose name spaces. Rather poor design forces
429 #the use of a typepattern in order to choose name spaces
430 cmds = cmds[:2]
435 else:
436 raise ValueError('invalid argument string for psearch: <%s>' %
437 pattern)
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 446 search_result = []
435 for ns in do_list:
447 for ns_name in ns_search:
448 ns = ns_table[ns_name]
436 449 tmp_res = list(list_namespace(ns,type_pattern,filter,
437 ignorecase=ignorecase,
438 showhidden=showhidden))
450 ignore_case=ignore_case,
451 show_all=show_all))
439 452 search_result.extend(tmp_res)
440 453 search_result.sort()
441 454
@@ -4,7 +4,7 b''
4 4 All the matplotlib support code was co-developed with John Hunter,
5 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 10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
@@ -132,9 +132,6 b' class IPShellEmbed:'
132 132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 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 135 # copy our own displayhook also
139 136 self.sys_displayhook_embed = sys.displayhook
140 137 # and leave the system's display hook clean
@@ -1,5 +1,5 b''
1 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 b' separate_out2 0'
262 262 # Simply removes all input/output separators, overriding the choices above.
263 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 273 # xmode - Exception reporting mode.
266 274
267 275 # Valid modes: Plain, Context and Verbose.
@@ -6,7 +6,7 b' Requires Python 2.1 or newer.'
6 6
7 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 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):'
508 508
509 509 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
510 510 user_ns = None,user_global_ns=None,banner2='',
511 custom_exceptions=((),None)):
511 custom_exceptions=((),None),embedded=False):
512 512
513 513 # Put a reference to self in builtins so that any form of embedded or
514 514 # imported code can test for being inside IPython.
@@ -532,6 +532,10 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):'
532 532 __builtin__.exit += _exit
533 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 539 # compiler command
536 540 self.compile = CommandCompiler()
537 541
@@ -584,9 +588,29 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):'
584 588 if user_global_ns is None:
585 589 user_global_ns = {}
586 590
587 # assign namespaces
591 # Assign namespaces
592 # This is the namespace where all normal user variables live
588 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 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 615 # The user namespace MUST have a pointer to the shell itself.
592 616 self.user_ns[name] = self
@@ -619,11 +643,6 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):'
619 643 # dict of output history
620 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 646 # dict of things NOT to alias (keywords, builtins and some special magics)
628 647 no_alias = {}
629 648 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
@@ -956,7 +975,15 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):'
956 975
957 976 This is called after the configuration files have been processed to
958 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 987 # dynamic data that survives through sessions
961 988 # XXX make the filename a config option?
962 989 persist_base = 'persist'
@@ -1629,7 +1656,16 b' want to merge them back into the new files.""" % locals()'
1629 1656 outflag = 1 # happens in more places, so it's easier as default
1630 1657 try:
1631 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 1669 finally:
1634 1670 # Reset our crash handler in place
1635 1671 sys.excepthook = old_excepthook
@@ -6,7 +6,7 b' Requires Python 2.1 or better.'
6 6
7 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 12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
@@ -82,7 +82,7 b' def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,'
82 82 # __IP.name. We set its name via the first parameter passed to
83 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 87 # Put 'help' in the user namespace
88 88 from site import _Helper
@@ -155,7 +155,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
155 155 'readline! readline_merge_completions! '
156 156 'readline_omit__names! '
157 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 159 'magic_docstrings system_verbose! '
160 160 'multi_line_specials!')
161 161
@@ -218,6 +218,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
218 218 upgrade = 0,
219 219 Version = 0,
220 220 xmode = 'Verbose',
221 wildcards_case_sensitive = 1,
221 222 magic_docstrings = 0, # undocumented, for doc generation
222 223 )
223 224
@@ -281,7 +282,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
281 282 except:
282 283 print cmd_line_usage
283 284 warn('\nError in Arguments: ' + `sys.exc_value`)
284 sys.exit()
285 sys.exit(1)
285 286
286 287 # convert the options dict to a struct for much lighter syntax later
287 288 opts = Struct(getopt.optionValues)
@@ -445,73 +446,72 b" object? -> Details about 'object'. ?object also works, ?? prints more."
445 446 # Execute user config
446 447
447 448 # first, create a valid config structure with the right precedence order:
448 # defaults < rcfile < command line
449 IP.rc = rc_def.copy()
450 IP.rc.update(opts_def)
449 # defaults < rcfile < command line. We make it as a local (IP_rc) to
450 # avoid a zillion attribute accesses. Right before returning, this will
451 # be set as IP.rc.
452 IP_rc = rc_def.copy()
453 IP_rc.update(opts_def)
451 454 if rcfiledata:
452 455 # now we can update
453 IP.rc.update(rcfiledata)
454 IP.rc.update(opts)
455 IP.rc.update(rc_override)
456 IP_rc.update(rcfiledata)
457 IP_rc.update(opts)
458 IP_rc.update(rc_override)
456 459
457 460 # Store the original cmd line for reference:
458 IP.rc.opts = opts
459 IP.rc.args = args
461 IP_rc.opts = opts
462 IP_rc.args = args
460 463
461 464 # create a *runtime* Struct like rc for holding parameters which may be
462 465 # created and/or modified by runtime user extensions.
463 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 469 # opts* shouldn't be used anymore.
467 470
468 471 # add personal .ipython dir to sys.path so that users can put things in
469 472 # there for customization
470 sys.path.append(IP.rc.ipythondir)
473 sys.path.append(IP_rc.ipythondir)
471 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 477 # tweaks. Basically options which affect other options. I guess this
475 478 # should just be written so that options are fully orthogonal and we
476 479 # wouldn't worry about this stuff!
477 480
478 if IP.rc.classic:
479 IP.rc.quick = 1
480 IP.rc.cache_size = 0
481 IP.rc.pprint = 0
482 IP.rc.prompt_in1 = '>>> '
483 IP.rc.prompt_in2 = '... '
484 IP.rc.prompt_out = ''
485 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
486 IP.rc.colors = 'NoColor'
487 IP.rc.xmode = 'Plain'
481 if IP_rc.classic:
482 IP_rc.quick = 1
483 IP_rc.cache_size = 0
484 IP_rc.pprint = 0
485 IP_rc.prompt_in1 = '>>> '
486 IP_rc.prompt_in2 = '... '
487 IP_rc.prompt_out = ''
488 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
489 IP_rc.colors = 'NoColor'
490 IP_rc.xmode = 'Plain'
488 491
489 492 # configure readline
490 493 # Define the history file for saving commands in between sessions
491 if IP.rc.profile:
492 histfname = 'history-%s' % IP.rc.profile
494 if IP_rc.profile:
495 histfname = 'history-%s' % IP_rc.profile
493 496 else:
494 497 histfname = 'history'
495 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 500 # update exception handlers with rc file status
501 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 503 otrap.release_out()
504 504
505 505 # activate logging if requested and not reloading a log
506 if IP.rc.logplay:
507 IP.magic_logstart(IP.rc.logplay + ' append')
508 elif IP.rc.logfile:
509 IP.magic_logstart(IP.rc.logfile)
510 elif IP.rc.log:
506 if IP_rc.logplay:
507 IP.magic_logstart(IP_rc.logplay + ' append')
508 elif IP_rc.logfile:
509 IP.magic_logstart(IP_rc.logfile)
510 elif IP_rc.log:
511 511 IP.magic_logstart()
512 512
513 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 515 try:
516 516 ed = os.environ['EDITOR']
517 517 except KeyError:
@@ -519,12 +519,16 b" object? -> Details about 'object'. ?object also works, ?? prints more."
519 519 ed = 'vi' # the only one guaranteed to be there!
520 520 else:
521 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 528 # Recursive reload
525 529 try:
526 530 from IPython import deep_reload
527 if IP.rc.deep_reload:
531 if IP_rc.deep_reload:
528 532 __builtin__.reload = deep_reload.reload
529 533 else:
530 534 __builtin__.dreload = deep_reload.reload
@@ -538,25 +542,25 b" object? -> Details about 'object'. ?object also works, ?? prints more."
538 542 # defining things on the command line, and %who works as expected.
539 543
540 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 547 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
544 548
545 549 # Now run through the different sections of the users's config
546 if IP.rc.debug:
550 if IP_rc.debug:
547 551 print 'Trying to execute the following configuration structure:'
548 552 print '(Things listed first are deeper in the inclusion tree and get'
549 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 557 try:
554 558 exec 'import '+mod in IP.user_ns
555 559 except :
556 560 IP.InteractiveTB()
557 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 564 if mod_fn == []: break
561 565 mod,fn = mod_fn[0],','.join(mod_fn[1:])
562 566 try:
@@ -565,14 +569,14 b" object? -> Details about 'object'. ?object also works, ?? prints more."
565 569 IP.InteractiveTB()
566 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 573 try:
570 574 exec 'from '+mod+' import *' in IP.user_ns
571 575 except :
572 576 IP.InteractiveTB()
573 577 import_fail_info(mod)
574 578
575 for code in IP.rc.execute:
579 for code in IP_rc.execute:
576 580 try:
577 581 exec code in IP.user_ns
578 582 except:
@@ -580,7 +584,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
580 584 warn('Failure executing code: ' + `code`)
581 585
582 586 # Execute the files the user wants in ipythonrc
583 for file in IP.rc.execfile:
587 for file in IP_rc.execfile:
584 588 try:
585 589 file = filefind(file,sys.path+[IPython_dir])
586 590 except IOError:
@@ -589,12 +593,12 b" object? -> Details about 'object'. ?object also works, ?? prints more."
589 593 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
590 594
591 595 # Load user aliases
592 for alias in IP.rc.alias:
596 for alias in IP_rc.alias:
593 597 IP.magic_alias(alias)
594 598
595 599 # release stdout and stderr and save config log into a global summary
596 600 msg.config.release_all()
597 if IP.rc.messages:
601 if IP_rc.messages:
598 602 msg.summary += msg.config.summary_all()
599 603
600 604 #------------------------------------------------------------------------
@@ -612,7 +616,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
612 616 if load_logplay:
613 617 print 'Replaying log...'
614 618 try:
615 if IP.rc.debug:
619 if IP_rc.debug:
616 620 logplay_quiet = 0
617 621 else:
618 622 logplay_quiet = 1
@@ -621,7 +625,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
621 625 IP.safe_execfile(load_logplay,IP.user_ns,
622 626 islog = 1, quiet = logplay_quiet)
623 627 msg.logplay.release_all()
624 if IP.rc.messages:
628 if IP_rc.messages:
625 629 msg.summary += msg.logplay.summary_all()
626 630 except:
627 631 warn('Problems replaying logfile %s.' % load_logplay)
@@ -639,7 +643,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
639 643 # ipython prompt. This would also give them the benefit of ipython's
640 644 # nice tracebacks.
641 645
642 if not embedded and IP.rc.args:
646 if not embedded and IP_rc.args:
643 647 name_save = IP.user_ns['__name__']
644 648 IP.user_ns['__name__'] = '__main__'
645 649 try:
@@ -655,40 +659,36 b" object? -> Details about 'object'. ?object also works, ?? prints more."
655 659 IP.user_ns['__name__'] = name_save
656 660
657 661 msg.user_exec.release_all()
658 if IP.rc.messages:
662 if IP_rc.messages:
659 663 msg.summary += msg.user_exec.summary_all()
660 664
661 665 # since we can't specify a null string on the cmd line, 0 is the equivalent:
662 if IP.rc.nosep:
663 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
664 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
665 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
666 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
667 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
668 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
669 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
666 if IP_rc.nosep:
667 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
668 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
669 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
670 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
671 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
672 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
673 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
670 674
671 675 # Determine how many lines at the bottom of the screen are needed for
672 676 # showing prompts, so we can know wheter long strings are to be printed or
673 677 # paged:
674 num_lines_bot = IP.rc.separate_in.count('\n')+1
675 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
678 num_lines_bot = IP_rc.separate_in.count('\n')+1
679 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
676 680 # Initialize cache, set in/out prompts and printing system
677 IP.outputcache = CachedOutput(IP.rc.cache_size,
678 IP.rc.pprint,
679 input_sep = IP.rc.separate_in,
680 output_sep = IP.rc.separate_out,
681 output_sep2 = IP.rc.separate_out2,
682 ps1 = IP.rc.prompt_in1,
683 ps2 = IP.rc.prompt_in2,
684 ps_out = IP.rc.prompt_out,
681 IP.outputcache = CachedOutput(IP_rc.cache_size,
682 IP_rc.pprint,
683 input_sep = IP_rc.separate_in,
684 output_sep = IP_rc.separate_out,
685 output_sep2 = IP_rc.separate_out2,
686 ps1 = IP_rc.prompt_in1,
687 ps2 = IP_rc.prompt_in2,
688 ps_out = IP_rc.prompt_out,
685 689 user_ns = IP.user_ns,
686 690 input_hist = IP.input_hist,
687 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)
691 pad_left = IP_rc.prompts_pad_left)
692 692
693 693 # user may have over-ridden the default print hook:
694 694 try:
@@ -697,7 +697,7 b" object? -> Details about 'object'. ?object also works, ?? prints more."
697 697 pass
698 698
699 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 702 # I don't like assigning globally to sys, because it means when embedding
703 703 # instances, each embedded instance overrides the previous choice. But
@@ -709,18 +709,25 b" object? -> Details about 'object'. ?object also works, ?? prints more."
709 709 IP.do_full_cache = IP.outputcache.do_full_cache
710 710
711 711 # configure startup banner
712 if IP.rc.c: # regular python doesn't print the banner with -c
713 IP.rc.banner = 0
714 if IP.rc.banner:
715 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
712 if IP_rc.c: # regular python doesn't print the banner with -c
713 IP_rc.banner = 0
714 if IP_rc.banner:
715 BANN_P = IP.BANNER_PARTS
716 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 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 731 IP.post_config_initialization()
725 732
726 733 return IP
@@ -21,7 +21,6 b' import re'
21 21 import pprint
22 22 import exceptions
23 23 import pdb
24 import IPython.genutils as genutils
25 24
26 25 def create_typestr2type_dicts(dont_include_in_type2type2str=["lambda"]):
27 26 """Return dictionaries mapping lower case typename to type objects, from
@@ -59,21 +58,21 b' def is_type(obj,typestr_or_type):'
59 58 else:
60 59 return False
61 60
62 def show_hidden(str,showhidden=False):
63 """Return true for strings starting with single _ if showhidden is true."""
64 return showhidden or str.startswith("__") or not str.startswith("_")
61 def show_hidden(str,show_all=False):
62 """Return true for strings starting with single _ if show_all is true."""
63 return show_all or str.startswith("__") or not str.startswith("_")
65 64
66 65
67 66 class NameSpace(object):
68 67 """NameSpace holds the dictionary for a namespace and implements filtering
69 68 on name and types"""
70 def __init__(self,obj,namepattern="*",typepattern="all",ignorecase=True,
71 showhidden=True):
72 self.showhidden = showhidden #Hide names beginning with single _
69 def __init__(self,obj,name_pattern="*",type_pattern="all",ignore_case=True,
70 show_all=True):
71 self.show_all = show_all #Hide names beginning with single _
73 72 self.object = obj
74 self.namepattern = namepattern
75 self.typepattern = typepattern
76 self.ignorecase = ignorecase
73 self.name_pattern = name_pattern
74 self.type_pattern = type_pattern
75 self.ignore_case = ignore_case
77 76
78 77 # We should only match EXACT dicts here, so DON'T use isinstance()
79 78 if type(obj) == types.DictType:
@@ -84,7 +83,7 b' class NameSpace(object):'
84 83
85 84 def get_ns(self):
86 85 """Return name space dictionary with objects matching type and name patterns."""
87 return self.filter(self.namepattern,self.typepattern)
86 return self.filter(self.name_pattern,self.type_pattern)
88 87 ns=property(get_ns)
89 88
90 89 def get_ns_names(self):
@@ -93,64 +92,47 b' class NameSpace(object):'
93 92 ns_names=property(get_ns_names,doc="List of objects in name space that "
94 93 "match the type and name patterns.")
95 94
96 def filter(self,namepattern,typepattern):
95 def filter(self,name_pattern,type_pattern):
97 96 """Return dictionary of filtered namespace."""
98 def glob_filter(lista,namepattern,hidehidden,ignorecase):
97 def glob_filter(lista,name_pattern,hidehidden,ignore_case):
99 98 """Return list of elements in lista that match pattern."""
100 pattern=namepattern.replace("*",".*")
101 if ignorecase:
99 pattern=name_pattern.replace("*",".*")
100 if ignore_case:
102 101 reg=re.compile(pattern+"$",re.I)
103 102 else:
104 103 reg=re.compile(pattern+"$")
105 104 result=[x for x in lista if reg.match(x) and show_hidden(x,hidehidden)]
106 105 return result
107 106 ns=self._ns
108 #Filter namespace by the namepattern
109 all=[(x,ns[x]) for x in glob_filter(ns.keys(),namepattern,
110 self.showhidden,self.ignorecase)]
111 #Filter namespace by typepattern
112 all=[(key,obj) for key,obj in all if is_type(obj,typepattern)]
107 #Filter namespace by the name_pattern
108 all=[(x,ns[x]) for x in glob_filter(ns.keys(),name_pattern,
109 self.show_all,self.ignore_case)]
110 #Filter namespace by type_pattern
111 all=[(key,obj) for key,obj in all if is_type(obj,type_pattern)]
113 112 all=dict(all)
114 113 return all
115 114
116 115 #TODO: Implement dictionary like access to filtered name space?
117 116
118 def list_namespace(namespace,typepattern,filter,ignorecase=False,showhidden=False):
119 """Return dictionary of all objects in namespace that matches typepattern
117 def list_namespace(namespace,type_pattern,filter,ignore_case=False,show_all=False):
118 """Return dictionary of all objects in namespace that matches type_pattern
120 119 and filter."""
121 patternlist=filter.split(".")
122 if len(patternlist)==1:
123 ns=NameSpace(namespace,namepattern=patternlist[0],typepattern=typepattern,
124 ignorecase=ignorecase,showhidden=showhidden)
120 pattern_list=filter.split(".")
121 if len(pattern_list)==1:
122 ns=NameSpace(namespace,name_pattern=pattern_list[0],type_pattern=type_pattern,
123 ignore_case=ignore_case,show_all=show_all)
125 124 return ns.ns
126 if len(patternlist)>1:
127 #This is where we can change if all objects should be searched or only moduleas
128 #Just change the typepattern to module to search only modules
129 ns=NameSpace(namespace,
130 namepattern=patternlist[0],
131 typepattern="all",ignorecase=ignorecase,showhidden=showhidden)
125 else:
126 # This is where we can change if all objects should be searched or
127 # only modules. Just change the type_pattern to module to search only
128 # modules
129 ns=NameSpace(namespace,name_pattern=pattern_list[0],type_pattern="all",
130 ignore_case=ignore_case,show_all=show_all)
132 131 res={}
133 132 nsdict=ns.ns
134 133 for name,obj in nsdict.iteritems():
135 ns=list_namespace(obj,typepattern,".".join(patternlist[1:]),
136 ignorecase=ignorecase,showhidden=showhidden)
134 ns=list_namespace(obj,type_pattern,".".join(pattern_list[1:]),
135 ignore_case=ignore_case,show_all=show_all)
137 136 for inner_name,inner_obj in ns.iteritems():
138 137 res["%s.%s"%(name,inner_name)]=inner_obj
139 138 return res
140
141 def choose_namespaces(shell,cmds):
142 """Returns a list of namespaces modified by arguments."""
143 nslist=genutils.mkdict(user=shell.user_ns,internal=shell.internal_ns,
144 builtin=__builtin__.__dict__,alias=shell.alias_table)
145 default_list=["user","builtin"] # Should this list be a user option??
146 for cmd in cmds:
147 if cmd[0]=="-": #remove from defaultlist
148 if cmd[1:] in default_list:
149 default_list.remove(cmd[1:])
150 elif cmd[0]=="+":
151 if cmd[1:] not in default_list and cmd[1:]in nslist:
152 default_list.append(cmd[1:])
153 else:
154 if cmd in nslist:
155 default_list.append(cmd[1:])
156 return [nslist[x] for x in default_list]
@@ -1,3 +1,18 b''
1 2005-11-15 <Fernando.Perez@colorado.edu>
2
3 * IPython/ipmaker.py (make_IPython): cleanups which should improve
4 startup time.
5
6 * IPython/iplib.py (runcode): my globals 'fix' for embedded
7 instances had introduced a bug with globals in normal code. Now
8 it's working in all cases.
9
10 * IPython/Magic.py (magic_psearch): Finish wildcard cleanup and
11 API changes. A new ipytonrc option, 'wildcards_case_sensitive'
12 has been introduced to set the default case sensitivity of the
13 searches. Users can still select either mode at runtime on a
14 per-search basis.
15
1 16 2005-11-13 <Fernando.Perez@colorado.edu>
2 17
3 18 * IPython/wildcard.py (NameSpace.__init__): fix resolution of
General Comments 0
You need to be logged in to leave comments. Login now