【问题标题】:Passing escape characters to grep -e command via Python subprocess.Popen()通过 Python subprocess.Popen() 将转义字符传递给 grep -e 命令
【发布时间】:2014-12-18 18:23:21
【问题描述】:

我想使用子进程从 Python 调用此命令:grep -e '^commit [a-z0-9]{40}'

当我直接在终端中调用此命令时,它不起作用,除非我用反斜杠转义大括号,例如:grep -e '^commit [a-z0-9]\{40\}'

当我尝试将此字符串与转义字符一起传递给在 python 中使用 Popen 的命令时,它不起作用。这是我尝试过的:

grepCommand = ['grep', '-e', "'^commit [a-z0-9]\\{{{0}\\}}'".format("40")]
grepCommand = ['grep', '-e', "'^commit [a-z0-9]\\\\{{{0}\\\\}}'".format("40")]
grepCommand = ['grep', '-e', "^commit [a-z0-9]\\{{{0}\\}}".format("40")]
grepCommand = ['grep', '-e', "^commit [a-z0-9]\\\\{{{0}\\\\}}".format("40")]

如何在 python 中正确格式化这个字符串,以便我可以通过 Popen 将它传递给 grep?

【问题讨论】:

  • 是否绝对有必要在 python 脚本中使用 grep,而不是使用原生 python 解决方案?
  • r"'^commit [a-z0-9]{40}'"
  • 您需要在{} 之前插入一个反斜杠,因为这是基本正则表达式的格式。您可能打算使用-E 选项而不是-e-E 用于扩展正则表达式,而 -e 仅表示下一个参数是一个模式(如果模式以 - 开头或有多个模式时很有用)。

标签: python regex bash grep subprocess


【解决方案1】:

该列表已经是一个参数分隔符,因此不需要额外引用'

grepCommand = ['grep', '-e', r"^commit [a-z0-9]\{{{0}\}}".format("40")]

【讨论】:

  • 这个答案中有错误的单引号,但除此之外它有效!
猜你喜欢
  • 2013-02-02
  • 2017-11-30
  • 1970-01-01
  • 2014-02-13
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
相关资源
最近更新 更多