Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - execute find with multiple conditions using Popen

I'd like to execute find with multiple conditions, for example: find foo excluding hidden files:

find . -type f \( -iname '*foo*' ! -name '.*' \)

Python code:

import subprocess

cmd = ["find", ".", "-type", "f", "(", "-iname", "*foo*", "!", "-name", ".*", ")"]
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print sp.communicate()[0].split()

Can somebody explain what I'm missing? Thanks!

like image 228
armandino Avatar asked Nov 25 '22 03:11

armandino


1 Answers

I ran into this issue as well, and I'm sure you've figured this out by now but I figured I'd weigh in just in case anyone else runs into the same issue. Come to find out, this happens due to what Python is actually doing when you use Popen (When shell=True is used, python is basically just using /bin/sh -c to pass in your command (Python's subprocess.Popen() results differ from command line?). shell is False by default, so if you omit this or set it to False, whatever is specified in 'executable' will be used. The docs go into more detail here: https://docs.python.org/2/library/subprocess.html#subprocess.Popen

Something along these lines should work

import subprocess
cmd = 'find . -type f -iname "*foo*" ! -name ".*"'
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print sp.communicate()[0].split()
like image 136
idofxeno Avatar answered Nov 26 '22 17:11

idofxeno