【问题标题】:Writing bytes to standard output in a way compatible with both, python2 and python3以兼容 python2 和 python3 的方式将字节写入标准输出
【发布时间】:2014-07-18 21:35:01
【问题描述】:
我想要一个函数返回一个文件对象,我可以用它将二进制数据写入标准输出。在python2中sys.stdout就是这样一个对象。在 python3 中是sys.stdout.buffer。
检索此类对象以使其适用于 python2 和 python3 解释器的最优雅/首选方法是什么?
是检查sys.stdout.buffer 是否存在的最佳方法(可能使用inspect 模块),如果存在,则返回它,如果不存在,假设我们在python2 上并返回sys.stdout?
【问题讨论】:
标签:
python
python-3.x
binary
stdout
【解决方案1】:
无需测试,直接使用getattr():
# retrieve stdout as a binary file object
output = getattr(sys.stdout, 'buffer', sys.stdout)
这会检索sys.stdout 上的.buffer 属性,但如果它不存在(Python 2),它将返回sys.stdout 对象本身。
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>'>
考虑到在 Python 2 中,stdout 仍然以文本模式打开,换行符在写入时仍然转换为 os.linesep。 Python 3 BufferedWriter 对象不会为您执行此操作。