commands.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import io
  2. import shutil
  3. import win_cli_launchers
  4. from .util import text_types
  5. SCRIPT_TEMPLATE = u"""#!python
  6. import sys, os
  7. import site
  8. installdir = os.path.dirname(os.path.dirname(__file__))
  9. pkgdir = os.path.join(installdir, 'pkgs')
  10. sys.path.insert(0, pkgdir)
  11. # Ensure .pth files in pkgdir are handled properly
  12. site.addsitedir(pkgdir)
  13. os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
  14. # Allowing .dll files in Python directory to be found
  15. os.environ['PATH'] += ';' + os.path.dirname(sys.executable)
  16. {extra_preamble}
  17. if __name__ == '__main__':
  18. from {module} import {func}
  19. {func}()
  20. """
  21. def prepare_bin_directory(target, commands, bitness=32):
  22. exe_src = win_cli_launchers.find_exe('x64' if bitness == 64 else 'x86')
  23. for name, command in commands.items():
  24. shutil.copy(exe_src, str(target / (name+'.exe')))
  25. specified_preamble = command.get('extra_preamble', None)
  26. if isinstance(specified_preamble, text_types):
  27. # Filename
  28. extra_preamble = io.open(specified_preamble, encoding='utf-8')
  29. elif specified_preamble is None:
  30. extra_preamble = io.StringIO() # Empty
  31. else:
  32. # Passed a StringIO or similar object
  33. extra_preamble = specified_preamble
  34. module, func = command['entry_point'].split(':')
  35. with (target / (name+'-script.py')).open('w') as f:
  36. f.write(SCRIPT_TEMPLATE.format(
  37. module=module, func=func,
  38. extra_preamble=extra_preamble.read().rstrip(),
  39. ))