Python的2.x的 - 写二进制输出到标准输出? [英] Python 2.x - Write binary output to stdout?
问题描述
有什么办法来写二进制输出在Python 2.x到sys.stdout来?在Python 3.x中,你可以使用sys.stdout.buffer(或分离标准输出,等...),但我一直没能找到任何解决方案的Python 2.5 / 2.6。
编辑,解决方案:
从ChristopheD的链接,如下:
进口SYS如果sys.platform ==的win32:
进口操作系统,MSVCRT
msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
编辑:我试图把一个PDF文件(二进制格式)到stdout的Web服务器上服务了。当我尝试编写使用sys.stdout.write函数的文件,它增加了各种回车来导致该PDF渲染腐败二进制流。
编辑2:对于这个项目,我需要在Windows Server上运行,不幸的是,这样的Linux解决方案都出来了。
。只要虚拟实例(从磁盘上的文件读取,而不是产生在飞行,只是让我们知道,一代code是不是问题):
文件=打开('C:\\\\的test.pdf,RB)
pdfFile = file.read()
sys.stdout.write函数(pdfFile)
哪个平台上是吗?
您可以尝试这个食谱如果你使用的是Windows(链接表明,它是Windows特定反正)。
如果sys.platform ==的win32:
进口操作系统,MSVCRT
msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
有网络上的一些参考,有会/应该是在Python 3.1的函数重新为sys.stderr
二进制模式,但我真的不知道,如果有一个更好的选择,然后上面的Python 2.x的。
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.
EDIT, Solution: From ChristopheD's link, below:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
EDIT: 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.
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)
Which platform are you on?
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)
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的 - 写二进制输出到标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!