log caller - Python
This is a discussion on log caller - Python ; 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' % ...
-
log caller
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...dsearch_v2.php
-
Re: log caller
On Jun 27, 2:42 pm, Matthew Peter <survivedsu...@yahoo.com> wrote:
> 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...mentation.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.
--
Hope this helps,
Steven
Similar Threads
-
By Application Development in forum Home Automation
Replies: 5
Last Post: 10-19-2007, 09:11 PM
-
By Application Development in forum c++
Replies: 9
Last Post: 08-13-2007, 04:57 PM
-
By Application Development in forum Python
Replies: 0
Last Post: 06-26-2007, 12:23 PM
-
By Application Development in forum DOTNET
Replies: 0
Last Post: 07-21-2005, 04:24 PM
-
By Application Development in forum basic.visual
Replies: 0
Last Post: 12-27-2003, 11:12 AM