site-patch.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. def __boot():
  2. import sys
  3. import os
  4. PYTHONPATH = os.environ.get('PYTHONPATH')
  5. if PYTHONPATH is None or (sys.platform == 'win32' and not PYTHONPATH):
  6. PYTHONPATH = []
  7. else:
  8. PYTHONPATH = PYTHONPATH.split(os.pathsep)
  9. pic = getattr(sys, 'path_importer_cache', {})
  10. stdpath = sys.path[len(PYTHONPATH):]
  11. mydir = os.path.dirname(__file__)
  12. for item in stdpath:
  13. if item == mydir or not item:
  14. continue # skip if current dir. on Windows, or my own directory
  15. importer = pic.get(item)
  16. if importer is not None:
  17. loader = importer.find_module('site')
  18. if loader is not None:
  19. # This should actually reload the current module
  20. loader.load_module('site')
  21. break
  22. else:
  23. try:
  24. import imp # Avoid import loop in Python 3
  25. stream, path, descr = imp.find_module('site', [item])
  26. except ImportError:
  27. continue
  28. if stream is None:
  29. continue
  30. try:
  31. # This should actually reload the current module
  32. imp.load_module('site', stream, path, descr)
  33. finally:
  34. stream.close()
  35. break
  36. else:
  37. raise ImportError("Couldn't find the real 'site' module")
  38. # 2.2 comp
  39. known_paths = dict([(
  40. makepath(item)[1], 1) for item in sys.path]) # noqa
  41. oldpos = getattr(sys, '__egginsert', 0) # save old insertion position
  42. sys.__egginsert = 0 # and reset the current one
  43. for item in PYTHONPATH:
  44. addsitedir(item) # noqa
  45. sys.__egginsert += oldpos # restore effective old position
  46. d, nd = makepath(stdpath[0]) # noqa
  47. insert_at = None
  48. new_path = []
  49. for item in sys.path:
  50. p, np = makepath(item) # noqa
  51. if np == nd and insert_at is None:
  52. # We've hit the first 'system' path entry, so added entries go here
  53. insert_at = len(new_path)
  54. if np in known_paths or insert_at is None:
  55. new_path.append(item)
  56. else:
  57. # new path after the insert point, back-insert it
  58. new_path.insert(insert_at, item)
  59. insert_at += 1
  60. sys.path[:] = new_path
  61. if __name__ == 'site':
  62. __boot()
  63. del __boot