Python에서 함수 모듈을 호출하는 __name__를 얻습니다
-
11-09-2019 - |
문제
가정하다 myapp/foo.py
포함
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
그리고 myapp/bar.py
포함
import foo
foo.info('Hello') # => [myapp.bar] Hello
원해요 caller_name
로 설정됩니다 __name__
이 경우 호출 함수 '모듈 ('myapp.foo ')의 속성. 이 작업은 어떻게 할 수 있습니까?
해결책
검사 모듈을 확인하십시오.
inspect.stack()
스택 정보를 반환합니다.
함수 내에서 inspect.stack()[1]
발신자의 스택을 반환합니다. 여기에서 발신자의 기능 이름, 모듈 등에 대한 자세한 정보를 얻을 수 있습니다.
자세한 내용은 문서를 참조하십시오.
http://docs.python.org/library/inspect.html
또한 Doug Hellmann은 Pymotw 시리즈에서 검사 모듈에 대한 훌륭한 글을 가지고 있습니다.
http://pymotw.com/2/inspect/index.html#module-inspect
편집 : 여기에 당신이 원하는 것을하는 코드가 있습니다.
def info(msg):
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
print '[%s] %s' % (mod.__name__, msg)
다른 팁
비슷한 문제에 직면하여 sys._current_frames () SYS 모듈에는 적어도 특정 사용 사례에서 검사를 가져올 필요없이 도움이 될 수있는 흥미로운 정보가 포함되어 있습니다.
>>> sys._current_frames()
{4052: <frame object at 0x03200C98>}
그런 다음 f_back을 사용하여 "이동"할 수 있습니다.
>>> f = sys._current_frames().values()[0]
>>> # for python3: f = list(sys._current_frames().values())[0]
>>> print f.f_back.f_globals['__file__']
'/base/data/home/apps/apricot/1.6456165165151/caller.py'
>>> print f.f_back.f_globals['__name__']
'__main__'
파일 이름의 경우 위의 Mark Roddy가 제안한대로 F.f_back.f_code.co_filename을 사용할 수도 있습니다. 이 방법의 한계와 경고는 확실하지 않지만 (여러 스레드가 문제가 될 가능성이 높습니다) 내 경우에는 사용하려고합니다.
나는 이것을 권장하지 않지만 다음 방법으로 목표를 달성 할 수 있습니다.
def caller_name():
frame=inspect.currentframe()
frame=frame.f_back.f_back
code=frame.f_code
return code.co_filename
그런 다음 기존 메소드를 다음과 같이 업데이트하십시오.
def info(msg):
caller = caller_name()
print '[%s] %s' % (caller, msg)