2017-01-24 2 views
0

Windows에서 파이썬 2.7을 통해 ghostscript를 실행하여 한 페이지 분량의 PDF 파일을 TIFF 이미지로 변환합니다. 내가 '(파일 설명 정상적으로 폐쇄해야한다고 제안 유사한 문제에 OSError: Too many open files파이썬과 고스트 스크립트 : OSError : 열려있는 파일이 너무 많습니다.

다른 게시물,하지만 난 그들을 여는 아니에요 이후 -

from os import listdir, remove 
from os.path import isfile, join 
import ghostscript 
import os 
import time 
import sys 

#Assumption #1: The input folder, output_tif_folder and output_pdf_folder 
#Assumption #2: Paths in windows use a backslash for reference. They have to be escaped characters - so use a \\ instead of a single \ 
# eg: 'C:\\Users\\User\\Desktop\\Folder\\' 
#Assumption #3: Required libraries are configured and installed properly. They are - i) ghostscript and ii) pyPdf 

input_folder = 'C:\\Users\\User\\Desktop\\Folder\\test_files\\'; #Has to be the absolute path, ending with a slash 
output_pdf_folder = 'C:\\Users\\User\\Desktop\\Folder\\pdf\\'; #Has to be an absolute path too, ending with a slash 
output_tif_folder = 'C:\\Users\\User\\Desktop\\Folder\\tif\\' #Absolute path too, ending with a slash 

onlyfiles = [f for f in listdir(input_folder) if isfile(join(input_folder, f))] 

from pyPdf import PdfFileWriter, PdfFileReader 

for pdfFile in onlyfiles: 
    inputpdf = PdfFileReader(open(input_folder + pdfFile, 'rb')) 
    for i in xrange(inputpdf.numPages): 
     output = PdfFileWriter() 
     output.addPage(inputpdf.getPage(i)) 
     with open(output_pdf_folder + pdfFile[:-4] + "_%s.pdf" % (i+1), "wb") as outputStream: 
      output.write(outputStream) 

def convertPdfTiff(inputfilename, outputfilename): 
    args = [ 
    "pdf2tif", # actual value doesn't matter 
    "-dNOPAUSE", "-dBATCH", "-dSAFER", 
    "-sDEVICE=tiff24nc", 
    "-sCompression=pack", 
    "-sOutputFile=" + outputfilename, 
    "-f", inputfilename 
    ] 
    try: 
     ghostscript.Ghostscript(*args) 
    except: 
     print 'something went wrong' 

pagefiles = [f for f in listdir(output_pdf_folder) if isfile(join(output_pdf_folder, f))] 
for pagefile in pagefiles: 
    print 'Input: ' + output_pdf_folder + pagefile 
    print 'Output: ' + output_tif_folder + pagefile[:-4] + ".tif" 
    convertPdfTiff(output_pdf_folder + pagefile, output_tif_folder + pagefile[:-4] + ".tif") 
    time.sleep(1) 

약 114 파일을 변환 한 후, 나는 다음과 같은 오류가 발생합니다 Ghostscript가 그렇게한다고 가정), 나는 그들을 닫을 수 없다.

이 상황을 처리하는 가장 좋은 방법은 무엇입니까?

답변

0

나는 파이썬 개발자 모르겠지만, (나는 잘못된 해요 경우 사과) 당신이 파일을 열 것을 나에게 보인다

for pdfFile in onlyfiles: 
    inputpdf = PdfFileReader(open(input_folder + pdfFile, 'rb')) 

당신이 그 파일을 닫고 어디 보이지 않아요. 그 외에도, Ghostscript는 분명히 모든 자체 파일을 닫아야합니다.하지만 Windows에서 GS가 파일을 실제로 삭제 한 후에 파일을 닫을 시간이 필요합니다. 그게 도움이되는지보기 위해 더 긴 time.sleep()을 넣을 수도 있습니다.

확실히 명령 줄에서 실행할 수 있습니다 (예 : DLL을 사용하는 대신 직접 Ghostscript를 사용하는 것). 수백 개의 파일을 처리해야합니다. Ghostscript 실행 파일이 같은 DLL을 사용하기 때문에 이런 식으로 사용하면 문제가 없습니다.