【问题标题】:PyPDF2: writing output to stdout fails with python3PyPDF2:使用 python3 将输出写入标准输出失败
【发布时间】:2019-06-19 14:38:20
【问题描述】:

我正在尝试使用 Python 3.7.2 和 PyPDF2 1.26 来选择输入 PDF 文件的一些页面并将输出写入标准输出(实际代码更复杂,这只是一个 MCVE):

import sys
from PyPDF2 import PdfFileReader, PdfFileWriter

input = PdfFileReader("example.pdf")
output = PdfFileWriter()
output.addPage(input.getPage(0))

output.write(sys.stdout)

这会失败并出现以下错误:

UserWarning: File <<stdout>> to write to is not in binary mode. It may not be written to correctly. [pdf.py:453]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/site-packages/PyPDF2/pdf.py", line 487, in write
    stream.write(self._header + b_("\n"))
TypeError: write() argument must be str, not bytes

问题似乎是sys.stdout 没有以二进制模式打开。正如一些答案所暗示的,我尝试了以下方法:

output.write(sys.stdout.buffer)

这会失败并出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/site-packages/PyPDF2/pdf.py", line 491, in write
    object_positions.append(stream.tell())
OSError: [Errno 29] Illegal seek

我也试过Changing the way stdin/stdout is opened in Python 3的答案:

sout = open(sys.stdout.fileno(), "wb")
output.write(sout)

这会失败并出现与上述相同的错误。

如何使用 PyPDF2 库将 PDF 输出到标准输出?

更一般地说,我如何正确地将sys.stdout 切换到二进制模式(类似于 Perl 的 binmode STDOUT)?

注意:无需告诉我我可以以二进制模式打开文件并将 PDF 写入该文件。这样可行;但是,我特别想将 PDF 写入标准输出。

【问题讨论】:

    标签: python python-3.x pypdf2


    【解决方案1】:

    From the documentation:

    write(stream)

    将添加到此对象的页面集合作为 PDF 文件写入。

    参数: stream – 将文件写入的对象。该对象必须支持write方法tell方法,类似于文件对象。

    事实证明,sys.stdout.buffer 如果不重定向到文件,则不是tellable,因此您不能将其用作PdfFileWriter.write 的流。

    假设您的脚本名为myscript。如果你只调用myscript,那么你会得到这个错误,但如果你使用它进行重定向,如:

    myscript > myfile.pdf
    

    然后 Python 知道它是一个可搜索的流,你不会得到错误。

    【讨论】:

    • 那么您的意思是,除非将标准输出重定向到文件,否则不可能使用 PyPDF2 将输出 PDF 写入标准输出?那是不幸的。我想将 Python 脚本与管道一起使用。
    • @NikolaBenes 恐怕似乎无法让 PyPDF2 写入非tellable 流。
    猜你喜欢
    • 1970-01-01
    • 2014-07-03
    • 2018-09-09
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    相关资源
    最近更新 更多