2011-03-16 3 views
6

내에서 호출 현재 모듈/라인을 확인하는 방법 :파이썬 반성 - 나는 기능이 기능

# utils.py 
def hello(name='World'): 
    # Detect where I'm being called from. 
    print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno)) 
    # ``mod`` and ``lineno`` on previous line would have been set in real use. 

그 기능을 가져오고 다른 곳

# other.py (this comment at line # 138) 
from utils import hello 
hello('Johnny') # From inside ``hello`` I want to be able to detect that this 
# was called from other.py at line # 140 

답변

13

액세스의 바깥 쪽 프레임을 실행 inspect.currentframe() :

import inspect 

def hello(name='World'): 
    f = inspect.currentframe().f_back 
    mod = f.f_code.co_filename 
    lineno = f.f_lineno 
    print('Hi, %s. You called this from %s at line # %d.' % 
      (name, mod, lineno)) 
3

traceback 모듈을 사용하면 STAC를 추출 할 수 있습니다 k를 사용하면 현재 스택 프레임에 어떻게 도달했는지 확인할 수 있습니다. 당신이 원하는 경우에 당신은 지금까지 당신이 원하는대로 스택까지 호출자의-발신자를 출력하려면이 옵션을 확장 할 수

import traceback 

def _trace(): 
    stack = traceback.extract_stack()[-3:-1] 
    path, line, in_func, _instr = stack[0] 
    print 'called from %s in func %s at line %s' % (path, in_func, line) 

def bar(): 
    _trace() 

def foo(): 
    bar() 
    baz() 

def baz(): 
    bar() 

bar() 
foo() 

출력 :

called from hello.py in func <module> at line 20 
called from hello.py in func foo at line 14 
called from hello.py in func baz at line 18 
1

사용 warnings 모듈.

import warnings 

def test(where): 
    warnings.warn('hi from test', stacklevel=2) 

def foo(): 
    test('inside foo') 

test('from main module') 
foo() 

결과 :

/tmp/test.py:9: UserWarning: hi from test 
    test('from main module') 
/tmp/test.py:7: UserWarning: hi from test 
    test('inside foo') 

확인 행 번호. warnings 모듈을 사용하면 모듈 사용자가 경고를 사용 중지하거나 완전히 검사 가능한 예외로 설정할 수 있기 때문에 유용합니다.