sys.stdout.detach() results in ValueError

P

Peter Kleiweg

I want to write out some binary data to stdout in Python3. I
thought the way to do this was to call detach on sys.stdout. But
apparently, you can't. Here is a minimal script:

#!/usr/bin/env python3.1
import sys
fp = sys.stdout.detach()

Not yet using fp in any way, this script gives the following error:

Exception ValueError: 'underlying buffer has been detached' in

Same in Python 3.1.4 and Python 3.2.2

So, what do I do if I want to send binary data to stdout?
 
D

Dave Angel

I want to write out some binary data to stdout in Python3. I
thought the way to do this was to call detach on sys.stdout. But
apparently, you can't. Here is a minimal script:

#!/usr/bin/env python3.1
import sys
fp = sys.stdout.detach()

Not yet using fp in any way, this script gives the following error:

Exception ValueError: 'underlying buffer has been detached' in

Same in Python 3.1.4 and Python 3.2.2

So, what do I do if I want to send binary data to stdout?

sys.stdout.write( some_binary_data )

Why should you need to do some funny manipulation?

If you have some other unstated motivation, better ask a clearer question.
 
T

Terry Reedy

Dave Angel schreef op de 7e dag van de lentemaand van het jaar 2012:


TypeError: must be str, not bytes

Right, you can only send binary data to file opened in binary mode. The
default sys.stdout is in text mode. I am pretty sure that remains true
even if stdout is redirected. (You did not mention your OS.) You would
have to open such a file and make sys.stdout point to it.
sys.stdout = my_binary_file.
But why do that? Just open the file and write to it directly without the
above.
 
M

Mark Tolonen

Right, you can only send binary data to file opened in binary mode. The
default sys.stdout is in text mode. I am pretty sure that remains true
even if stdout is redirected. (You did not mention your OS.) You would
have to open such a file and make sys.stdout point to it.
sys.stdout = my_binary_file.
But why do that? Just open the file and write to it directly without the
above.

Write binary data to sys.stdout.buffer.

-Mark
 
B

Benjamin Peterson

Peter Kleiweg said:
Not yet using fp in any way, this script gives the following error:

Exception ValueError: 'underlying buffer has been detached' in

You're probably using print() or some such which tries to write to sys.stdout.
It's safest to just write to sys.stdout.buffer rather than using detach.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top