2012-08-03 2 views
7

파이썬에서 특정 함수의 호출자에 대한 정보를 얻고 싶습니다. 예 :파이썬에서 함수 호출자 정보 가져 오기

class SomeClass(): 
    def __init__(self, x): 
     self.x = x 
    def caller(self): 
     return special_func(self.x) 

def special_func(x): 
    print "My caller is the 'caller' function in an 'SomeClass' class." 

파이썬에서는 가능합니까?

답변

10

예, sys._getframe() 함수는 현재 실행 스택에서 프레임을 검색 한 다음 inspect module에있는 메소드와 설명서를 검사 할 수 있습니다. 당신은뿐만 아니라 f_code 내용은 f_locals 속성에 특정 지역 주민을 위해 찾고있을거야 : 당신은 당신이 각 프레임에서 발견 어떤 종류의 정보를 감지하는 몇 가지 조심해야합니다

import sys 
def special_func(x): 
    callingframe = sys._getframe(1) 
    print 'My caller is the %r function in a %r class' % (
     callingframe.f_code.co_name, 
     callingframe.f_locals['self'].__class__.__name__) 

참고.

+2

을'그것은 주셔서 감사합니다 Python.' – pradyunsg

3

예 :

def f1(a): 
    import inspect 
    print 'I am f1 and was called by', inspect.currentframe().f_back.f_code.co_name 
    return a 

def f2(a): 
    return f1(a) 

는 "즉시"발신자를 검색합니다. 서로 호출되지 않은 경우

>>> f2(1) 
I am f1 and was called by f2 

그리고 당신은 (IDLE에서) 얻을 : 나는 모든 발신자의 정렬 된 목록을 반환하는 함수를 만들 수 있었다 존 클레멘트 대답에

>>> f1(1) 
I am f1 and was called by <module> 
+0

의 모든 구현에 존재 보장 할 수 없습니다, 나는 이것을 받아들이고 그것을 나의 필요에 적응시킬 수 있었다. –

2

감사합니다 :

def f1(): 
    names = [] 
    frame = inspect.currentframe() 
    ## Keep moving to next outer frame 
    while True: 
     try: 
      frame = frame.f_back 
      name = frame.f_code.co_name 
      names.append(name) 
     except: 
      break 
    return names 

및 체인이라고했을 때

def f2(): 
    return f1() 

def f3(): 
    return f2() 

def f4(): 
    return f3() 

print f4() 

은 다음과 같습니다 : 내 경우

['f2', 'f3', 'f4', '<module>'] 

나는 원래 발신자의 이름으로 마지막 항목을 다음 '<module>'에서 후에 무엇을 필터링합니다.

또는 '<'로 시작하는 이름의 첫 등장에서 구제하기 위해 원래의 루프 수정 : 워드 프로세서

frame = frame.f_back 
name = frame.f_code.co_name 
if name[0] == '<': 
    break 
names.append(name)