问题描述
我想要一个函数,该函数返回一个文件对象,利用该对象可以将二进制数据写入标准输出.在python2中,sys.stdout
是这样的对象.在python3中,它是sys.stdout.buffer
.
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
.
检索此类对象以使其同时适用于python2和python3解释器的最优雅/首选的方法是什么?
What is the most elegant/preferred way to retrieve such an object so that it works for both, the python2 and the python3 interpreter?
是检查sys.stdout.buffer
是否存在的最佳方法(可能使用inspect
模块),如果存在,则将其返回,如果不存在,则假定我们在python2上并返回sys.stdout
? >
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?
推荐答案
无需测试,只需使用 getattr()
:
No need to test, just use getattr()
:
# retrieve stdout as a binary file object
output = getattr(sys.stdout, 'buffer', sys.stdout)
这会检索sys.stdout
上的.buffer
属性,但是如果该属性不存在(Python 2),它将返回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>'>
请注意,在Python 2中,stdout
仍以文本模式打开,编写时换行符仍会转换为os.linesep
. Python 3 BufferedWriter
对象不会为您完成此操作.
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.
这篇关于以与python2和python3兼容的方式将字节写入标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!