1 import os 2 import sys 3 import imp 4 5 from idlelib.TreeWidget import TreeItem 6 from idlelib.ClassBrowser import ClassBrowser, ModuleBrowserTreeItem 7 8 class PathBrowser(ClassBrowser): 9 10 def __init__(self, flist): 11 self.init(flist) 12 13 def settitle(self): 14 self.top.wm_title("Path Browser") 15 self.top.wm_iconname("Path Browser") 16 17 def rootnode(self): 18 return PathBrowserTreeItem() 19 20 class PathBrowserTreeItem(TreeItem): 21 22 def GetText(self): 23 return "sys.path" 24 25 def GetSubList(self): 26 sublist = [] 27 for dir in sys.path: 28 item = DirBrowserTreeItem(dir) 29 sublist.append(item) 30 return sublist 31 32 class DirBrowserTreeItem(TreeItem): 33 34 def __init__(self, dir, packages=[]): 35 self.dir = dir 36 self.packages = packages 37 38 def GetText(self): 39 if not self.packages: 40 return self.dir 41 else: 42 return self.packages[-1] + ": package" 43 44 def GetSubList(self): 45 try: 46 names = os.listdir(self.dir or os.curdir) 47 except os.error: 48 return [] 49 packages = [] 50 for name in names: 51 file = os.path.join(self.dir, name) 52 if self.ispackagedir(file): 53 nn = os.path.normcase(name) 54 packages.append((nn, name, file)) 55 packages.sort() 56 sublist = [] 57 for nn, name, file in packages: 58 item = DirBrowserTreeItem(file, self.packages + [name]) 59 sublist.append(item) 60 for nn, name in self.listmodules(names): 61 item = ModuleBrowserTreeItem(os.path.join(self.dir, name)) 62 sublist.append(item) 63 return sublist 64 65 def ispackagedir(self, file): 66 if not os.path.isdir(file): 67 return 0 68 init = os.path.join(file, "__init__.py") 69 return os.path.exists(init) 70 71 def listmodules(self, allnames): 72 modules = {} 73 suffixes = imp.get_suffixes() 74 sorted = [] 75 for suff, mode, flag in suffixes: 76 i = -len(suff) 77 for name in allnames[:]: 78 normed_name = os.path.normcase(name) 79 if normed_name[i:] == suff: 80 mod_name = name[:i] 81 if mod_name not in modules: 82 modules[mod_name] = None 83 sorted.append((normed_name, name)) 84 allnames.remove(name) 85 sorted.sort() 86 return sorted 87 88 def main(): 89 from idlelib import PyShell 90 PathBrowser(PyShell.flist) 91 if sys.stdin is sys.__stdin__: 92 mainloop() 93 94 if __name__ == "__main__": 95 main() 96