On 11/19/2010 7:48 PM, Glenn Linderman wrote:
One of the cgitb outputs from my attempt to serve the binary file claims that my CGI script's output file (which comes from a subprocess PIPE) is a TextIOWrapper with encoding cp1252.  Maybe that is the default that comes when a new Python is launched, even though it gets a subprocess PIPE as stdout?

So the rather gross code below solves the cp1252 stdout problem, and also permits both strings and bytes to be written to the same file, although those two features are separable.  But now that I've worked around it, it seems that subprocesss should somehow ensure that launched Python programs know they are working on a binary stream?  Of course, not all programs launched are Python programs... so maybe it should be a documentation issue, but it seems to be missing from the documentation.

#####################################
if sys.version_info[ 0 ] == 2:
    class IOMix():
        def __init__( self, fh, encoding="UTF-8"):
            self.fh = fh
        def write( self, param ):
            if isinstance( param, unicode ):
                self.fh.write( param.encode( encoding ))
            else:
                self.fh.write( param )
#####################################
if sys.version_info[ 0 ] == 3:
    class IOMix():
        def __init__( self, fh, encoding="UTF-8"):
            if hasattr( fh, 'buffer'):
                self.bio = fh.buffer
                fh.flush()
                self.last = 'b'
                import io
                self.txt = io.TextIOWrapper( self.bio, encoding, None, '\r\n')
            else:
                raise ValueError("not a buffered stream")
        def write( self, param ):
            if isinstance( param, str ):
                self.last = 't'
                self.txt.write( param )
            else:
                if self.last == 't':
                    self.txt.flush()
                self.last = 'b'
                self.bio.write( param )
#####################################