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)
你可以定义自己的开放功能
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)
归档时间: |
|
查看次数: |
21834 次 |
最近记录: |