Python sys.settrace will not track inline functions

I use the sys.settrace function to write a tracer for my program, which works fine, except that it doesn't seem to be called for inline functions like open ('filename.txt'). This behavior does not seem to be documented so I'm not sure if I am doing something wrong or this is the expected behavior. I use the Doug Hellmann "trace_calls_and_returns" code here as my trace function.

If I cannot do this with the definition, is there a way to track open () calls? I don’t want to use Linux strace, because it will work for the whole program (and not just for the part that I want to track), and will not show line numbers / python file names, etc. Another option that I have been considering is decapitating an open function through a shell, for example:

import traceback, __builtin__ def wrapped_open(*arg,**kw): print 'open called' traceback.print_stack() f = __builtin__.open(*arg,**kw) return f open = wrapped_open 

but it seemed to me very fragile.

Can anyone suggest a better way to do this?

+4
source share
1 answer

You will not be able to track compiled code imported into python, and open() not pure python, this is the C binding from the CPython part of Python Distribution .

Thus, the only way you should trace in open() is to switch to strace or the equivalent, but somehow go beyond what python itself can implement.

+3
source

Source: https://habr.com/ru/post/1489021/


All Articles