Alex Alex - 1 year ago 56
Python Question

Python subprocess call throws errors when using find

I am making a script in

from the
library. The problem that I am having is that this command
find . -mtime +3 | xargs rm -rf
will work perfectly fine when put into the terminal but when I do this:

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

I end up getting an error that looks something like this:

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

What I am doing wrong? Please help :-)

Answer Source

| isn't a command argument; it is shell syntax for joining two commands together.

The simplest way to use a pipe is to pass a single string to subprocess and let a shell parse it:

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

In this case, it works nicely because the command line is very simple; nothing needs quoting.

You can set up a pipe in Python, but it's not as succinct as a single | character.

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

See the Python documentation for further reference.