java_command_file.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import platform
  2. import subprocess as sp
  3. def _java_cmd_file_quote(s):
  4. """ Wrap argument based on https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html#java-command-line-argument-files """
  5. if not s:
  6. return "''"
  7. if not any(char.isspace() for char in s):
  8. return s
  9. return f'"{s.replace('\\', '\\\\')}"'
  10. def call_java_with_command_file(cmd, wrapped_args, **kwargs):
  11. is_win = platform.system() == 'Windows'
  12. args = cmd
  13. args_to_wrap = wrapped_args
  14. if is_win:
  15. args = [cmd[0]]
  16. args_to_wrap = cmd[1:] + args_to_wrap
  17. commands_file = 'wrapped.args'
  18. with open(commands_file, 'w') as f:
  19. f.write(' '.join(_java_cmd_file_quote(arg) for arg in args_to_wrap))
  20. if is_win:
  21. # Some Windows machines has troubles with running cmd lines with `@` without shell=True
  22. kwargs['shell'] = True
  23. try:
  24. return sp.check_output(
  25. args + ["@" + commands_file],
  26. **kwargs
  27. )
  28. except Exception as e:
  29. if hasattr(e, "add_note"):
  30. e.add_note(f"Original command: {cmd} {wrapped_args}")
  31. e.add_note(f"Wrapped part: {wrapped_args}")
  32. raise