4.13 Sending Binary Data to Standard Output Under Windows
Credit: Hamish Lawson
4.13.1 Problem
You want to
send binary data (e.g., an image) to stdout, under
Windows.
4.13.2 Solution
That's what the setmode function,
in the platform-dependent msvcrt module in
Python's standard library, is for:
import sys
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno( ), os.O_BINARY)
4.13.3 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.
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.
4.13.4 See Also
Documentation for the msvcrt module in the
Library Reference.
|