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