質問

Let's imagine, I've got a module foo.py with declared a function foofunc:

def foofunc():
    # smart things
    return

And two different modules — bar.py and spam.py, where exists code which directly executes the function from foo module.

# `bar` module. All rights reserved.

from foo import foofunc


def run_foofunc():
     return foofunc()

The same thing in another module:

# `spam` module. All rights reserved.

from foo import foofunc


def run_foofunc():
    return foofunc()

I need to know where is executed the function without knowledge of possible places. Something like:

def foofunc():
    print inspect.executedfrom()

Will do something like that in standard output

<pack.bar.run_foofunc>

Does it something similar in real world?

役に立ちましたか?

解決

Running the risk of not answering the actual question, you wrote that you need it for research and debugging.

I think the traceback module is just great for that.

import traceback
traceback.print_stack()

Also take a look at pdb, it allows you to interactively step through your code during runtime.

他のヒント

test.py:

import inspect    

def foofunc():
    frame, filename, line_number, function_name, lines, index = inspect.getouterframes(
        inspect.currentframe())[1]

    print(filename, line_number, function_name)
    return

foo.py:

import test
def run_foofunc():
    test.foofunc()

run_foofunc()

yields

('/tmp/foo.py', 3, 'run_foofunc')

Here is a possible implementation of executed_from:

import inspect

def executed_from():
    f = inspect.currentframe().f_back.f_back
    return "%s.%s" % (inspect.getmodule(f).__name__, f.f_code.co_name)

During wait for your answers I found my own answer. This issue possible to resolve by raising an exception in debugged function and make out the traceback layer by layer. This approach is bad in general because it is stops execution, but not bad in the my particular case. And besides it is very pythonic and easy to clean.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top