【发布时间】: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