1"""Recursively load pth files in site-packages of sys.path 2 3- iterate over sys.path 4- check for pth in dirs that end in site-packages 5- ignore import statements in pth files 6- add dirs listed in pth files right after current sys.path element, 7 they will be processed in next iteration 8""" 9 10import os 11import site 12import sys 13 14 15for path_idx, sitedir in enumerate(sys.path): 16 # ignore non-site-packages 17 if not sitedir.endswith('site-packages'): 18 continue 19 20 # find pth files 21 try: 22 names = os.listdir(sitedir) 23 except os.error: 24 continue 25 dotpth = os.extsep + "pth" 26 pths = [name for name in names if name.endswith(dotpth)] 27 28 for pth in pths: 29 fullname = os.path.join(sitedir, pth) 30 try: 31 f = open(fullname, "rU") 32 except IOError: 33 continue 34 35 with f: 36 for n, line in enumerate(f): 37 if line.startswith("#"): 38 continue 39 40 if line.startswith(("import ", "import\t")): 41 continue 42 43 line = line.rstrip() 44 dir, dircase = site.makepath(sitedir, line) 45 if not dircase in sys.path: 46 sys.path.insert(path_idx+1, dir)