Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions source/isaaclab/isaaclab/cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,34 @@ def _print_debug_env(prefix: str, env: dict[str, str] | None) -> None:
print_debug(f"{prefix}: ENV removed: {env_removed}")


_CMD_METACHARACTERS = frozenset("<>|&^")


def _escape_for_cmd_exe(cmd: list[str] | tuple[str, ...]) -> str | list[str]:
"""
Quote ``cmd.exe`` metacharacters when invoking ``.bat``/``.cmd`` files.

Returns a command string (not list) so ``subprocess.run`` bypasses
``list2cmdline`` which doesn't escape cmd.exe metacharacters (<, >, |, &, ^).
"""
# Only .bat/.cmd files are executed via cmd.exe.
exe = str(cmd[0]).lower()
if not (exe.endswith(".bat") or exe.endswith(".cmd")):
return list(cmd)

# Wrap args that contain metacharacters or whitespace in double quotes.
parts: list[str] = []
for arg in cmd:
s = str(arg)
if any(c in s for c in _CMD_METACHARACTERS) or " " in s or "\t" in s:
parts.append(f'"{s}"')
else:
parts.append(s)

# Return a string so subprocess skips list2cmdline.
return " ".join(parts)


def run_command(
cmd: str | list[str] | tuple[str, ...],
cwd: str | Path | None = None,
Expand Down Expand Up @@ -179,6 +207,10 @@ def run_command(
print_debug(f'run_command(): CMD: "{command_str}"')
_print_debug_env("run_command()", env)

# On Windows, escape cmd.exe metacharacters when invoking .bat/.cmd files.
if isinstance(cmd, (list, tuple)) and is_windows():
cmd = _escape_for_cmd_exe(cmd)

try:
return subprocess.run(
cmd,
Expand Down
Loading