Writing bytes to standard output in a way compatible with both, python2 and python3

与世无争的帅哥 提交于 2019-12-23 15:00:00

问题


I want a function returning a file object with which I can write binary data to standard output. In python2 sys.stdout is such an object. In python3 it is sys.stdout.buffer.

What is the most elegant/preferred way to retrieve such an object so that it works for both, the python2 and the python3 interpreter?

Is the best way to check for existance of sys.stdout.buffer (probably using the inspect module) and if it exists, return it and if it doesnt, assume we are on python2 and return sys.stdout instead?


回答1:


No need to test, just use getattr():

# retrieve stdout as a binary file object
output = getattr(sys.stdout, 'buffer', sys.stdout)

This retrieves the .buffer attribute on sys.stdout, but if it doesn't exist (Python 2) it'll return the sys.stdout object itself instead.

Python 2:

>>> import sys
>>> getattr(sys.stdout, 'buffer', sys.stdout)
<open file '<stdout>', mode 'w' at 0x100254150>

Python 3:

>>> import sys
>>> getattr(sys.stdout, 'buffer', sys.stdout)
<_io.BufferedWriter name='<stdout>'>

Take into account that in Python 2, stdout is still opened in text mode, newlines are still translated to os.linesep when writing. The Python 3 BufferedWriter object won't do this for you.



来源:https://stackoverflow.com/questions/23932332/writing-bytes-to-standard-output-in-a-way-compatible-with-both-python2-and-pyth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!