StringIO和与'with'语句的兼容性(上下文管理器)

mpe*_*tis 44 python python-2.x with-statement contextmanager

我有一些带遗留函数的遗留代码,它将文件名作为参数并处理文件内容.下面是代码的工作传真.

我想要做的是不必使用我生成的一些内容写入磁盘以使用此遗留函数,因此我可以使用StringIO创建对象来代替物理文件名.但是,这不起作用,如下所示.

我认为StringIO是这样的方式.任何人都可以告诉我是否有一种方法可以使用这个遗留函数并在参数中传递一些东西,而不是磁盘上的文件但可以通过遗留函数对待它?遗留函数确实让with上下文管理器对filename参数值进行处理.

我在谷歌遇到的一件事是:http://bugs.python.org/issue1286,但这对我没有帮助......

from pprint import pprint
import StringIO

    # Legacy Function
def processFile(filename):
    with open(filename, 'r') as fh:
        return fh.readlines()

    # This works
print 'This is the output of FileOnDisk.txt'
pprint(processFile('c:/temp/FileOnDisk.txt'))
print

    # This fails
plink_data = StringIO.StringIO('StringIO data.')
print 'This is the error.'
pprint(processFile(plink_data))
Run Code Online (Sandbox Code Playgroud)

产量

这是输出FileOnDisk.txt:

['This file is on disk.\n']
Run Code Online (Sandbox Code Playgroud)

这是错误:

Traceback (most recent call last):
  File "C:\temp\test.py", line 20, in <module>
    pprint(processFile(plink_data))
  File "C:\temp\test.py", line 6, in processFile
    with open(filename, 'r') as fh:
TypeError: coercing to Unicode: need string or buffer, instance found
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 62

一个StringIO实例一个打开的文件了.open另一方面,该命令只接受文件名,以返回打开的文件.甲StringIO实例不适合作为一个文件名.

此外,您不需要关闭StringIO实例,因此也不需要将其用作上下文管理器.

如果您的所有遗留代码都可以使用文件名,则StringIO实例不是可行的方法.使用该tempfile模块生成临时文件名.

以下是使用contextmanager确保临时文件被清除后的示例:

import os
import tempfile
from contextlib import contextmanager

@contextmanager
def tempinput(data):
    temp = tempfile.NamedTemporaryFile(delete=False)
    temp.write(data)
    temp.close()
    try:
        yield temp.name
    finally:
        os.unlink(temp.name)

with tempinput('Some data.\nSome more data.') as tempfilename:
    processFile(tempfilename)
Run Code Online (Sandbox Code Playgroud)

  • @mpettis:我已经更新了我的答案以使用上下文管理器给出一个示例,该管理器将创建临时文件并一次性为您清理它. (2认同)

Jor*_*ley 6

你可以定义自己的开放功能

fopen = open
def open(fname,mode):
    if hasattr(fname,"readlines"): return fname
    else: return fopen(fname,mode)
Run Code Online (Sandbox Code Playgroud)

但是想要在完成后调用__exit__并且StringIO没有退出方法...

您可以定义要与此打开一起使用的自定义类

class MyStringIO:
     def __init__(self,txt):
         self.text = txt
     def readlines(self):
          return self.text.splitlines()
     def __exit__(self):
          pass
Run Code Online (Sandbox Code Playgroud)