在 subprocess.Popen 中向 'pstops' 发出指定参数

Issue specifying parameters to 'pstops' in subprocess.Popen

从命令行发出此命令:

pdftops -paper A4 -nocenter opf.pdf - | pstops "1:0@0.8(0.5cm,13.5cm)" > test.ps

工作正常。我试图将其转换为 subprocess.Popen 的参数列表,如下所示:

import subprocess as sp

path = 'opf.pdf'

ps = sp.Popen(
            ["pdftops",
             "-paper", "A4",
             "-nocenter",
             "{}".format(path),
             "-"],
            stdout = sp.PIPE)
pr = sp.Popen(
            ["pstops",
             "'1:0@0.8(0.5cm,13.5cm)'"],
            stdin = ps.stdout,
            stdout = sp.PIPE)
sp.Popen(
            ["lpr"],
            stdin = pr.stdout )

其中 path 是文件名 - opf.pdf。这会产生错误,在第二个 Popen:

0x23f2dd0age specification error:
  pagespecs = [modulo:]spec
  spec      = [-]pageno[@scale][L|R|U|H|V][(xoff,yoff)][,spec|+spec]
                modulo >= 1, 0 <= pageno < modulo

(原文如此)。我怀疑 0x23f2dd0 以某种方式取代了 'P'。无论如何,我怀疑问题出在页面规范 1:0@0.8(0.5cm,13.5cm) 中,所以我尝试了 with/without 单引号和(转义)双引号。我什至尝试了 shlex.quote,它产生了一个非常奇特的 ''"'"'1:0@0.8(0.5cm,13.5cm)'"'"'',但仍然是同样的错误。

这是什么原因造成的?

编辑 作为最后一个资源,我尝试了:

    os.system(("pdftops -paper A4 -nocenter {} - | "
               "pstops '1:0@0.8(1cm,13.5cm)' | "
               "lpr").format(path))

效果很好。不过,我仍然更喜欢上面的 Popen 解决方案。

想想 shell 对那个论点做了什么(或使用 printf '%s\n' 之类的东西来让它向你展示)。我们需要撤消 shell 引号并将其替换为 Python 引号(这恰好非常相似):

pr = sp.Popen(
            ["pstops",
             "1:0@0.8(0.5cm,13.5cm)"],
            stdin = ps.stdout,
            stdout = sp.PIPE)