Search code examples
pythonsubprocesspopenghostscript

convert Ghostscript from os.popen to subsession.popen python


I need to create a Monkey patch for Ghostscript, I have to migrate from os.popen to subsession.popen because I can't use the shell in my system.

I tried it in this way:

def mioGhostscript(tile, size, fp):
    """Render an image using Ghostscript (Unix only)"""

    # Unpack decoder tile
    decoder, tile, offset, data = tile[0]
    length, bbox = data

    import tempfile, os

    file = tempfile.mktemp()

    # Build ghostscript command
    command = ["gs",
        "-q",                    # quite mode
        "-g%dx%d" % size,        # set output geometry (pixels)
        "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
        "-sDEVICE=ppmraw",       # ppm driver
        "-sOutputFile=%s" % file,# output file
        "- >/dev/null 2>/dev/null"
    ]

    #command = shlex.split(string.join(command))
    # push data through ghostscript

    try:
        #gs = os.popen(command, "w")

        args = command#['gs','-dSAFER','-dNOPAUSE','-dBATCH','-sDEVICE=jpeg','-sOutputFile=/home/user/output2.jpg /home/user/downloads/test.pdf']
        gs = subprocess.Popen( args, stdout = PIPE, stderr = STDOUT, stdin=PIPE )
        # adjust for image origin
        if bbox[0] != 0 or bbox[1] != 0:
            #gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
            gs.stdin.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
        fp.seek(offset)
        while length > 0:
            s = fp.read(8192)
            if not s:
                break
            length = length - len(s)
            raise Exception(s)
            gs.stdin.write(s)
        gs.communicate()[0]
        status = gs.stdin.close()
        #status = gs.close()
        #if status:
        #   raise IOError("gs failed (status %d)" % status)
        im = Image.core.open_ppm(file)
    finally:
        try: os.unlink(file)
        except: pass

    return im

import PIL
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

but i have this traceback:

Traceback (most recent call last): File "/home/web/lib/driver_mod_python.py", line 252, in handler buf = m.__dict__[pard['program']](pard) File "/home/dtwebsite/bin/cms_gest_ordini.py", line 44, in wrapped return func(pard) File "/home/dtwebsite/bin/cms_gest_ordini.py", line 95, in wrapped return func(pard) File "/home/dtwebsite/bin/cms_gest_picking_list.py", line 341, in picking_list tr_modelllo = render_row_picking_list(pard, item, picked=0, plist_allowed=plist_allowed) File "/home/dtwebsite/bin/cms_gest_picking_list.py", line 432, in render_row_picking_list aa = a.tostring() File "/rnd/apps/interpreters/python-2.5.6/lib/python2.5/site-packages/PIL/Image.py", line 532, in tostring self.load() File "/rnd/apps/interpreters/python-2.5.6/lib/python2.5/site-packages/PIL/EpsImagePlugin.py", line 283, in load self.im = Ghostscript(self.tile, self.size, self.fp) File "/home/dtwebsite/bin/cms_gest_picking_list.py", line 64, in mioGhostscript gs.stdin.write(s) IOError: [Errno 32] Broken pipe 

someone can help me please?


Solution

  • I found the solution at the problem. It was with the PIL package, something didn't compile right during the installation. After that i had a dependencies problem. I fixed it in the following way:

    import PIL.EpsImagePlugin
    PIL.EpsImagePlugin.Ghostscript = mioGhostscript
    

    Then I saw this in the command:

    "- >/dev/null 2>/dev/null"
    

    the code is a shell's code and it didn't work on my system because python tried to read a file literally named - >/dev/null 2>/dev/null and it doesn't exist.

    I replaced

    "- >/dev/null 2>/dev/null"
    

    with

    "-" 
    

    and the program now read from the stdin.

    The final code is:

    def mioGhostscript(tile, size, fp):
        """Render an image using Ghostscript (Unix only)"""
    
        # Unpack decoder tile
        decoder, tile, offset, data = tile[0]
        length, bbox = data
    
        import tempfile, os
    
        file = tempfile.mktemp()
    
        # Build ghostscript command
        command = ["gs",
            "-q",                    # quite mode
            "-g%dx%d" % size,        # set output geometry (pixels)
            "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
            "-sDEVICE=ppmraw",       # ppm driver
            "-sOutputFile=%s" % file,# output file
            "-"
        ]
    
        #command = shlex.split(string.join(command))
        # push data through ghostscript
    
        try:
            #gs = os.popen(command, "w")
    
            args = command#['gs','-dSAFER','-dNOPAUSE','-dBATCH','-sDEVICE=jpeg','-sOutputFile=/home/user/output2.jpg /home/user/downloads/test.pdf']
            gs = subprocess.Popen( args, stdout = PIPE, stderr = STDOUT, stdin=PIPE )
            # adjust for image origin
            if bbox[0] != 0 or bbox[1] != 0:
                #gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
                gs.stdin.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
            fp.seek(offset)
            while length > 0:
                s = fp.read(8192)
                if not s:
                    break
                length = length - len(s)
                gs.stdin.write(s)
            gs.communicate()[0]
            status = gs.stdin.close()
            #status = gs.close()
            #if status:
            #   raise IOError("gs failed (status %d)" % status)
            im = Image.core.open_ppm(file)
        finally:
            try: os.unlink(file)
            except: pass
    
        return im
    
    import PIL.EpsImagePlugin
    PIL.EpsImagePlugin.Ghostscript = mioGhostscript
    

    I hope this posts can help someone.