【问题标题】:Escaping quotes in bash command using subprocess call and shlex使用子进程调用和 shlex 在 bash 命令中转义引号
【发布时间】: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 命令中保留这些引号和空格。

【问题讨论】:

标签: python bash escaping subprocess shlex


【解决方案1】:

不要和引号、空格等打交道,用列表就行了:

my_command = ["command", "-option1", arg1, "-option2", arg2]
subprocess.call(my_command)

【讨论】:

  • 这种方法行不通,因为输入可以有空格,分割将基于空格。
  • 我的解决方案没有使用split
【解决方案2】:

您没有在当前代码中转义引号,因为\" 完全等于"。您应该使用双转义来转义反斜杠 (\) 字符:

arg1 = arg1.replace('"', '\\"').replace("'", "\\'")
arg2 = arg2.replace('"', '\\"').replace("'", "\\'")

【讨论】:

  • 谢谢 Sekcuk 但问题是我想保留那些引号和空格。
  • @AshokKumar 这就是为什么你应该使用我建议的方法来逃避它们。
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2013-12-28
相关资源
最近更新 更多