1import importlib.machinery 2import os 3import sys 4 5from idlelib.browser import ClassBrowser, ModuleBrowserTreeItem 6from idlelib.pyshell import PyShellFileList 7from idlelib.tree import TreeItem 8 9 10class 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 28class PathBrowserTreeItem(TreeItem): 29 30 def GetText(self): 31 return "sys.path" 32 33 def GetSubList(self): 34 sublist = [] 35 for dir in sys.path: 36 item = DirBrowserTreeItem(dir) 37 sublist.append(item) 38 return sublist 39 40 41class DirBrowserTreeItem(TreeItem): 42 43 def __init__(self, dir, packages=[]): 44 self.dir = dir 45 self.packages = packages 46 47 def GetText(self): 48 if not self.packages: 49 return self.dir 50 else: 51 return self.packages[-1] + ": package" 52 53 def GetSubList(self): 54 try: 55 names = os.listdir(self.dir or os.curdir) 56 except OSError: 57 return [] 58 packages = [] 59 for name in names: 60 file = os.path.join(self.dir, name) 61 if self.ispackagedir(file): 62 nn = os.path.normcase(name) 63 packages.append((nn, name, file)) 64 packages.sort() 65 sublist = [] 66 for nn, name, file in packages: 67 item = DirBrowserTreeItem(file, self.packages + [name]) 68 sublist.append(item) 69 for nn, name in self.listmodules(names): 70 item = ModuleBrowserTreeItem(os.path.join(self.dir, name)) 71 sublist.append(item) 72 return sublist 73 74 def ispackagedir(self, file): 75 " Return true for directories that are packages." 76 if not os.path.isdir(file): 77 return False 78 init = os.path.join(file, "__init__.py") 79 return os.path.exists(init) 80 81 def listmodules(self, allnames): 82 modules = {} 83 suffixes = importlib.machinery.EXTENSION_SUFFIXES[:] 84 suffixes += importlib.machinery.SOURCE_SUFFIXES 85 suffixes += importlib.machinery.BYTECODE_SUFFIXES 86 sorted = [] 87 for suff in suffixes: 88 i = -len(suff) 89 for name in allnames[:]: 90 normed_name = os.path.normcase(name) 91 if normed_name[i:] == suff: 92 mod_name = name[:i] 93 if mod_name not in modules: 94 modules[mod_name] = None 95 sorted.append((normed_name, name)) 96 allnames.remove(name) 97 sorted.sort() 98 return sorted 99 100 101def _path_browser(parent): # htest # 102 flist = PyShellFileList(parent) 103 PathBrowser(flist, _htest=True) 104 parent.mainloop() 105 106if __name__ == "__main__": 107 from unittest import main 108 main('idlelib.idle_test.test_pathbrowser', verbosity=2, exit=False) 109 110 from idlelib.idle_test.htest import run 111 run(_path_browser) 112