2014-11-24 62 views
0

我希望使用ghostscript压缩目录中的所有pdf文件。 我想用Python来读取文件 的和压缩PDF格式的GS命令脚本压缩目录中的所有pdf文件

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 

这给了语法错误,在“/屏幕”, 对于下面的命令单个文件工作正常

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

有人可以帮我纠正这个脚本或备用解决方案吗?

+1

你需要调用一个执行程序的python函数。查看'subprocess.call'。另外,在将文件名粘合在一起时,您使用的是错误的变量名,它应该是'filename = os.path.join(path,file)'。 – tdelaney 2014-11-24 18:59:56

+0

['find ... -exec'](http://unixhelp.ed.ac.uk/CGI/man-cgi?find)可能是一个更简单的选项。 – georg 2014-11-24 19:15:06

回答

1

感谢您的建议tdelaney我试过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()) 

另外find ... -exec是shell脚本的好选择。

+0

我不能在Windows 7上使用它。它是不同的命令 – 2014-12-24 05:16:37

+0

@YankiTwizzy是 – Kalanamith 2016-08-26 04:24:11

相关问题