简体   繁体   中英

cupsfilter Does Not Work With Python subprocess.call()

After reading this question , I've been experimenting and using subprocess.call() in Python to run a command as if from the terminal. I've found it works quite well and I prefer it over os.system. I've run into a problem with cupsfilter, though. I'm trying to run this command on OS X, from Python:

cupsfilter -o cpi=10 PDFTestIn.txt 2>PDFTestError.txt >PDFTestOut.pdf

(I tried it, originally, with more than one option, but am limiting it to one option until I can get it working.)

I can run the command fine from the command line and from os.system, but I'm having trouble with this command in subprocess.call(). I've been experimenting in IDLE and cupsfilter does not work with this as other programs do. If I provide options in the form:

-o optionname=optionvalue

I always get error messages. I tried this:

import subprocess
import os
cmd = '/usr/sbin/cupsfilter'
args = ['-o cpi=10']
ifile='PDFTestIn.txt'
ofile='PDFTestOut.pdf'
efile='PDFTestError.txt'
cmdargs = [cmd] + args + [ifile]
with open(ofile, 'w') as pdfout, open(efile, 'w') as errout:
    subprocess.call(cmdargs, stdout=pdfout, stderr=errout)

When I do that, I get a return value of 1 from the last command. I check PDFTestError.txt for output and it reads:

cupsfilter: Unknown option " ".

I experimented by changing the 4th line to this:

args = ['-ocpi=10']

and I get this error:

cupsfilter: Unknown option "c".

Whatever character comes after the "-o" is seen as an option, and only that one letter is acknowledged, not the word (like "cpi"). Even though there are other options I can use besides "-o," I thought I'd try it without the "-o" just in case. When I do that, I get this error:

cupsfilter: Only one filename can be specified.

(And if I use only the command as an argument in the list passed to subprocess.call(), and still specify stdout and stderr, it works okay.)

Summary: When I use "-o" to provide an option for cupsfilter, in subprocess.call(), cupsfilter looks only at the next character, not the next word. If I have a space after "-o" as I would on the command line, it expects that space to be an option. If I leave the space out, it looks at the next character and not the next word. If I leave out "-o" it sees the option as another file name (as I'd expect).

But if I use the command line, above, from a terminal, or from os.system(), there's no problem at all.

Why won't this work with subprocess.call() and is there a way to correct that?

您需要分隔每个arg, '-o cpi=10' -> '-o', 'cpi=10'

subprocess.call([cmd,'-o','cpi=10',infile], stdout=pdfout, stderr=errout)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM