How to print to stdout in binary

brianbird at my-deja.com brianbird at my-deja.com
Fri Jul 7 06:49:32 EDT 2000


I was actually testing under WindowsNT, but using Linux isn't a problem
either. I tried your test under both using an image file (test.gif)
piping into a new file "test2.gif"

Under linux the new file was identical and remained as an image
viewable from a web browser
Under windows, the new file was identical (according to Textpad's
compare function) but in Internet Explorer the image appeared partially
corrupted - but it still appeared as an image which is more than I got
before :-)

Does this mean sys.stdout will write in whatever mode it thinks is
correct or does it just output the exact string you give it to output?
(A normal file can output two different strings into a text file
depending on whether you tell it to write in binary or ascii)

However, I think this means that the problem I had with displaying the
image in an <IMG SRC="test.py"> HTML tag is probably not to do with the
mode of python stdout after all. Probably a webserver will output a
header before an image file which means the script will need to do that
as well. This probably isn't really the forum to ask, but does anyone
happen to know what this might be? :)

In article <3965408E.DDD4A2 at pehr.net>,
  pehr at pehr.net wrote:
> What platform are you developing on?
> under linux I did the following in a file "t.py":
>
> 	import sys
> 	x = open("python.prc", "rb").read()
> 	sys.stdout.write(x)
>
> [pehr at morseall python]$ python t.py  > t
> [pehr at morseall python]$ diff python.prc t
>
> I didn't get any differences when I did this.
> Would you try it and see how it goes?
>
> 	-pehr
>
> brianbird at my-deja.com wrote:
> >
> > I've seen similar questions to this posted in other language forums,
> > but I've not seen anything for Python:
> >
> > Does anyone know how to tell python to print the sys.stdout in
binary
> > rather than plain text. It's mode is set as 'w' and I can't seem to
> > change it.
> >
> > I'm experimenting with a cgi script which I want to output an image
to
> > the browser so that the HTML file can have:
> > <IMG SRC="test.cgi">
> > and the resulting output of the script is an image.
> > I've currently got:
> >
> > f = open("test.jpg","rb")
> > bytes = f.read()
> > f.close()
> > sys.stdout.print(bytes)
> >
> > but I want the output to print in binary mode so that the image can
be
> > displayed correctly. If I was printing to another file I could open
it
> > with:
> >
> > f2 = open("test2.jpg","wb")
> > f2.write(bytes)
> > f2.close()
> >
> > so is there any way to do this with stdout?
> >
> > Thanks
> >
> > Sent via Deja.com http://www.deja.com/
> > Before you buy.
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list