在bash命令转义引号使用子呼叫,并shlex [英] Escaping quotes in bash command using subprocess call and shlex
问题描述
我使用python的subprocess.call执行bash命令()。
我是把用户输入像下面的参数传递给我的命令。
my_command ='命令-option1 {0} -option2 {1}。格式(ARG1,ARG2)
下面ARG1 ARG2和是用户输入的,但问题是用户输入可以的报价和空格的,所以我想围绕用双引号的参数是这样的。
my_command ='命令-option1{0}-option2{1}'格式(ARG1,ARG2)
因为我有超过用户输入无法控制,输入可包含双引号或单引号。因此,我有以下转义序列代替输入。
ARG1 = arg1.replace('','\\')取代(',\\')
ARG2 = arg2.replace('','\\')取代(',\\')
my_command ='命令-option1{0}-option2{1}'格式(ARG1,ARG2)
所有对我来说很好,但是当我执行命令我得到下面的错误。
subprocess.call(shlex.split(my_command))
文件/usr/lib/python2.6/shlex.py,线路279,在斯普利特
返回列表(法)
文件/usr/lib/python2.6/shlex.py,269线,在明年
令牌= self.get_token()
文件/usr/lib/python2.6/shlex.py,96线,在的get_token
原料= self.read_token()文件/usr/lib/python2.6/shlex.py,172线,在read_token
提高ValueError错误,无收盘
ValueError错误:没有收盘报价
块引用>我该如何处理呢?
编辑:我想preserve在bash命令这些报价和空格
解决方案不要用引号,空格等处理只需使用一个列表:
my_command = [命令,-option1ARG1-option2,ARG2]
subprocess.call(my_command)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.
解决方案Don't deal with quotation marks, spaces, etc. Just use a list:
my_command = ["command", "-option1", arg1, "-option2", arg2] subprocess.call(my_command)
这篇关于在bash命令转义引号使用子呼叫,并shlex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!