2

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?

Cerin
  • 60,957
  • 96
  • 316
  • 522

1 Answers1

3

You are looking for subprocess.run or subprocess.call, https://docs.python.org/3/library/subprocess.html, which take their arguments in a list, as in

import subprocess
subprocess.run(["mycommand.py", "Hello y'all"])
# make sure mycommand.py is in your path, or use /path/to/mycommand.py

This way allows for quotes, spaces, tabs, and much more fun that will not be interfered with by an intermediate shell.

mCoding
  • 4,059
  • 1
  • 5
  • 11