How to designate sys.stdout for binary output in win32?

John Machin sjmachin at lexicon.net
Mon May 5 08:16:09 EDT 2003


zERo <zERo at nowhere.com> wrote in message news:<Xns9371E2027B4E3zERo at 204.127.199.17>...
> 
> My current application uses Python to generate an image.  Instead of
> creating a file, it could be used to send raw output.  By using
> appropriate html headers, I could use it as a CGI app and have it
> display directly in a browser.  Thus, the requirement of 'binary'
> output to sys.stdout, so the browser can act upon it.
> 
> I can think of other uses this may have, an example would be akin
> to Unix filter apps, where the Python app would take the input and
> pass along modified output (albeit in 'binary' form) as stdout.
> 
> After reading your post, it got me thinking.  I now believe that the
> indication I got that sys.stdout is a Pyshell.PseudoFile instance
> comes from the fact that I tried to simplify it into a test-case and
> *WAS* checking it out in a PyShell, and hence would receive that
> indication.  Uugggh!! back to square one...
> 
> Thanks for your input.  BTW, it should not matter what the receiving
> app is, so long as the previous stage sends data out on stdout and the
> receiving app receives it on stdin, right???

No, it shouldn't matter, so long as the receiving app can handle the
raw input data.

In any case, it seems your problem is more apparent than real. The
following code actually does work when run at the Windows 2000 cmd.exe
prompt by

python stdoutb.py >bin2.txt

i.e. the \0 is in the output file and there's no \r.

What I don't understand is why the fdopen way (meth = 1) doesn't work;
there's a \r in the output.

import sys, os, msvcrt
test_str = "abc\0def\npqr"
sso_fd = sys.stdout.fileno()
sys.stderr.write("sso_fd=%d\n" % sso_fd)
meth = 2
if meth == 1:
   f = os.fdopen(sso_fd, "wb")
   sys.stdout = f
elif meth == 2:
   msvcrt.setmode(sso_fd, os.O_BINARY)
sys.stdout.write(test_str)




More information about the Python-list mailing list