Use shlex.quote for shell argument escaping on POSIX

quote_arg() only wrapped arguments containing spaces in double quotes.
Shell metacharacters ($, backtick, ;, |, &, etc.) were left unescaped.

On POSIX, use shlex.quote() which single-quotes to prevent all shell
interpretation. Retain original Windows behavior since cmd.exe does not
interpret single-quoted strings.
This commit is contained in:
Asher Haig committed 2026-03-21 23:21:16 -04:00
1 parent 0c915bd18d
commit 239f480cbb
1 file changed
+11 -4
+11 -4
View File
@@ -1,4 +1,5 @@
import platform
import shlex
import subprocess
@@ -15,8 +16,14 @@ def subprocess_kwargs() -> dict:
def quote_arg(arg: str) -> str:
"""
Adds quotes around an argument if it contains spaces.
Quotes a shell argument to prevent interpretation of metacharacters.
Uses :func:`shlex.quote` on POSIX systems for proper escaping of all
shell-special characters. On Windows, wraps arguments containing spaces
in double quotes (Windows shell does not interpret single-quoted strings).
"""
if " " not in arg:
return arg
return f'"{arg}"'
if platform.system() == "Windows":
if " " not in arg:
return arg
return f'"{arg}"'
return shlex.quote(arg)