How do I return binary data from a python CGI called from CGIHTTPServer?

Mark Wright mwright at pro-ns.net
Wed Jun 6 16:37:11 EDT 2001


dirck at pacbell.net (Dirck Blaskey) wrote in message news:<6c8b7eb9.0106061043.57104307 at posting.google.com>...
> "Alex Martelli" <aleaxit at yahoo.com> wrote in message news:<9f96kb01mq8 at enews1.newsguy.com>...
> > "Mark Wright" <mwright at pro-ns.net> wrote in message
> > news:f9ff3f62.0106011427.6243e5e9 at posting.google.com...
> >     ...
> > > But my original problem/question remains: how does a CGI program
> > > return binary data on windows?  Is it even possible?  The problem is
> > 
> > python.exe must be run with option -u, to have binary standard input
> > and output streams, rather than text ones as it has by default.
> 
> In order to send or receive binary files from Python CGIs under IIS 
> (and Xitami) under Win32, I had to do the following in the scripts,
> instead of using the -u option:
> 
> try:
>     import msvcrt
>     msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
>     msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)    
> except:
>     pass
> 
> The -u option broke something in cgi.py, I don't remember what.

Perfect.  This is exactly what I was looking for.  And it has the
added benefit of allowing me to print headers using single '\n' and
then switching the mode to binary when I print the binary page
content.

Contrary to a prior post, there is no bug in popen, just one in the
documentation.  Although the .hlp file doesn't say so, like open(),
popen()'s 2nd argument can include the 'b' attribute to indicate that
a binary input stream is being opened.  If 'b' isn't specified, then
the calling process will not see any data past the ctrl-z.  It's not
enough to call python with the '-u' directive (or set the mode as
above).  If you popen a process in python, you must use 'rb' rather
than 'r' if your client returns a ctrl-z.

This is why CGIHTTPServer is truncating the data at the ctrl-z - it
used popen(filename, 'r') rather than popen(filename, 'rb').  It seems
to me that this should be changed in CGIHTTPServer.


Mark



More information about the Python-list mailing list