Search code examples
pythonpdfjpegghostscript

python ghostscript not closing output file


I'm trying to turn PDF files with one or many pages into images for each page. This is very much like the question found here. In fact, I'm trying to use the code from @Idan Yacobi in that post to accomplish this. His code looks like this:

import ghostscript

def pdf2jpeg(pdf_input_path, jpeg_output_path):
    args = ["pdf2jpeg", # actual value doesn't matter
            "-dNOPAUSE",
            "-sDEVICE=jpeg",
            "-r144",
            "-sOutputFile=" + jpeg_output_path,
            pdf_input_path]
    ghostscript.Ghostscript(*args)

When I run the code I get the following output from python: ##### 238647312 c_void_p(238647312L)

When I look at the folder where the new .jpg image is supposed to be created, there is a file there with the new name. However, when I attempt to open the file, the image preview says "Windows Photo Viewer can't open this picture because the picture is being edited in another program."

It seems that for some reason Ghostscript opened the file and wrote to it, but didn't close it after it was done. Is there any way I can force that to happen? Or, am I missing something else?

I already tried changing the last line above to the code below to explicitly close ghostscript after it was done.

GS = ghostscript.Ghostscript(*args)
GS.exit()

Solution

  • I was having the same problem where the image files were kept open but when I looked into the ghostscript init.py file (found in the following directory: PythonDirectory\Lib\site-packages\ghostscript__init__.py), the exit method has a line commented.

    The gs.exit(self._instance) line is commented by default but when you uncomment the line, the image files are being closed.

    def exit(self):
        global __instance__
        if self._initialized:
            print '#####', self._instance.value, __instance__
            if __instance__:
                gs.exit(self._instance) # uncomment this line
                self._instance = None
            self._initialized = False