【问题标题】:Python's StringIO doesn't do well with `with` statementsPython 的 StringIO 不适用于 `with` 语句
【发布时间】:2012-08-15 06:00:57
【问题描述】:

我需要存根 tempfile 和 StringIO 看起来很完美。只是这一切都失败了:

In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()

--> AttributeError: StringIO instance has no attribute '__exit__'

提供预设信息而不是读取具有不确定内容的文件的常用方法是什么?

【问题讨论】:

    标签: python unit-testing stringio stubs


    【解决方案1】:

    StringIO 模块早于with 语句。既然 StringIO has been removed in Python 3 反正你可以用它的替代品 io.BytesIO:

    >>> import io
    >>> with io.BytesIO(b"foo") as f: f.read()
    b'foo'
    

    【讨论】:

    • 请注意,io 模块在 Python 2.6 中是纯 Python,而 Python 2.7 使用 Python 3.1 的快速 C 实现。因此,仅对于 Python 2.6,使用 io.BytesIO 会导致性能下降。
    • 未删除,来自 Python 3.0 的新增功能:StringIO 和 cStringIO 模块已消失。相反,导入 io 模块并分别对文本和数据使用 io.StringIO 或 io.BytesIO。
    【解决方案2】:

    这个猴子补丁在 python2 中对我有用。在初始化例程中调用 monkeypatch。

    import logging
    from StringIO import StringIO
    logging.basicConfig(level=logging.DEBUG if __debug__ else logging.INFO)
    
    def debug(*args):
        logging.debug('args: %s', args)
        return args[0]
    
    def monkeypatch():
        '''
        allow StringIO to use `with` statement
        '''
        StringIO.__exit__ = debug
        StringIO.__enter__ = debug
    
    if __name__ == '__main__':
        monkeypatch()
        with StringIO("this is a test") as infile:
            print infile.read()
    

    试运行:

    jcomeau@aspire:~/stackoverflow/12028637$ python test.py 
    DEBUG:root:args: (<StringIO.StringIO instance at 0xf73e76ec>,)
    this is a test
    DEBUG:root:args: (<StringIO.StringIO instance at 0xf73e76ec>, None, None, None)
    jcomeau@aspire:~/stackoverflow/12028637$
    

    【讨论】:

    • 请注意,这仅适用于纯 python 版本,不适用于 cStringIO 版本,因此在 2.7 中让快速 StringIO 与with 配合使用没有任何帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多