Escaping quotes in bash command using subprocess call and shlex

不想你离开。 提交于 2019-12-25 04:38:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!