Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python';s StringIO没有';不能很好地处理'with'语句_Python_Unit Testing_Stringio_Stubs - Fatal编程技术网

Python';s StringIO没有';不能很好地处理'with'语句

Python';s StringIO没有';不能很好地处理'with'语句,python,unit-testing,stringio,stubs,Python,Unit Testing,Stringio,Stubs,我需要存根tempfile和StringIO看起来很完美。只是所有这一切都因遗漏而失败: In [1]: from StringIO import StringIO In [2]: with StringIO("foo") as f: f.read() --> AttributeError: StringIO instance has no attribute '__exit__' 提供固定信息而不是读取内容不确定的文件的通常方法是什么?StringIO模块早于with语句。由于Str

我需要存根
tempfile
StringIO
看起来很完美。只是所有这一切都因遗漏而失败:

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

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

提供固定信息而不是读取内容不确定的文件的通常方法是什么?

StringIO模块早于
with
语句。由于StringIO无论如何都可以使用它的替代品:


这个monkeypatch在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$
jcomeau@aspire:~/stackoverflow/12028637$python test.py
调试:根:参数:(,)
这是一个测试
调试:根:参数:(,无,无,无)
jcomeau@aspire:~/stackoverflow/12028637$

注意,
io
模块在Python2.6中是纯python的,而Python2.7使用Python3.1的快速C实现。因此,仅对Python2.6而言,使用
io.BytesIO将导致性能下降。在Python3.0中的新增功能中,没有删除:StringIO和cStringIO模块消失了。相反,导入io模块,并分别对文本和数据使用io.StringIO或io.BytesIO。请注意,这只适用于纯python版本,而不适用于cStringIO版本,因此在2.7中让fast StringIO与
配合使用没有任何帮助
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$