I am running ghostscript in a subprocess, which is working well except I don’t seem to be able to capture errors.
import subprocess
cmd = 'gs -dSAFER -dNOPAUSE -dBATCH -sDEVICE=jpeg -sOutputFile=img-%d.jpeg -r150 -g600x600 sample.pdf'
p = subprocess.Popen(cmd.split(), shell=False, stderr=subprocess.PIPE)
stderr = p.communicate()
print stderr
My problem is whether the command executes correctly or no the stderr always equals:
(None, ”)
I made a second attempt specifying both stdout and stderr
p = subprocess.Popen(slide_cmd.split(), shell=False, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
p.stdout gives output but p.stderr still returns on None
Ghostscript seems to write mostly to STDOUT, except for the summary of fatal errors like
which ends up on STDERR. So, read STDOUT as well and you should be able to capture everything.
In order to help debug this, print the command you’re executing in python using subprocess and then use IO redirection in your shell to redirect output to files in order to see on that stream GS outputs what. For example:
gs [args] 2>stderr.txt 1>stdout.txtOn a side note, you should use
shlex.split()instead ofstr.split()to tokenize argument lists, see this note in the subprocess docs.On a second site note: Once you start substituting ‘sample.pdf’ with an actual filename using string formatting (
cmd % filename), make sure you escape that%d(because it’s meant to be interpreted by GS, not Python) by using%%dinstead.