文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!
-- 61.182.251.99 [DateTime(2004-09-24T03:03:25Z)] TableOfContents
描述
Sending Binary Data to Standard Output Under Windows
输出2进制数据到Windows标准输出上
Credit: Hamish Lawson
问题 Problem
You want to send binary data (e.g., an image) to stdout, under Windows 在windows中输出2进制数据(例如图象文件)到标准输出,
解决 Solution
That's what the setmode function, in the platform-dependent msvcrt module in Python's standard library, is for:
Python标准库中平台相关的msvcrt模块有函数setmode,正可以解决这个任务:
讨论 Discussion
If you are reading or writing binary data, such as an image, under Windows, the file must be opened in binary mode (Unix doesn't make a distinction between text and binary modes). However, this is a problem for programs that write binary data to standard output (as a CGI program could be expected to do), because Python opens the sys.stdout file object on your behalf, normally in text mode.
在Windows中读写一个2进制文件,比如图象文件,必须使用2进制模式(rb参数)打开文件(Unix不区分2进制和文本文件). 然而,如果需要将2进制数据输出到标准输出(例如,CGI程序),由于Python打开sys.stdout文件对象时默认使用了文本模式 ,这样会产生问题。
You can have stdout opened in binary mode instead by supplying the -u command-line option to the Python interpreter. However, if you want to control this mode from within a program, you can use the setmode function provided by the Windows-specific msvcrt module to change the mode of stdout's underlying file descriptor, as shown in the recipe.
启动Python解释器时使用命令行参数-u可以解决这个问题,以2进制模式打开stdout. 如果要在程序中控制输出模式, 可以如上面脚本那样使用Windows系统下特有的Python模块msvcrt中的setmode函数。
参考 See Also
Documentation for the msvcrt module in the Library Reference.