0
votes

I'm having problem with string redirection and python with a shell Ghostscript command.

There is NP executing this:

subprocess.call(["gs", "-q","-dBATCH", "-dNOPAUSE","-sDEVICE=bbox", "input.pdf"])

But I get an error adding 2>&1:

subprocess.call(["gs", "-q","-dBATCH", "-dNOPAUSE","-sDEVICE=bbox", "input.pdf","2>&1"])

Or:

subprocess.call(["gs", "-q","-dBATCH", "-dNOPAUSE","-sDEVICE=bbox", "input.pdf","2>&1",">/dev/null"])

I want to use 2>&1 to apply 'grep'.

Sample of the error:

Error: /undefinedfilename in (2>&1) Operand stack:

Execution stack: %interp_exit .runexec2 --nostringval--
--nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push Dictionary stack: --dict:1156/1684(ro)(G)--
--dict:1/20(G)-- --dict:77/200(L)-- Current allocation mode is local Last OS error: 2 GPL Ghostscript 9.05: Unrecoverable error, exit code 1 1

Still remains unsolved how to execute a command like:

subprocess.call("gs -q -dBATCH -dNOPAUSE -sDEVICE=bbox input.pdf 2>&1
| egrep -v HiResBoundingBox | egrep -o "[0-9]{1,}",shell=True)
1
The "unsolved" command you are trying to execute doesn't work? Or it doesn't work if you try to do it with shell=False? (it seems to me that it should work with shell=True) - mgilson
Your initial version had a typo: it had '2<&1' where '2>&1' should have been (at 2 different locations). Check if this was the cause of the error you did see. Otherwise, it may be Python (which I'm not overly familiar with) not supporting this kind of redirection (or requiring a different syntax). - Kurt Pfeifle
Read up about Ghostscript's 'Interacting with Pipes' here: git.ghostscript.com/?p=ghostpdl.git;a=blob_plain;f=gs/doc/… - It may help you to find a workaround. - Kurt Pfeifle
Sorry for the typo. Still the last command does not work even with shell=False. Thanks. - jacktrades

1 Answers

2
votes

It's because you're passing the arguments as a list. When you pass the arguments as an iterable, each piece is passed to the spawned process (in this case, gs is complaining that it doesn't know what to do with 2>&1...) You'd probably get the same message if you typed:

gs -q -dBATCH -dNOPAUSE -sDEVICE=bbox input.pdf '2>&1' 

in a shell.

subprocess.call("gs -q -dBATCH -dNOPAUSE -sDEVICE=bbox input.pdf 2>&1",shell=True)

will do what you want -- or 'better'...

import sys
subprocess.call(["gs", "-q", "-dBATCH", "-dNOPAUSE", "-sDEVICE=bbox", "input.pdf"],stderr=sys.stdout)

(better because it sidesteps the security issues with shell=True)