Пример #1
0
def rdir(obj=None, regex='.*', inv=False, ret=True):
    """A wrapper around the dir python function with additional filtering options.
    Selects those names from a dir resposne which match the second regex argument.
     
    Names returned by the builtin function dir() are filtered
    to include only those names matched by the specified regex, or
    not containing the regex incase the inv = True parameter is passed along.

    The function returns a list by default, just pretty prints the filtered names.
    The result can be returned explicity as a list by setting ret = True.
    """
    if obj:
        name_list = __builtin__.dir(obj)
    else:
        name_list = list(inspect.currentframe().f_back.f_locals.keys())
    if inv == False:
        fil = ifilter
    else:
        fil = ifilterfalse
    if not isinstance(regex, basestring):
        regex = "|".join(regex)

    name_list = list(fil(re.compile(regex).search, name_list))
    if ret == False:
        pprint(name_list)
    else:
        return name_list
Пример #2
0
def pdir(obj=None, help=False, spl=False, inner=False):
    '''
    A wrapper around the dir python function, that lets you do
        - Pretty printing
        - Gives you quick help showing a sneak into the docstrings for each method
        - Removes special and inner methods in the listing unless specified

    - To see a bit of help along with each of the attribute names just pass, help=True
    as an extra parameter

    - Special Methods, Inner methods are disabled by default can be enabled by setting
    spl, inner parameters as True.
    Special methods are those which have 2 leading underscores and 2 trailing ones.
    Inner Methods are those which have one leading underscore.
    '''
    if spl == False:
        if inner == False:
            sanitized_names = rdir(obj,regex='^_',inv=True)
        else:
            sanitized_names = rdir(obj,regex='^__',inv=True)
    else:
        if inner == False:
            # TODO: Unchecked Case (Though its not very useful)
            # sanitized_names = rdir(obj,regex='^[^_]')
            pass
        else:
            # Then things are as good filtering everything.
            # Smart people should use dir directly for such a case. 
            sanitized_names = __builtin__.dir(obj)
        
    if help == False:
        return pprint(sanitized_names)
    else:
        return _withhelp(obj,sanitized_names)
Пример #3
0
def get_autocomps_names(globals, locals, objname):
    """
    Engine task to get autocomplete names for the objname given.
    """
    import __builtin__
        
    #No address, a top level object
    if objname =='':
        #get the names from the locals and globals
        names = locals.keys()       
        for name in globals.keys():
            #only add global name if not already in the locals
            if name not in names:
                names.append(name)

        #get the builtins
        try:
            builtinlist = eval("__builtins__.dir(__builtins__)",globals, locals)
            for name in builtinlist:
                if name not in names:
                    names.append(name)
        except:
            pass

    #Need to get object then dir listing 
    else:
        #if address contains a call or index DO NOT EVALUATE!
        if objname.count(')') >0:
            names = []
        elif objname.count(']') >0:    
            names = []
        else:
            try:
                obj = eval(objname, globals, locals)
                names = __builtin__.dir( obj )
            except:
                names = []      

    #get type strings and build full address and make item = (name,type) tuple
    items = []
    for name in names:
        try:
            #get the object
            if objname not in ['',u'']:
                oname = objname+'.'+name
            else:
                oname = name
            obj = eval(oname, globals, locals)

            #get type_string
            t = type(obj)
            type_string = t.__module__ + '.' + t.__name__
        except:
            type_string = 'UNKNOWN'
            
        items.append( (name, type_string) )

    return items
Пример #4
0
def methodname(obj): #{{{
    o = None
    mt = methodtype(obj)
    if mt == METHODTYPE_CLASS:
        o = obj.im_class
    elif mt == METHODTYPE_INSTANCE:
        o = obj.im_self
    else:
        return
    for i in _ab.dir(o):
        if _ab.getattr(o, i) == obj:
            return i
Пример #5
0
        newy = newy[sel2]
        goodx = goodx[sel2]
        goody = goody[sel2]
        diffx = diffx[sel2]
        diffy = diffy[sel2]

        try:
            print "Saving to ", os.path.dirname(fname)+'.mat'
            output_dict = {}
            for var in ('xl', 'yl', 'xr', 'yr', 'varxl', 'varxr', 'newx', 'newy',
                        'diffx', 'diffy',
                        'framesetnum', 'tpmins', 'tpmaxes', 'imgname', 
                        'DQ_varbig_x','DQ_varbig_y', 'DQ_varbig_t',
                        'DQ_nomatch_x', 'DQ_nomatch_y', 'DQ_nomatch_t',
                        'DQ_toodim_x', 'DQ_toodim_y', 'DQ_toodim_t'):
                if var in dir():
                    exec 'output_dict["%s"] = %s' % (var, var)      
            
            if opts.frame_map:
                for var in ('xl_fids', 'yl_fids', 'xr_fids', 'yr_fids', 
                            'xl_exp', 'yl_exp', 'xr_exp', 'yr_exp',
                            'framesetnum_fids', 'framesetnum_exp'):
                    if var in dir():
                        exec 'output_dict["%s"] = %s' % (var, var)
            output_dict['framebyframe'] = opts.framewise
            output_dict['mapname'] = opts.map
            output_dict['mapname2'] = opts.map2
            
            io.savemat(opts.output or os.path.dirname(fname) + '.mat', output_dict)
        except IOError:
            print "Couldn't save a .mat file.  Probably a filesystem issue"
Пример #6
0
def isGoodGdb():
    #return gdb.VERSION.startswith("6.8.50.2009") \
    #   and gdb.VERSION != "6.8.50.20090630-cvs"
    return 'parse_and_eval' in __builtin__.dir(gdb)
Пример #7
0
def listOfLocals(varList):
    try:
        frame = gdb.selected_frame()
        #warn("FRAME %s: " % frame)
    except RuntimeError:
        warn("FRAME NOT ACCESSIBLE")
        return []

    # gdb-6.8-symbianelf fails here
    hasBlock = 'block' in __builtin__.dir(frame)

    items = []
    if hasBlock and isGoodGdb():
        #warn("IS GOOD: %s " % varList)
        try:
            block = frame.block()
            #warn("BLOCK: %s " % block)
        except:
            warn("BLOCK NOT ACCESSIBLE")
            return items

        while True:
            if block is None:
                warn("UNEXPECTED 'None' BLOCK")
                break
            for symbol in block:
                name = symbol.print_name

                if name == "__in_chrg":
                    continue

                # "NotImplementedError: Symbol type not yet supported in
                # Python scripts."
                #warn("SYMBOL %s: " % symbol.value)
                #warn("SYMBOL %s  (%s): " % (symbol, name))
                item = Item(0, "local", name, name)
                try:
                    item.value = frame.read_var(name)  # this is a gdb value
                except RuntimeError:
                    # happens for  void foo() { std::string s; std::wstring w; }
                    #warn("  FRAME READ VAR ERROR: %s (%s): " % (symbol, name))
                    continue
                #warn("ITEM %s: " % item.value)
                items.append(item)
            # The outermost block in a function has the function member
            # FIXME: check whether this is guaranteed.
            if not block.function is None:
                break

            block = block.superblock
    else:
        # Assuming gdb 7.0 release or 6.8-symbianelf.
        filename, file = createTempFile()
        #warn("VARLIST: %s " % varList)
        #warn("FILENAME: %s " % filename)
        gdb.execute("set logging off")
        gdb.execute("set logging redirect off")
        gdb.execute("set logging file %s" % filename)
        gdb.execute("set logging redirect on")
        gdb.execute("set logging on")
        try:
            gdb.execute("info args")
            # We cannot use "info locals" as at least 6.8-symbianelf
            # aborts as soon as we hit unreadable memory.
            # gdb.execute("interpreter mi '-stack-list-locals 0'")
            # results in &"Recursive internal problem.\n", so we have
            # the frontend pass us the list of locals.

            # There are two cases, either varList is empty, so we have
            # to fetch the list here, or it is not empty with the
            # first entry being a dummy.
            if len(varList) == 0:
                gdb.execute("info locals")
            else:
                varList = varList[1:]
        except:
            pass
        gdb.execute("set logging off")
        gdb.execute("set logging redirect off")

        try:
            temp = open(filename, "r")
            for line in temp:
                if len(line) == 0 or line.startswith(" "):
                    continue
                # The function parameters
                pos = line.find(" = ")
                if pos < 0:
                    continue
                varList.append(line[0:pos])
            temp.close()
        except:
            pass
        removeTempFile(filename, file)
        #warn("VARLIST: %s " % varList)
        for name in varList:
            #warn("NAME %s " % name)
            item = Item(0, "local", name, name)
            try:
                item.value = frame.read_var(name)  # this is a gdb value
            except RuntimeError:
                pass
                #continue
            except:
                # Something breaking the list, like intermediate gdb warnings
                # like 'Warning: can't find linker symbol for virtual table for
                # `std::less<char const*>' value\n\nwarning:  found
                # `myns::QHashData::shared_null' instead [...]
                # that break subsequent parsing. Chicken out and take the
                # next "usable" line.
                continue
            items.append(item)

    return items