import sys
print(sys.stdin)
print(type(sys.stdin))
print(sys.stdin.name)
print(sys.stdin.__dict__)
执行上述操作时,输出如下:
<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
<class '_io.TextIOWrapper'>
<stdin>
{'mode': 'r'}
因此,从上面的代码片段和输出中,我可以看到name
是代表_io.TextIOWrapper
的sys.stdin
实例的属性。从io.TextIOWrapper
的文档中(例如,通过$ pydoc io.TextIOWrapper
),它确实将name
列为数据描述符。但是,无论出于何种原因,name
都不会在其__dict__
中显示为项目。
例如,当我使用例如手动创建io.TextIOWrapper
的实例时:
import io
a = io.TextIOWrapper(io.BytesIO())
print(a)
a.name
<_io.TextIOWrapper encoding='UTF-8'>
被打印。但是a.name
行抛出错误:AttributeError: '_io.BytesIO' object has no attribute 'name'
;我曾期望的AttributeError
,但我没想到它是_io.BytesIO
对象。
然后我尝试创建一个子类并手动附加一个name
属性,如下所示:
import io
class NamedTextIOWrapper(io.TextIOWrapper):
def __init__(self, buffer, name=None, **kwargs):
self.name = name
io.TextIOWrapper.__init__(self, buffer, **kwargs)
input = io.BytesIO('abc')
stdin = NamedTextIOWrapper(input, name='<stdin>', encoding='utf-8')
print(stdin.name)
但是它遇到了:AttributeError: attribute 'name' of '_io.TextIOWrapper' objects is not writable
。
[理想情况下,我还希望能够在手动实例化的mode
对象中也维护sys.stdin
实例中似乎可用的io.TextIOWrapper
属性。而且,对于sys.stdout
等效项,我认为除了name
应该只设置为'<stdout>'
以及mode
到'w'
之外,其他都是一样的。