file modes

Albert Hopkins ahopkins at
Tue Feb 1 12:47:44 EST 2000

On Tue, 1 Feb 2000 16:06:41 -0000, Dave Berkeley <dave at> wrote:
>Hi All
>I'm trying to write a CGI script that returns image data instead of HTML.
>The problem is that sys.stdout is opened in text mode, and I need to write
>in binary. As a result each embedded "\n" in the image data gets expanded
>into "\r\n", corrupting the image. I have tried the following:
>out = os.fdopen(sys.stdout.fileno(), "wb")
>out.write("Content-Type: application/octet-stream\r\n\r\n")

Are you sure?  I've successfully done this on
Apache and IIS with the following code fragment:

sys.stdout.write("Content-type: image/jpeg\n\n")

I'm not sure why you are [re]opening sys.stdout but it should be open
when your CGI is called.

>But the "wb" mode does not seem to override the underlying mode of stdout.
>I'm using Python 1.5.2 on Win 98 SE, talking to Apache 1.3.9.
>How can I write to stdout in binary mode?
>Dave Berkeley


Albert Hopkins
Sr. Systems Specialist
Dynacare, Inc
ahopkins at

More information about the Python-list mailing list