gpt4 book ai didi

python - 在 python 中捕获复杂 shell 命令的输出

转载 作者:行者123 更新时间:2023-12-01 05:01:52 25 4
gpt4 key购买 nike

我想在 python 脚本中嵌入命令并捕获输出。在这种情况下,我尝试使用 "find"在不确定数量的子目录中查找不确定数量的文件,并 grep 每个匹配的文件以查找字符串,例如:

grep "rabbit" `find . -name "*.txt"`

我正在运行 Python 2.6.6(是的,我也很抱歉,但现在无法让整个组织为此做出让步)。

我使用 subprocess 尝试了很多东西, shlex等等,这里已经建议了,但我还没有找到一种语法,要么吞掉这个,要么最终吸收“查找...”as the search string for grep` 等。建议表示赞赏。肯

最佳答案

import subprocess


find_p = subprocess.Popen(["find", ".", "-name", "*.txt"], stdout=subprocess.PIPE)
grep_p = subprocess.Popen(["xargs", "grep", "rabbit"], stdin=find_p.stdout)

grep_p.wait()

关于python - 在 python 中捕获复杂 shell 命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25937921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com