subprocess.run simple scenario fails

999 views Asked by At

I am trying to run python subprocess.run function to execute following command:

 pdftoppm -jpeg -f 1 -scale-to 200 data/andromeda.pdf and-page

pdftoppm - is part of poppler utility and it generates images from pdf files.

File data/andromeda.pdf exists. Folder data is on same level with python script and/or where I run command from. Command basically will generate a jpeg file, from page 1 (-f 1) 200px wide (-scale-to) from given file of and-page-1.jpeg format (so called ppmtroot).

Long story short: from command line it works as expected i.e. if I call the above command either from zsh or bash shell, manually - it generates thumbnail as expected. However if I run it from python subprocess module - it fails it returns 99 error code!

Following is python code (file name is sc_02_thumbnails.py):

import subprocess
import sys


def main(filename, ppmroot):
    cmd = [
        'pdftoppm',
        '-f 1',
        '-scale-to 200',
        '-jpeg',
        filename,
        ppmroot
    ]
    result = subprocess.run(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    if result.returncode:
        print("Failed to generate thumbnail. Return code: {}. stderr: {}".format(
            result.returncode,
            result.stderr
        ))
        print("Used cmd: {}".format(' '.join(cmd)))
        sys.exit(1)
    else:
        print("Success!")         


if __name__ == "__main__":
    if len(sys.argv) > 2:
        filename = sys.argv[1]
        ppmroot = sys.argv[2]
    else:
        print("Usage: {} <pdffile> <ppmroot>".format(sys.argv[0]))
        sys.exit(1)

    main(filename, ppmroot)

And here is repo which includes data/andromeda.pdf file as well. I call my script with as (from zsh):

 $ chmod +x ./sc_02_thumbnauils.py
 $ ./sc_02_thumbnails.py data/andromeda.pdf  and-page

and ... thumbnail generating fails! I have tried executing python script from both, from zsh and bash shells :( What I am doing wrong?

1

There are 1 answers

1
tripleee On BEST ANSWER

The quoting is wrong, you should have '-f', '1', etc