我有以下 Python 行:
import subprocess
subprocess.Popen("egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory", stdout=subprocess.PIPE, shell=True).communicate()[0]
不幸的是,bash 完全忽略了 --exclude=*{.git,.svn}* 标志。
我已将问题缩小到花括号。 --exclude=*.git* 将通过 python 的 popen 工作,但是引入花括号的那一刻,我束手无策。有什么建议吗?
注意:我尝试使用 Python 的 command 库运行该命令,它产生完全相同的输出——以及完全相同的被忽略的 --exclude 标志。
最佳答案
当您传递 shell=True 时,python 将命令转换为 /bin/sh -c <command>
(如描述 here )。/bin/sh 显然不支持花括号扩展。您可以改为尝试以下操作:
import subprocess
subprocess.Popen(["/bin/bash", "-c", "egrep -r --exclude=*{.git,.svn}* \"text\" ~/directory"], stdout=subprocess.PIPE).communicate()[0]
关于Bash : curly braces 的 Python 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8629618/