1
0

sitecustomize.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. '''Python AppImage hooks
  2. '''
  3. import atexit
  4. import os
  5. import sys
  6. _bin_at_start = os.listdir(sys.prefix + '/bin')
  7. '''Initial content of the bin/ directory
  8. '''
  9. def patch_pip_install():
  10. '''Change absolute shebangs to relative ones following a `pip` install
  11. '''
  12. if not 'pip' in sys.modules:
  13. return
  14. args = sys.argv[1:]
  15. if 'install' in args:
  16. for exe in os.listdir(sys.prefix + '/bin'):
  17. path = os.path.join(sys.prefix, 'bin', exe)
  18. if (not os.path.isfile(path)) or (not os.access(path, os.X_OK)) or \
  19. exe.startswith('python') or os.path.islink(path) or \
  20. exe.endswith('.pyc') or exe.endswith('.pyo'):
  21. continue
  22. try:
  23. with open(path, 'r') as f:
  24. header = f.read(2)
  25. if header != '#!':
  26. continue
  27. content = f.read()
  28. except:
  29. continue
  30. shebang, body = content.split(os.linesep, 1)
  31. shebang = shebang.split()
  32. python_x_y = os.path.basename(shebang.pop(0))
  33. if not python_x_y.startswith('python'):
  34. head, altbody = body.split(os.linesep, 1)
  35. if head.startswith("'''exec' /"): # Patch for alt shebang
  36. body = altbody.split(os.linesep, 1)[1]
  37. python_x_y = os.path.basename(head.split()[1])
  38. else:
  39. continue
  40. relpath = os.path.relpath(
  41. sys.prefix + '/../../usr/bin/' + python_x_y,
  42. sys.prefix + '/bin')
  43. shebang.append('"$@"')
  44. cmd = (
  45. '"exec"',
  46. '"$(dirname $(readlink -f ${0}))/' + relpath + '"',
  47. '"$0"',
  48. ' '.join(shebang)
  49. )
  50. try:
  51. with open(path, 'w') as f:
  52. f.write('#! /bin/sh\n')
  53. f.write(' '.join(cmd) + '\n')
  54. f.write(body)
  55. except IOError:
  56. continue
  57. if exe in _bin_at_start:
  58. continue
  59. usr_dir = os.path.join(sys.prefix, '../../usr/bin')
  60. usr_exe = os.path.join(usr_dir, exe)
  61. if not os.path.exists(usr_exe):
  62. relpath = os.path.relpath(path, usr_dir)
  63. os.symlink(relpath, usr_exe)
  64. elif 'uninstall' in args:
  65. usr_dir = os.path.join(sys.prefix, '../../usr/bin')
  66. for exe in os.listdir(usr_dir):
  67. path = os.path.join(usr_dir, exe)
  68. if (not os.path.islink(path)) or \
  69. os.path.exists(os.path.realpath(path)):
  70. continue
  71. os.remove(path)
  72. if os.getenv('VIRTUAL_ENV') is None:
  73. atexit.register(patch_pip_install)
  74. else:
  75. del _bin_at_start
  76. del patch_pip_install