ipykernel icon indicating copy to clipboard operation
ipykernel copied to clipboard

`sys.stdout` has no attribute `buffer`

Open MarcoGorelli opened this issue 4 years ago • 3 comments

If I run

import sys
sys.stdout.buffer

in a Python or a IPython shell, it works fine:

In [1]: import sys

In [2]: sys.stdout.buffer
Out[2]: <_io.BufferedWriter name='<stdout>'>

However, when running in a Jupyter Notebook, I get:

AttributeError                            Traceback (most recent call last)
/var/folders/hp/166tdb592211tp23nb_rgmqw0000gp/T/ipykernel_3131/3028238189.py in <module>
----> 1 sys.stdout.buffer

AttributeError: 'OutStream' object has no attribute 'buffer'

Some diagnostics:

$ pip freeze | grep ipykernel
ipykernel==6.4.1
$ python --version
Python 3.9.6

Noticed when looking into https://github.com/psf/black/issues/2516

MarcoGorelli avatar Oct 18 '21 20:10 MarcoGorelli

From the TextIO docs:

[buffer] is not part of the TextIOBase API and may not exist in some implementations.

So it is not guaranteed to be defined, and should not be relied upon. Assuming its presence isn't a safe assumption.

We can patch it in, though, but it should be considered a bug anywhere sys.stdout.buffer is accessed unconditionally.

minrk avatar Nov 04 '21 10:11 minrk

There is a suggestion on stackoverflow to use sys.stdout.buffer instead of sys.stdout in the first argument of the write method of xml.etree.ElementTree. To write the xml text to stdout.

In light of this issue, what would the correct first argument of the write method be if sys.stdout.buffered might not exist?

jimka2001 avatar Nov 29 '23 11:11 jimka2001

@jimka2001 In the SO case the write method takes a file object https://docs.python.org/3/glossary.html#term-file-object

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.

Googling gives https://github.com/psf/black/issues/2516 as a similar issue

So you need to be able to access the Outstream object and see what it can do.

bestlem avatar Nov 29 '23 13:11 bestlem