Hooking file open

Dale Strickland-Clark dale at riverhall.nospam.co.uk
Wed Nov 1 16:00:37 EST 2006


You might consider trapping calls to file() too, which is an alias for
open().

Also, I think I'd do my logging before calling the real function. It depends
how you want to deal with exceptions. 

Farshid Lashkari wrote:

> Hi,
> 
> My goal is to detect all (or most) file dependencies of a script (i.e.
> modules, dlls, data files). Currently, after a script is finished
> executing I use sys.modules to determine all module dependencies, and I
> use win32process.EnumProcessModules to determine DLL dependencies. This
> works reasonably well, however I would still like to detect dependencies
> from regular file open calls.
> 
> I did a little test by modifying __builtins__.open to point to a custom
> function that forwards the call to the original open function and saves
> the filename to a list. It seemed to work for simple test cases. Here is
> the code:
> 
> def open_hook(*args,**kwargs):
>      r = open_real(*args,**kwargs)
>      saveFileName(args[0])
>      return r
> 
> open_real = __builtins__.open
> __builtins__.open = open_hook
> 
> Is this a safe approach? Is there a more efficient way of doing this? I
> realize that some dependencies will still fall through my checks,
> especially file opens from C extensions, which is fine. I just want to
> be able to detect the most common use cases. Any other suggestions are
> appreciated.
> 
> -Farshid

-- 
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk




More information about the Python-list mailing list