问题
I am executing bash command using python's subprocess.call(). I am taking user input as an argument to my command like below.
my_command = 'command -option1 {0} -option2 {1}'.format(arg1, arg2)
Here arg1 and arg2 are user inputs but the problem is user input can have quotes and spaces so I want to surround arguments by double quotes like this.
my_command = 'command -option1 "{0}" -option2 "{1}"'.format(arg1, arg2)
Since I have no control over user input, input can contains double quotes or single quotes. Hence I am replacing input with following escape sequence.
arg1 = arg1.replace('"', '\"').replace("'", "\'")
arg2 = arg2.replace('"', '\"').replace("'", "\'")
my_command = 'command -option1 "{0}" -option2 "{1}"'.format(arg1, arg2)
All looks good to me but when I execute command I get following error.
subprocess.call(shlex.split(my_command))
File "/usr/lib/python2.6/shlex.py", line 279, in split return list(lex)
File "/usr/lib/python2.6/shlex.py", line 269, in next token = self.get_token()
File "/usr/lib/python2.6/shlex.py", line 96, in get_token raw = self.read_token() File "/usr/lib/python2.6/shlex.py", line 172, in read_token
raise ValueError, "No closing quotation"
ValueError: No closing quotation
How can I deal with it ?
Edit : I want to preserve those quotes and spaces in bash command.
回答1:
Don't deal with quotation marks, spaces, etc. Just use a list:
my_command = ["command", "-option1", arg1, "-option2", arg2]
subprocess.call(my_command)
回答2:
You are not escaping quotes in your current code as \"
is simply equal to "
. You should use double escapes to escape the backslash (\
) character:
arg1 = arg1.replace('"', '\\"').replace("'", "\\'")
arg2 = arg2.replace('"', '\\"').replace("'", "\\'")
来源:https://stackoverflow.com/questions/35762670/escaping-quotes-in-bash-command-using-subprocess-call-and-shlex