我试图自定义文件句柄的行为在两个python 2.7和python 3.x(至少>=3.6)的库中。
我正在实现的自定义行为要求在close调用方法时执行某些操作(direct(fh.close())或作为__exit__()方法的结果)。
我还试图添加一个额外的方法 - 让我们调用它custom_copy()。
我理想是的是给我的用户一个他们可以正常使用的文件句柄(读/读/写/ ...),但在幕后也有一些特殊的逻辑。
这是我目前正在使用的...
from os import fsync
def custom_open(filepath, mode='rt', args *kwargs):
# Open the file normally using open_args
orig_file_handle = open(filepath, mode, *args, **kwargs) # pylint: disable=star-args
# Preserve original close function
original_close_fn = orig_file_handle.close
# Create a custom close function
def custom_close_fn(*args, **kwargs):
original_close_fn(*args, **kwargs)
print("Do Something Custom")
orig_file_handle.close = custom_close_fn
# Add custom_copy function
def custom_copy_fn(*args, **kwargs):
if orig_file_handle.closed:
raise ValueError("I/O operation on closed file")
# Ensure buffer has been flushed before rsync
orig_file_handle.flush()
fsync()
return _my_custom_copy(filepath, *args, **kwargs)
orig_file_handle.custom_copy = custom_copy_fn
return orig_file_handle
上面的代码可以使用python3.7.0,但是python2.7.8它失败了
orig_file_handle.close = custom_close_fn
E AttributeError: 'file' object attribute 'close' is read-only
我还尝试了另一种涉及SubClassing的方法type(orig_file_handle),但是还有其他一些问题......
def custom_open(filepath, mode='rt', open_args=None):
open_args = open_args or {}
open_args['mode'] = mode
# Open the file normally using open_args
orig_file_handle = open(filepath, **open_args) # pylint: disable=star-args
class CustomFile(type(orig_file_handle)):
def __init__(self, file_handle):
# pylint: disable=super-init-not-called
self.__dict__ = file_handle.__dict__.copy()
def close(self, *args, **kwargs):
# Execute normal file handle close
super(CustomFile, self).close(*args, **kwargs)
print("Do Something Custom")
def custom_copy(self, *args, **kwargs):
if self.closed: # pylint: disable=no-member
raise ValueError("I/O operation on closed file")
self.flush() # pylint: disable=no-member
fsync()
return _my_custom_copy(filepath, *args, **kwargs)
return CustomFile(orig_file_handle)
在python2.7.8这失败了
self.__dict__ = file_handle.__dict__.copy()
E AttributeError: 'file' object has no attribute '__dict__'
而在python3.7.0它失败了
self.__dict__ = file_handle.__dict__.copy()
E AttributeError: attribute '__dict__' of '_io._IOBase' objects is not writable
任何想法如何解决这个问题,还是有其他模式我应该遵循以获得我想要的结果?
class CustomFile:
def __init__(self, file_handle):
# pylint: disable=super-init-not-called
self._f = file_handle
def close(self, *args, **kwargs):
self._f.close(*args,**kwargs)
print("Do Something Custom")
self.closed = True
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。