Thursday, March 29, 2012

New python module search function

New search function on module library...abstracted a bit more here, recommend using with caution with high recursion counts...unfortunately through runtime exception with open recursion (at tree depth) for gi.repository libraries here, so implemented a counter to avoid run time error. 

To implement function typically call at terminal you'd want to set modulepkg to instance object of the loaded module...e.g.,
>>a = gi.repository
if the searchword module file is saved as file searchword.py
>>searchword.searchword(a, 'Gtk', 3)

Searches the repository libraries at recursion depth of three levels at each top level directory paths.
 

def findresult(a, word):
    results = []
    for item in a:
       if word in item:
           results.append(item)
    return results      
       

def searchword(modulepkg, word, recursioncnt):


    resultsa = []
   
    a = dir(modulepkg)
   
    asearch = findresult(a, word)
    if recursioncnt > 0:
        for item2 in a:
            exception1 = False
            exception2 = False

            try:
                modulename = eval('modulepkg.__name__')
                #print(modulename)
                exec('import ' + modulename)
            except:
                pass
            try:
                b =  eval(modulename + '.' + item2)

            except:
                print('execption trying modulepkg.',item2)
                exception1 = True
            if exception1:
                try:
                    b = eval('modulepkg.'+ item2)
                except:
                    exception2 = True
                    pass
            if not exception2:
                results = searchword(b, word, recursioncnt-1)
                for item2  in results:
                    strngpath = item + '.' + item2
                    asearch.append(strngpath)
   
    return asearch

No comments:

Post a Comment

Oblivion

 Between the fascination of an upcoming pandemic ridden college football season, Taylor Swift, and Kim Kardashian, wildfires, crazier weathe...