有没有办法在 Python 2.x 中将二进制输出写入 sys.stdout?在 Python 3.x 中,您可以只使用 sys.stdout.buffer(或分离 stdout 等),但我无法找到 Python 2.5/2.6 的任何解决方案.
Is there any way to write binary output to sys.stdout in Python 2.x? In Python 3.x, you can just use sys.stdout.buffer (or detach stdout, etc...), but I haven't been able to find any solutions for Python 2.5/2.6.
编辑,解决方案:来自 ChristopheD 的链接,如下:
EDIT, Solution: From ChristopheD's link, below:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
我正在尝试将 PDF 文件(二进制形式)推送到标准输出,以便在 Web 服务器上提供服务.当我尝试使用 sys.stdout.write 写入文件时,它会将各种回车添加到导致 PDF 呈现损坏的二进制流中.
I'm trying to push a PDF file (in binary form) to stdout for serving up on a web server. When I try to write the file using sys.stdout.write, it adds all sorts of carriage returns to the binary stream that causes the PDF to render corrupt.
编辑 2:对于这个项目,很遗憾,我需要在 Windows Server 上运行,所以 Linux 解决方案已经过时了.
EDIT 2: For this project, I need to run on a Windows Server, unfortunately, so Linux solutions are out.
简单的虚拟示例(从磁盘上的文件读取,而不是动态生成,只是为了让我们知道生成代码不是问题):
Simply Dummy Example (reading from a file on disk, instead of generating on the fly, just so we know that the generation code isn't the issue):
file = open('C:\test.pdf','rb')
pdfFile = file.read()
sys.stdout.write(pdfFile)
你在哪个平台上?
你可以试试这个食谱 如果您使用的是 Windows(链接表明它是 Windows 特定的).
You could try this recipe if you're on Windows (the link suggests it's Windows specific anyway).
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
网络上有一些参考资料表明 Python 3.1 中会有/应该有一个函数以二进制模式重新打开 sys.stdout
但我真的不知道是否有比以上适用于 Python 2.x.
There are some references on the web that there would/should be a function in Python 3.1 to reopen sys.stdout
in binary mode but I don't really know if there's a better alternative then the above for Python 2.x.
这篇关于Python 2.x - 将二进制输出写入标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!