Programing

inspect를 사용하여 Python에서 수신자로부터 호출자 정보를 얻는 방법은 무엇입니까?

crosscheck 2020. 10. 27. 07:52
반응형

inspect를 사용하여 Python에서 수신자로부터 호출자 정보를 얻는 방법은 무엇입니까?


수신자로부터 발신자 정보 (어떤 파일 / 어떤 줄)를 받아야합니다. 나는 목적을 위해 inpect 모듈을 사용할 수 있다는 것을 배웠지 만 정확히 방법은 아닙니다.

검사로 정보를 얻는 방법은 무엇입니까? 아니면 정보를 얻을 수있는 다른 방법이 있습니까?

import inspect

print __file__
c=inspect.currentframe()
print c.f_lineno

def hello():
    print inspect.stack
    ?? what file called me in what line?

hello()

호출자의 프레임이 현재 프레임보다 한 프레임 높습니다. inspect.currentframe().f_back발신자의 프레임을 찾는 데 사용할 수 있습니다 . 그런 다음 inspect.getframeinfo사용 하여 호출자의 파일 이름과 줄 번호를 가져옵니다.

import inspect

def hello():
    previous_frame = inspect.currentframe().f_back
    (filename, line_number, 
     function_name, lines, index) = inspect.getframeinfo(previous_frame)
    return (filename, line_number, function_name, lines, index)

print(hello())

# ('/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0)

inspect.stack대신 사용 하는 것이 좋습니다 .

import inspect

def hello():
    frame,filename,line_number,function_name,lines,index = inspect.stack()[1]
    print(frame,filename,line_number,function_name,lines,index)
hello()

단일 매개 변수로 스택 프레임을 다루는 간단한 스택 프레임 주소 지정으로 검사 용 래퍼를 게시했습니다 spos.

pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)

spos=0lib-function은 어디 spos=1에서 호출자, spos=2호출자 등입니다.


호출자가 주 파일 인 경우 sys.argv [0]을 사용하면됩니다.

참고 URL : https://stackoverflow.com/questions/3711184/how-to-use-inspect-to-get-the-callers-info-from-callee-in-python

반응형