How can I add a callback or hook to a Python builtin class method? -


i trying gather information on files being opened , closed can keep track of processes doing what. work users not systematically use custom i/o functions , methods change behavior of builtins.

i figured out way change open function. might not optimal, works.

import logging import os import sys import io import logging import __builtin__   def custom_open(file_name, access_mode, buffering = 0):     logging.debug('opening file ' + file_name)         return __builtin__.open(file_name, access_mode, buffering)  logging.getlogger('').setlevel(logging.debug)  open = custom_open  f = open('workfile', 'w')  f.write('this test\n')         f.close() 

what change behavior of file close method. tried few things nothing works.

to elaborate little on comment, since nobody else seems submitting answer:

# create custom file class class custom_file(file):      def close(self):          # logging         super(file, self).close()  # create custom file opener def custom_open(*args, **kwargs):     # logging     return custom_file(*args, **kwargs)  # set local `open` point custom_open fn open = custom_open 

implicit here (and didn't research wrong) open('bla') calling out file.__init__('bla'), careful there.

edit: might want make sure you're overriding other methods on file, flush or else cause python touch disk.


Popular posts from this blog