Python 使用查找时子进程调用抛出错误

Python subprocess call throws errors when using find

我正在使用 subprocess 库中的 callpython3 中制作脚本。我遇到的问题是这个命令 find . -mtime +3 | xargs rm -rf 在输入终端时可以正常工作但是当我这样做时:

from subprocess import call
call(["find", ".", "-mtime", "+3", "|", "xargs", "rm", "-rf"])

我最终收到如下所示的错误:

find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]
1

我做错了什么?请帮助:-)

| 不是命令参数;它是 shell 将两个命令连接在一起的语法。

使用管道的最简单方法是将单个字符串传递给 subprocess 并让 shell 解析它:

from subprocess import call
call("find . -mtime +3 | xargs rm -rf", shell=True)

在这种情况下,它工作得很好,因为命令行非常简单;没有什么需要引用。

您可以在 Python 中设置竖线,但不如单个 | 字符简洁。

from subprocess import Popen, PIPE
p1 = Popen(["find", ".", "-mtime", "+3"], stdout=PIPE)
p2 = Popen(["xargs", "rm", "-rf"], stdin=p1.stdout)
p1.stdout.close()
p2.wait()

请参阅 further reference 的 Python 文档。