programing

Python에서 현재 모듈의 속성에 대한 참조를 얻는 방법

mailnote 2023. 7. 20. 22:04
반응형

Python에서 현재 모듈의 속성에 대한 참조를 얻는 방법

제가 하려는 작업은 명령줄에서 다음과 같이 나타납니다.

>>> import mymodule
>>> names = dir(mymodule)

에서 정의된 모든 이름에 대한 참조를 얻으려면 어떻게 해야 합니까?mymodule내부에서mymodule그 자체?

이와 같은 것:

# mymodule.py
names = dir(__thismodule__)

앞서 언급했듯이 글로벌은 모듈에 정의된 이름의 목록을 제공하는 dir()와 달리 사전을 제공합니다.일반적으로 이 작업이 수행되는 방식은 다음과 같습니다.

import sys
dir(sys.modules[__name__])

전역만 사용()

globals() - 현재 전역 기호 테이블을 나타내는 사전을 반환합니다.이것은 항상 현재 모듈의 사전입니다(함수 또는 메서드 내에서, 이것은 호출된 모듈이 아니라 정의된 모듈입니다).

http://docs.python.org/library/functions.html#globals

답이 늦어질 수도 있지만, 저는 제 자신에게 맞는 답을 찾지 못했습니다.가장 가깝고 정확한 솔루션(보다 빠름)inspect.stack()) 파이썬에서3.7.x:

# search for first module in the stack
stack_frame = inspect.currentframe()
while stack_frame:
  print('***', stack_frame.f_code.co_name, stack_frame.f_code.co_filename, stack_frame.f_lineno)
  if stack_frame.f_code.co_name == '<module>':
    if stack_frame.f_code.co_filename != '<stdin>':
      caller_module = inspect.getmodule(stack_frame)
    else:
      # piped or interactive import
      caller_module = sys.modules['__main__']
    if not caller_module is None:
      #... do something here ...
    break
  stack_frame = stack_frame.f_back

찬성:

  • 보다 정확함globals()방법.
  • 스택 중간 프레임에 의존하지 않습니다. 스택 중간 프레임은 예를 들어 후크를 통해 추가되거나 다음과 같은 3D 파티 도구에 의해 추가될 수 있습니다.pytest:
*** foo ... ..
*** boo ... ..
*** runtest c:\python\x86\37\lib\site-packages\xonsh\pytest_plugin.py 58
*** pytest_runtest_call c:\python\x86\37\lib\site-packages\_pytest\runner.py 125
*** _multicall c:\python\x86\37\lib\site-packages\pluggy\callers.py 187
*** <lambda> c:\python\x86\37\lib\site-packages\pluggy\manager.py 86
*** _hookexec c:\python\x86\37\lib\site-packages\pluggy\manager.py 92
*** __call__ c:\python\x86\37\lib\site-packages\pluggy\hooks.py 286
*** <lambda> c:\python\x86\37\lib\site-packages\_pytest\runner.py 201
*** from_call c:\python\x86\37\lib\site-packages\_pytest\runner.py 229
*** call_runtest_hook c:\python\x86\37\lib\site-packages\_pytest\runner.py 201
*** call_and_report c:\python\x86\37\lib\site-packages\_pytest\runner.py 176
*** runtestprotocol c:\python\x86\37\lib\site-packages\_pytest\runner.py 95
*** pytest_runtest_protocol c:\python\x86\37\lib\site-packages\_pytest\runner.py 80
*** _multicall c:\python\x86\37\lib\site-packages\pluggy\callers.py 187
*** <lambda> c:\python\x86\37\lib\site-packages\pluggy\manager.py 86
*** _hookexec c:\python\x86\37\lib\site-packages\pluggy\manager.py 92
*** __call__ c:\python\x86\37\lib\site-packages\pluggy\hooks.py 286
*** pytest_runtestloop c:\python\x86\37\lib\site-packages\_pytest\main.py 258
*** _multicall c:\python\x86\37\lib\site-packages\pluggy\callers.py 187
*** <lambda> c:\python\x86\37\lib\site-packages\pluggy\manager.py 86
*** _hookexec c:\python\x86\37\lib\site-packages\pluggy\manager.py 92
*** __call__ c:\python\x86\37\lib\site-packages\pluggy\hooks.py 286
*** _main c:\python\x86\37\lib\site-packages\_pytest\main.py 237
*** wrap_session c:\python\x86\37\lib\site-packages\_pytest\main.py 193
*** pytest_cmdline_main c:\python\x86\37\lib\site-packages\_pytest\main.py 230
*** _multicall c:\python\x86\37\lib\site-packages\pluggy\callers.py 187
*** <lambda> c:\python\x86\37\lib\site-packages\pluggy\manager.py 86
*** _hookexec c:\python\x86\37\lib\site-packages\pluggy\manager.py 92
*** __call__ c:\python\x86\37\lib\site-packages\pluggy\hooks.py 286
*** main c:\python\x86\37\lib\site-packages\_pytest\config\__init__.py 90
*** <module> c:\Python\x86\37\Scripts\pytest.exe\__main__.py 7
  • 파이썬 파이프 또는 대화형 세션을 처리할 수 있습니다.

단점:

  • 일종의 매우 정밀하고 실행 파일에 등록된 모듈을 반환할 수 있습니다.pytest.exe당신이 원하는 것이 아닐 수도 있습니다.
  • inspect.getmodule후킹에 따라 유효한 모듈에서 None을 반환할 수 있습니다.

나는 파이썬의 확장자가 있습니다.전체 경로가 지정된 모듈을 가져오는 방법은 무엇입니까?

이 경우 래퍼 함수가 있는 확장자:

def tkl_get_stack_frame_module_by_offset(skip_stack_frames = 0, use_last_frame_on_out_of_stack = False):
  ...

def tkl_get_stack_frame_module_by_name(name = '<module>'):
  ...

확장을 올바르게 초기화해야 합니다.

# portable import to the global space
sys.path.append(<path-to-tacklelib-module-directory>)
import tacklelib as tkl

tkl.tkl_init(tkl, global_config = {'log_import_module':os.environ.get('TACKLELIB_LOG_IMPORT_MODULE')})

# cleanup
del tkl # must be instead of `tkl = None`, otherwise the variable would be still persist
sys.path.pop()

# use `tkl_*` functions directly from here ...

언급URL : https://stackoverflow.com/questions/990422/how-to-get-a-reference-to-current-modules-attributes-in-python

반응형