【发布时间】: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