Python 用于压缩目录中所有pdf文件的脚本

Python 用于压缩目录中所有pdf文件的脚本,python,pdf,ghostscript,Python,Pdf,Ghostscript,我希望使用ghostscript压缩目录中的所有pdf文件。 我想用python来读取文件 压缩pdf的gs命令是 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.j

我希望使用ghostscript压缩目录中的所有pdf文件。 我想用python来读取文件 压缩pdf的gs命令是

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
这会在“/screen”处出现语法错误, 对于下面的单个文件,该命令可以正常工作

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

有人能帮我更正此脚本或替代解决方案吗?

谢谢您的建议。我尝试了subprocess.call,这很有帮助。下面是解决问题的代码

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())

还发现-exec是shell脚本的好选择。

您需要调用执行程序的python函数。签出
子流程。调用
。另外,将文件名粘在一起时使用了错误的变量名,它应该是
filename=os.path.join(path,file)
。可能是一个更简单的选择.我无法在Windows7上使用。这是不同的命令吗