_rewrite_shebangs.py 816 B

12345678910111213141516171819202122232425262728293031323334
  1. """This is run during installation to rewrite the shebang (#! headers) of script
  2. files.
  3. """
  4. import glob
  5. import os.path
  6. import sys
  7. if sys.version_info[0] >= 3:
  8. # What do we do if the path contains characters outside the system code page?!
  9. b_python_exe = sys.executable.encode(sys.getfilesystemencoding())
  10. else:
  11. b_python_exe = sys.executable
  12. def rewrite(path):
  13. with open(path, 'rb') as f:
  14. contents = f.readlines()
  15. if not contents:
  16. return
  17. if contents[0].strip() != b'#!python':
  18. return
  19. contents[0] = b'#!' + b_python_exe + b'\n'
  20. with open(path, 'wb') as f:
  21. f.writelines(contents)
  22. def main():
  23. target_dir = sys.argv[1]
  24. for path in glob.glob(os.path.join(target_dir, '*-script.py')):
  25. rewrite(path)
  26. if __name__ == '__main__':
  27. main()