Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.check_output not accepting long arguments

If I do the following from the same machine, I get a beautiful PDF as expected:

$ wkhtmltopdf --title "Transaction 773 (printed version)" --margin-left 5 --margin-right 2 --encoding utf8 www.google.com - > salida.pdf

But if from a common python shell I do:

>>> import subprocess
>>> f = open("salida.pdf", "wb")
>>> f.write(subprocess.check_output(["wkhtmltopdf", '--title "Transaction 773 (printed version)"', "--margin-left 5", "--margin-right 2", "--encoding utf8", "www.google.com", "-"]))

Then all I get is the common error:

/usr/lib/python2.7/subprocess.pyc in check_output(*popenargs, **kwargs)
    542         if cmd is None:
    543             cmd = popenargs[0]
--> 544         raise CalledProcessError(retcode, cmd, output=output)
    545     return output
    546 

CalledProcessError: Command '['wkhtmltopdf', '--title "Transaction 773 (printed version)"', '--margin-left 5', '--margin-right 2', '--encoding utf8', 'www.google.com', '-']' returned non-zero exit status 1

Looking at the complete error message, it tells me:

Unknown long argument --title "Transaction 773 (printed version)"

Why is not accepting the arguments? It's worth mentioning that if I remove all arguments and just leave the input file and the "-", it works like charm.

like image 573
Mariano Avatar asked Feb 19 '23 06:02

Mariano


1 Answers

You need to specify each argument in a separate item, and long arguments are actually 2 values:

f.write(subprocess.check_output([
    "wkhtmltopdf", 
    '--title', "Transaction 773 (printed version)",
    "--margin-left", "5",
    "--margin-right", "2",
    "--encoding", "utf8",
    "www.google.com", "-"]))

Normally, the shell parses such a command line, splits it on whitespace (except where text has been enclosed in quotes), and passes that on to the new process as the argv value.

Now, you are creating that argv list yourself, and you have to do the splitting yourself. Note that the --title argument thus no longer needs to have the shell-level quotes either.

A short argument (-ml5 or similar) doesn't have that whitespace, so you didn't have a problem with those.

like image 57
Martijn Pieters Avatar answered Feb 26 '23 19:02

Martijn Pieters