How do you escape text so you can use it as a quoted argument in a Bash command?
I'm trying to run a command like:
os.system(f'mycommand.py "{some_value_generated_by_python}"')
Answers to similar questions have suggested shlex.quote()
or pipes.quote()
, but none of these work inside quoted arguments because these both escape single and double quotes by wrapping them inside single or double quotes, which isn't proper shell escaping.
I also can't use unquoted arguments because my string may contain spaces, and naturally, neither method escapes spaces at all.
So if my value was "Hello y'all", it would generate a command like:
sh mycommand.py "Hello y"'"all"
which isn't a valid command syntax.
I could write some regexes to do the escaping, but is there some pre-existing function to do this?