Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do `shlex.split`, `shlex.quote` and `shlex.join` help?

IntermediateConceptOS, filesystem, subprocess & CLIs
Answer
  • shlex.split('ssh -o "StrictHostKeyChecking no" host') turns a shell-like string into a correct argument list (respects quotes).
  • shlex.quote(value) safely quotes a value for inclusion in a shell string, for example a command sent over SSH, where a remote shell will parse it.
  • shlex.join(args) renders a list as a copy-pasteable command for logs.

Over SSH there is always a remote shell, so quoting matters even when the local call uses a list.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs