Script to compress all pdf files in a directory
Question: I wish to compress all pdf files in a directory using ghostscript. I thought
of using python to read files and the gs command that compress pdf is

    
    
    from __future__ import print_function
    import os
    for path, dirs, files in os.walk("/home/mario/books"):
        for file in files:
            if file.endswith(".pdf"):
                filename = os.path.join(root, file)
                gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=file filename
    

This gives syntax error at "/screen", For a single file below command works
fine

    
    
    gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=output.pdf input.pdf
    

Could someone help me correcting this script or alternate solution?


Answer: Thanks for suggestion tdelaney I tried subprocess.call which helped. Below is
the code solved the problem.

    
    
    from __future__ import print_function
    import os
    import subprocess
    for root, dirs, files in os.walk("."):
    for file in files:
        if file.endswith(".pdf"):
          filename = os.path.join(root, file)
          arg1= '-sOutputFile=' +"v"+ file
          p = subprocess.Popen(['/usr/bin/gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4', '-dPDFSETTINGS=/screen', '-dNOPAUSE', '-dBATCH',  '-dQUIET', str(arg1), filename], stdout=subprocess.PIPE)
          print (p.communicate())
    

Also find ... -exec is good option for shell script though.

