0

I'm currently making use of a complex find command to delete files that has a specific MIME type.

find -type f -exec bash -c '
  for f; do
    file=$(file -- "$f")
    if [[ $file =~ ^$f:\ "C source" ]]; then
      echo rm -- "$f"
    fi
  done
' bash {} +

I wanted to make use of python to run the following command as per my requirements. When I try to use subprocess to invoke the command I do not any output. I'm not sure if this is the right way to do it as I'm new to linux. Any help would be appreciated.

from subprocess import call
call('''
find -type f -exec bash -c '
  for f; do
    file=$(file -- "$f")
    if [[ $file =~ ^$f:\ "ASCII text" ]]; then
      echo rm -- "$f"
    fi
  done
' bash {} +

''', shell=True)

I currently have a set of files in my directory and I'm running this python script from the same directory. I'm expecting a set of filenames as an output since there are few matches for 'C source'

0

The function subprocess.call() returns a returncode (zero is success, non zero means some error occured).

If you want the command output use the function subprocess.check_output(...).

PS: haven't you considered write it all in Python? The std module pathlib is great for that.

8
  • Thanks. I tried subprocess.check_output() too but I don't get the output. For some reason the find command does not execute . Not sure if this is a right way to invoke a shell command from python
    – dmorgan
    Jul 26 '20 at 11:39
  • @dmorgan The reason probably is that you don't have `` at the end of each line of your shell multiline command. python from subprocess import call call(''' find -type f -exec bash -c ' \ for f; do \ file=$(file -- "$f") \ if [[ $file =~ ^$f:\ "ASCII text" ]]; then \ echo rm -- "$f" \ fi \ done \ ' bash {} + ''', shell=True)
    – icaine
    Jul 26 '20 at 13:30
  • @dmorgan seems block formatting doesn't work here. So check here pastebin.com/agXNFjaU
    – icaine
    Jul 26 '20 at 13:37
  • Thanks. Ya I did try that too. Added a '\' in each of the lines and still I don't see any changes in the output.
    – dmorgan
    Jul 26 '20 at 13:40
  • @dmorgan silly question - have you tried to wrap it with print: print(check_output(...).decode('utf8'))?
    – icaine
    Jul 26 '20 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.