`sys.stdout` has no attribute `buffer`
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
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.
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 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.