4 ms·
No love for Python's shlex.quote[1] or their equivalents in other languages to quote arguments for shell? In his case, which is interpolating a variable inside
by telotortium 2y ago
No love for Python's shlex.quote[1] or their equivalents in other languages to quote arguments for shell? In his case, which is interpolating a variable inside a shell double-quoted string, I would probably use environment variables, or else use shell `printf` with `shlex.quote`. But generally I interpolate directly into the command line using `shlex.quote`, when I can't avoid executing using the shell.
I was happy to learn about Python's template string proposal (i.e., t-strings) from https://peps.python.org/pep-0750/ https://peps.python.org/pep-0750/, although it probably won't become common for a while.
[1] https://docs.python.org/3/library/shlex.html#shlex.quote https://docs.python.org/3/library/shlex.html#shlex.quote
- Wingy 2y agoYes, you can quote the values and embed them directly, but what if you want to do something like this? shell('echo "Hello, {user}"') You would have to do something like: arg_for_echo = f"Hello, {user}" shell(f"echo {shlex.quote(arg_for_echo)}") The main drawback of quoting values like that is that you can't embed them inside an argument in the shell. The environment variable "trick" I used avoids this problem. Using quotes to sanitize arguments like that is how google/zx (library for writing shell/JS hybrid scripts) handles arguments: https://google.github.io/zx/quotes https://google.github.io/zx/quotes
- oasisaimlessly 2y agoMy proposal: shell('echo '+shlex.quote(f'Hello, {user}')) i.e. never quote any (non-constant?) shell args by hand.