sitecustomize.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. '''Hooks for isloating the AppImage Python and making it relocatable
  2. '''
  3. import atexit
  4. import os
  5. import sys
  6. def clean_path():
  7. '''Remove system locations from the packages search path
  8. '''
  9. site_packages = '/usr/local/lib/python{:}.{:}/site-packages'.format(
  10. *sys.version_info[:2])
  11. binaries_path = '/usr/local/bin'
  12. env_path = os.getenv("PYTHONPATH")
  13. if env_path is None:
  14. env_path = []
  15. else:
  16. env_path = [os.path.realpath(path) for path in env_path.split(':')]
  17. if ((os.path.dirname(sys.executable) != binaries_path) and
  18. (site_packages not in env_path)):
  19. # Remove the builtin site-packages from the path
  20. try:
  21. sys.path.remove(site_packages)
  22. except ValueError:
  23. pass
  24. clean_path()
  25. def patch_pip_install():
  26. '''Change absolute shebangs to relative ones following a `pip` install
  27. '''
  28. if ('pip' in sys.modules) and ('install' in sys.argv[1:]):
  29. for exe in os.listdir(sys.prefix + '/bin'):
  30. path = os.path.join(sys.prefix, 'bin', exe)
  31. if (not os.path.isfile(path)) or (not os.access(path, os.X_OK)) or \
  32. exe.startswith('python') or os.path.islink(path) or \
  33. exe.endswith('.pyc') or exe.endswith('.pyo'):
  34. continue
  35. try:
  36. with open(path, 'r') as f:
  37. header = f.read(2)
  38. if header != '#!':
  39. continue
  40. content = f.read()
  41. except:
  42. continue
  43. shebang, body = content.split(os.linesep, 1)
  44. shebang = shebang.split()
  45. python_x_y = os.path.basename(shebang.pop(0))
  46. if not python_x_y.startswith('python'):
  47. continue
  48. relpath = os.path.relpath(
  49. sys.prefix + '/../../usr/bin/' + python_x_y,
  50. sys.prefix + '/bin')
  51. shebang.append('"$@"')
  52. cmd = (
  53. '"exec"',
  54. '"$(dirname $(readlink -f ${0}))/' + relpath + '"',
  55. '"$0"',
  56. ' '.join(shebang)
  57. )
  58. try:
  59. with open(path, 'w') as f:
  60. f.write('#! /bin/sh\n')
  61. f.write(' '.join(cmd) + '\n')
  62. f.write(body)
  63. except IOError:
  64. pass
  65. atexit.register(patch_pip_install)