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