如何使用名称属性实例化io.TextIOWrapper对象?

问题描述 投票:1回答:1
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.TextIOWrappersys.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'之外,其他都是一样的。

python stream stdout stdin
1个回答
1
投票
© www.soinside.com 2019 - 2024. All rights reserved.