【发布时间】:2016-03-03 11:55:37
【问题描述】:
我正在使用 python 的 subprocess.call() 执行 bash 命令。 我将用户输入作为我的命令的参数,如下所示。
my_command = 'command -option1 {0} -option2 {1}'.format(arg1, arg2)
这里 arg1 和 arg2 是用户输入,但问题是用户输入可以有 引号和空格,所以我想用这样的双引号将参数括起来。
my_command = 'command -option1 "{0}" -option2 "{1}"'.format(arg1, arg2)
由于我无法控制用户输入,因此输入可以包含双引号或单引号。因此,我将输入替换为以下转义序列。
arg1 = arg1.replace('"', '\"').replace("'", "\'")
arg2 = arg2.replace('"', '\"').replace("'", "\'")
my_command = 'command -option1 "{0}" -option2 "{1}"'.format(arg1, arg2)
对我来说一切都很好,但是当我执行命令时出现以下错误。
subprocess.call(shlex.split(my_command))
文件“/usr/lib/python2.6/shlex.py”,第 279 行,拆分 返回列表(lex)
文件“/usr/lib/python2.6/shlex.py”,第 269 行,在下一个 令牌 = self.get_token()
文件“/usr/lib/python2.6/shlex.py”,第 96 行,在 get_token 中 raw = self.read_token() 文件“/usr/lib/python2.6/shlex.py”,第 172 行,在 read_token 中
raise ValueError, "没有收盘价"
ValueError: 没有结束引号
我该如何处理?
编辑:我想在 bash 命令中保留这些引号和空格。
【问题讨论】:
-
无关:
shlex不是很复杂。 It may break easily:r'echo "\$x"'。在开发过程中,从现有示例命令行创建初始args列表很有用。
标签: python bash escaping subprocess shlex