問題描述
有沒有辦法在 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模板網!