Modifying a built-in function for logging purposes

Bengt Richter bokr at oz.net
Sun May 15 05:02:38 EDT 2005


On Sun, 15 May 2005 07:52:42 +0200, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>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).
>
I should have mentioned that for my version of the same thing.

I wonder what the chances are for a hook to catch all opens.
My feeling is that file system access should be virtualized
to look like a unix directory tree, with all manner of duck-typed
file-system-like things mountable in the tree, and built-in open
would refer to the open of a particular virtually mounted file system
that might be configured to default as now. Anyway, lots of stuff
would become possible... e.g., msys, the MinGW-related shell provides
some of this capability, virtualizing windows partitions as /c/* /d/* 
and so forth, as well as having virtual mounts of various subdir trees.
Good night...

Regards,
Bengt Richter



More information about the Python-list mailing list