python - 通过 Python subprocess.Popen() 将转义字符传递给 grep -e 命令

标签 python regex bash grep subprocess

我想使用子进程从 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?

最佳答案

列表已经是参数分隔,因此不需要使用 ' 进行额外引用:

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

关于python - 通过 Python subprocess.Popen() 将转义字符传递给 grep -e 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27553210/

相关文章:

python - 网页抓取中的问题

python - 如何提取 python 脚本中使用的文件名的一部分作为参数?

python - 如何从python中的列表中删除所有整数值

Java正则表达式从txt文件输入

c# - 如何通过正则表达式验证mvc中的CNIC号

bash - 如何在 Ubuntu 中一次提取文件夹中的多个 7z 文件?

php - 如何在 ubuntu 中为 php 脚本设置 cron 作业

python - 如何在 Python 中拆分数字后显示前导零

php - 在 PHP preg_replace 函数中包含新行

linux - 在 Bash 中使用heredoc创建新文件