如何在python中跟踪callee中的调用者详细信息

时间:2015-05-12 12:20:27

标签: python

我正在调用位于模块(module2.py)中的函数来自另一个类,该类位于名为module1.py的模块中

例如:

*module2.py*

def test_envconfig():
     #I have to get the name/parent base class details of caller to this function
     #print the caller function name is ?
     #print the location of the caller function is ?
     return "user"

*module1.py*

class MyClass(SomeOther):
    def process(self):
         module2.test_envconfig()

在上面的示例中, MyClass 中的处理方法调用 module1 中的 test_envconfig 函数。所以,我必须获取有关的详细信息 test_envconfig 函数中的调用者(此处为 MyClass - > baseclass SomeOther )(包括基类层次结构详细信息)

那么,如何在被调用者(test_envconfig)中获取调用函数(MyClass - > SomeOther)的详细信息?

修改:执行此操作的原因:*

动态地说,该体系结构是为与多个项目共享的情况而设计的。我们有大量模块调用函数test_envconfig来激活环境。对于来自特定位置的少数模块应该被激活到环境(用户)在呼叫test_envconfig时,应该为环境激活来自其他位置的其他几个模块' prod'当它调用相同的test_envconfig时。基于模块的位置,环境激活发生。 test_envconfig负责通过必要的配置激活环境。

您可以帮助查找test_envconfig内的来电者位置和姓名详情吗?

1 个答案:

答案 0 :(得分:0)

经过几次尝试后我得到了答案。

对我有用的解决方案。欢迎您提出建议。

module2.py

def test_envconfig():
     import inspect
     for frame, filename, line_num, func, source_code, source_index in inspect.stack():
         if 'tests/unittests/capital/' in filename:
             print 'The Test env is activated for %s' % (filename)
     return "user"
相关问题