2014-11-24 124 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

相關問題