settrace doesn't trace builtin functions

S

skunkwerk

Hi,
I've been using the settrace function to write a tracer for my program, which is working great except that it doesn't seem to work for built-in functions, like open('filename.txt'). This doesn't seem to be documented, so I'm not sure if I'm doing something wrong or that's the expected behavior.

If settrace's behavior in this regard is fixed, is there any way to trace calls to open()?
I don't want to use Linux's strace, as it'll run for whole program (not just the part I want) and won't show my python line numbers/file names, etc.
The other option I considered was monkey-patching the open function througha wrapper, like:

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

but that seemed very brittle to me.

Could someone suggest a better way of doing this?

thank you,
imran
 
S

Skip Montanaro

I've been using the settrace function to write a tracer for my program,which is working great except that it doesn't seem to work for built-in functions, like open('filename.txt'). This doesn't seem to be documented, soI'm not sure if I'm doing something wrong or that's the expected behavior.

I believe that's expected behavior. Stuff written in Python is
traced. C functions are not. It's been a whole lot of years since I
looked at that code though, so I might be misremembering.
The other option I considered was monkey-patching the open function through a wrapper ... but that seemed very brittle to me.

For debugging purposes, practicality beats purity. I trust you won't
be tracing in a production environment, so fragility shouldn't be a
major concern. Monkey patching seems entirely appropriate to me.

Python 2.x:
.... return _open(name, mode, buffering)
....<function open at 0x82afa3c>

Python 3.x:
.... errors=None, newline=None, closefd=True, opener=None):
.... return _open(file, mode, buffering, encoding, errors, newline,
closefd, opener)
....<function open at 0x1010c18c8>

You can, of course, do this for more builtins. Presuming you can get
a handle on a function's namespace and modify it, you should be able
to perform the same trick for most functions or methods written in C.
.... return sys._settrace(*args, **kwds)
....
Totally untested. No warranties expressed or implied. YMMV... etc, etc

Skip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top