log caller

M

Matthew Peter

Is it possible to print the function calls to a module? Like:

test.py
import mymod
print mymod.x()


mymod.py
# each time a function is called we print out the called function and module
print 'Func call: %s from %s' % (???, ???)

def x():
return 'hello'

Where would I pick up the ??? variables? A brief example would be nice too :) Thanks
in advance!



____________________________________________________________________________________
The fish are biting.
Get more visitors on your site using Yahoo! Search Marketing.
http://searchmarketing.yahoo.com/arp/sponsoredsearch_v2.php
 
A

attn.steven.kuo

Is it possible to print the function calls to a module? Like:

test.py
import mymod
print mymod.x()

mymod.py
# each time a function is called we print out the called function and module
print 'Func call: %s from %s' % (???, ???)

def x():
return 'hello'

Where would I pick up the ??? variables? A brief example would be nice too :) Thanks
in advance!



You can use a decorator to wrap the function. You can use
sys._getframe or
inspect.stack to get information about the caller. The examples from
the decorator module are very useful:

http://www.phyast.pitt.edu/~micheles/python/documentation.html

If for some reason you can't edit mymod.py to add the decorators, you
can still wrap the function:

import mymod
import inspect

try:
from functools import update_wrapper
except ImportError:
def decorator_trace(f):
def newf():
caller = inspect.stack()[1]
print 'Caller is line %d of %s' % (caller[2], caller[1])
print 'Calling: %s from %s' % (f.__name__, f.__module__)
return f()
newf.__name__ = f.__name__
newf.__dict__.update(f.__dict__)
newf.__doc__ = f.__doc__
newf.__module__ = f.__module__
return newf
else:
def decorator_trace(f):
def newf():
caller = inspect.stack()[1]
print 'Caller is line %d of %s' % (caller[2], caller[1])
print 'Calling: %s from %s' % (f.__name__, f.__module__)
return f()
return update_wrapper(newf, f)


mymod.x = decorator_trace(mymod.x)
greetings = mymod.x()
print greetings


but this approach has the shortcoming mentioned in the article.
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top