What interface is a ‘Popen.stdout’ presenting?
Ben Finney
ben+python at benfinney.id.au
Wed Dec 23 20:24:17 EST 2015
Howdy all,
When I want to wrap a binary stream to provide a text stream, such as
the ‘Popen.stdout’ attribute from a subprocess, I can use
‘io.TextIOWrapper’.
That works on Python 3::
$ python3
Python 3.4.4rc1 (default, Dec 7 2015, 11:09:54)
[GCC 5.3.1 20151205] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import io
>>> gnupg_subprocess = subprocess.Popen(["/usr/bin/gpg", "--version"], stdout=subprocess.PIPE)
>>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout)
>>> type(gnupg_stdout)
<class '_io.TextIOWrapper'>
but not Python 2::
$ python2
Python 2.7.11 (default, Dec 9 2015, 00:29:25)
[GCC 5.3.1 20151205] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import io
>>> gnupg_subprocess = subprocess.Popen(["/usr/bin/gpg", "--version"], stdout=subprocess.PIPE)
>>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'readable'
I'm trying to write code that, as far as practicable, works unchanged on
Python 2 and Python 3.
How do I wrap an arbitrary byte stream – already opened, such as a
‘Popen.stdout’ attribute – in a text wrapper with a particular encoding?
--
\ “With Lisp or Forth, a master programmer has unlimited power |
`\ and expressiveness. With Python, even a regular guy can reach |
_o__) for the stars.” —Raymond Hettinger |
Ben Finney
More information about the Python-list
mailing list