开发者社区> 问答> 正文

继承自python的'File'类并定义自定义行为 - python2和3

我试图自定义文件句柄的行为在两个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
任何想法如何解决这个问题,还是有其他模式我应该遵循以获得我想要的结果?

展开
收起
一码平川MACHEL 2019-01-23 11:56:13 2238 0
1 条回答
写回答
取消 提交回答
  • 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
    
    2019-07-17 23:26:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载