Modifying a built-in function for logging purposes

Fredrik Lundh fredrik at pythonware.com
Sun May 15 01:52:42 EDT 2005


qwweeeit at yahoo.it wrote:

> I wonder if it is possible to change (temporarily) a built-in function
> for logging purposes.
> Let me explain:
> I want to log all the 'open' operations, recording the file to be
> opened, the "mode" (r/w/a...) and (possibly) the module which made the
> call.

import sys
import __builtin__ # note: no plural s

old_open = __builtin__.open

def myopen(*args):
    code = sys._getframe(1).f_code
    print "OPEN", args, "FROM", code.co_name, "IN", code.co_filename
    return old_open(*args)

__builtin__.open = myopen

this only handles file opens that goes via the "open" function, of course.
to handle all opens, including internal operations (e.g. imports), you're
probably better off using an external tool (e.g. strace, filemon, or some-
thing similar).

</F>






More information about the Python-list mailing list