Bash的Python子进程:大括号

2024-04-29 15:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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的命令库运行该命令,它生成完全相同的输出——以及完全相同的忽略——排除标志。


Tags: textimportgit命令标志stdoutsvn大括号
3条回答

您需要引用该表达式,以防止bash在启动它时根据当前工作目录对其求值。你也有一个错误,你的搜索条件假设你正在寻找“文本”(与引文)。转义将引号放入Python字符串中,但需要再次执行此操作才能让shell看到它们。在

... --exclude='*{.git,.svn}*' \\\"text\\\" ...

当传递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]

我猜可能是脱壳?在

也许最好是自己把争论分开,完全避免空壳?在

import subprocess
subprocess.Popen(["egrep","-r","--exclude=*{.git,.svn}*","text","~/directory"], stdout=subprocess.PIPE).communicate()[0]

注意:你可能得展开~,我不确定。在

或者,如果bash应该扩展大括号,那么可以在python中执行:

^{pr2}$

相关问题 更多 >