itsource

모듈의 모든 기능을 나열하는 방법은 무엇입니까?

mycopycode 2022. 9. 5. 23:18
반응형

모듈의 모든 기능을 나열하는 방법은 무엇입니까?

시스템에 Python 모듈이 설치되어 있는데 어떤 함수/클래스/메서드를 사용할 수 있는지 보고 싶습니다.

하고 help기능을 합니다.루비에서 나는 다음과 같은 것을 할 수 있다.ClassName.methods해당 클래스에서 사용 가능한 모든 메서드의 목록을 가져옵니다.Python? Python?

예:

from somemodule import foo
print(foo.methods)  # or whatever is the correct method to call

하시면 됩니다.dir(module)사용 가능한 모든 메서드/속성을 표시합니다.PyDocs 。

모듈을 사용합니다.

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

'모듈'도 참조해 주세요.help()및 인터랙터 pydoc필요한 문서를 생성하는 명령줄 도구입니다.원하는 문서를 보고자 하는 클래스를 제공하면 됩니다.예를 들어 HTML 출력을 생성하여 디스크에 쓸 수도 있습니다.

import모듈에서는 다음 작업을 수행할 수 있습니다.

help(modulename)

...모든 기능에 대한 문서를 대화식으로 한 번에 얻을 수 있습니다.또는 다음을 사용할 수 있습니다.

dir(modulename)

... 모듈에서 정의된 모든 함수 및 변수의 이름을 간단히 나열합니다.

모듈의 모든 변수/클래스/함수 등을 가져오고 함수만 가져오려면 술어로 전달합니다.

from inspect import getmembers, isfunction
from my_project import my_module
    
functions_list = getmembers(my_module, isfunction)

getmembers는 튜플 합니다.(object_name, object)이름순으로 정렬되어 있습니다.

할 수 요.isfunction 어떤 과도 함께isXXX모듈 내에서 기능합니다.

import types
import yourmodule

print([getattr(yourmodule, a) for a in dir(yourmodule)
  if isinstance(getattr(yourmodule, a), types.FunctionType)])

완전성을 위해 때로는 코드를 Import하지 않고 해석하고 싶을 수도 있다는 점을 지적하고 싶습니다.import최상위 수준의 표현이 실행되기 때문에 문제가 될 수 있습니다.

예를 들어, zipapp로 만드는 패키지에 대해 사용자가 진입점 기능을 선택할 수 있도록 합니다.사용.import ★★★★★★★★★★★★★★★★★」inspect잘못된 코드가 실행되어 크래시, 도움말메시지 출력, GUI 대화상자 팝업 등의 위험이 있습니다.

대신 ast 모듈을 사용하여 모든 최상위 기능을 나열합니다.

import ast
import sys

def top_level_functions(body):
    return (f for f in body if isinstance(f, ast.FunctionDef))

def parse_ast(filename):
    with open(filename, "rt") as file:
        return ast.parse(file.read(), filename=filename)

if __name__ == "__main__":
    for filename in sys.argv[1:]:
        print(filename)
        tree = parse_ast(filename)
        for func in top_level_functions(tree.body):
            print("  %s" % func.name)

를 이이에 list.py그 다음과 같이.

$ python list.py list.py
list.py
  top_level_functions
  parse_ast

물론 AST는 레벨이 낮기 때문에 Python과 같은 비교적 단순한 언어에서도 AST 탐색이 어려울 수 있습니다.그러나 간단하고 명확한 사용 사례가 있다면 실행 가능하고 안전합니다.

시 음, 다, 다, 다, 다, 다, 다, 다, 다, 다, 다, 다, though, ,, though, though, though, though, though, though, ,, ,, ,, ,, ,, though, though, that, though, that 등의 기능을 찾을 수 없다는 단점이 .foo = lambda x,y: x*y.

평가하고 싶지 않은 코드에 대해서는 AST 기반의 접근법(csl의 답변 등)을 권장합니다.예:

import ast

source = open(<filepath_to_parse>).read()
functions = [f.name for f in ast.parse(source).body
             if isinstance(f, ast.FunctionDef)]

그 외의 모든 경우 검사 모듈은 정확합니다.

import inspect

import <module_to_inspect> as module

functions = inspect.getmembers(module, inspect.isfunction)

을 ples in in개 .[(<name:str>, <value:function>), ...].

위의 간단한 답변은 다양한 응답과 코멘트로 암시되지만 명시적으로 호출되지는 않습니다.

이렇게 하면 효과가 있습니다.

dir(module) 

그러나 반환된 목록을 읽는 것이 귀찮을 경우 다음 루프를 사용하여 한 줄에 하나의 이름을 가져옵니다.

for i in dir(module): print i

dir(module)는 스크립트 또는 표준 인터프리터를 사용하는 표준 방법이며, 대부분의 답변에서 언급되어 있습니다.

그러나 IPython과 같은 인터랙티브한 python 쉘에서는 tab-completion을 사용하여 모듈에서 정의된 모든 객체의 개요를 볼 수 있습니다.이것은 스크립트를 사용하는 것보다 훨씬 편리합니다.print이치노

  • module.<tab>를 .
  • module.ClassX.<tab>의 메서드와 줍니다.
  • module.function_xy? ★★★★★★★★★★★★★★★★★」module.ClassX.method_xy?는 그 /메서드 을 보여줍니다.
  • module.function_x?? ★★★★★★★★★★★★★★★★★」module.SomeClass.method_xy??함수/메서드의 소스 코드를 표시합니다.

기능의 dir()는 사용하는 명령어입니다(대부분의 답변에서 설명하듯이). 단, 여기에는 퍼블릭 기능과 비 퍼블릭 기능이 모두 나열되어 있습니다.

실행 예:

>>> import re
>>> dir(re)

다음과 같은 함수/클래스를 반환합니다.

'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'

중단, 모듈만, 와 같은 는 제외).__doc__,__file__과 함께 것은 이 되지 이에, Python은 「」를 사용할 에 무엇을 수 를 알 수 ).from module import *를 참조해 주세요.

__all__는 이 문제를 해결하기 위해 사용할 수 있으며 모듈의 모든 공용 함수 및 클래스 목록을 반환합니다(밑줄로 시작하지 않음:_Python에서 __all_을 설명할 수 있는 사람이 있습니까?를 참조해 주십시오.을 사용하기 위해서__all__.

다음은 예를 제시하겠습니다.

>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>

되어 있기 에 를 통해 할 수 .import *.

:__all__항상 정의되어 있는 것은 아닙니다.되어 있지 않은 는, 「」를 해 주세요.AttributeError인스톨 됩니다.

이 경우 ast 모듈을 사용합니다.

>>> import ast
>>> ast.__all__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>

Import 오류 없이 해당 Python 파일을 Import할 수 없는 경우 이러한 답변 중 어느 것도 작동하지 않습니다.의존관계가 많은 대규모 코드베이스에서 파일을 검사했을 때 그랬습니다.다음은 파일을 텍스트로 처리하고 "def"로 시작하는 모든 메서드 이름을 검색하여 해당 이름과 해당 행 번호를 인쇄합니다.

import re
pattern = re.compile("def (.*)\(")
for i, line in enumerate(open('Example.py')):
  for match in re.finditer(pattern, line):
    print '%s: %s' % (i+1, match.groups()[0])

스크립트 내의 콜 오브젝트).__main__

파일 내의 스탠드아론 이는 프리픽스는 프리픽스로 되어 있습니다.task_.npm run제공되고 있습니다.

TL;DR

는, 「」를 실행합니다.inspect.getmembers module은 '아까부터'에 되어 있습니다.sys.modules['__main__'] 아.

inspect.getmembers(sys.modules['__main__'], inspect.isfunction)

다만, 프리픽스로 메서드 리스트를 필터링 해, 프리픽스를 삭제해 검색 사전을 작성하려고 했습니다.

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

출력 예:

{
 'install': <function task_install at 0x105695940>,
 'dev': <function task_dev at 0x105695b80>,
 'test': <function task_test at 0x105695af0>
}

긴 버전

반복할 필요 없이 CLI 태스크명을 정의하는 메서드의 이름을 원했습니다.

./tasks.py

#!/usr/bin/env python3
import sys
from subprocess import run

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

def _cmd(command, args):
    return run(command.split(" ") + args)

def task_install(args):
    return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)

def task_test(args):
    return _cmd("python3 -m pytest", args)

def task_dev(args):
    return _cmd("uvicorn api.v1:app", args)

if __name__ == "__main__":
    tasks = _inspect_tasks()

    if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():
        tasks[sys.argv[1]](sys.argv[2:])
    else:
        print(f"Must provide a task from the following: {list(tasks.keys())}")

예: 인수 없음:

λ ./tasks.py
Must provide a task from the following: ['install', 'dev', 'test']

추가 인수를 사용하여 테스트를 실행하는 예:

λ ./tasks.py test -qq
s.ssss.sF..Fs.sssFsss..ssssFssFs....s.s    

무슨 말인지 알겠어.프로젝트가 점점 더 진행됨에 따라 README을 최신 상태로 유지하는 것보다 스크립트를 최신 상태로 유지하는 것이 더 쉬워지고 다음과 같이 요약할 수 있습니다.

./tasks.py install
./tasks.py dev
./tasks.py test
./tasks.py publish
./tasks.py logs

도움의 손길을 뻗치다
- ipython을 엽니다.
- module_name Import
이라고 하고 tabsname_name 을 파이썬 모듈의 모든 기능을 나열하는 작은 창이 열립니다.
아주 깔끔해 보여요.

다음은 hashlib 모듈의 모든 함수를 나열한 스니펫입니다.

(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
             hashlib.algorithms            hashlib.new                   hashlib.sha256
             hashlib.algorithms_available  hashlib.pbkdf2_hmac           hashlib.sha384
             hashlib.algorithms_guaranteed hashlib.sha1                  hashlib.sha512
             hashlib.md5                   hashlib.sha224
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]

vars(module)다음 명령을 사용하여 함수가 아닌 모든 항목을 필터링합니다.

import inspect
import my_module

my_module_functions = [f for _, f in vars(my_module).values() if inspect.isfunction(f)]

over 또는 의 장점은 알파벳 순으로 정렬되지 않고 정의된 순서대로 함수를 반환한다는 것입니다.

Import를 됩니다.my_module 하고, 「」에 되어 있는 는, 「」를 참조해 주세요my_modulePython 모듈에서 정의된 함수를 모두 가져옵니다.

셸에서 모듈의 모든 기능을 목록으로 표시하려면 다음 방법을 사용합니다.

import module

module.*?
r = globals()
sep = '\n'+100*'*'+'\n' # To make it clean to read.
for k in list(r.keys()):
    try:
        if str(type(r[k])).count('function'):
            print(sep+k + ' : \n' + str(r[k].__doc__))
    except Exception as e:
        print(e)

출력:

******************************************************************************************
GetNumberOfWordsInTextFile : 

    Calcule et retourne le nombre de mots d'un fichier texte
    :param path_: le chemin du fichier à analyser
    :return: le nombre de mots du fichier

******************************************************************************************

    write_in : 

        Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode a,
        :param path_: le path du fichier texte
        :param data_: la liste des données à écrire ou un bloc texte directement
        :return: None


 ******************************************************************************************
    write_in_as_w : 

            Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode w,
            :param path_: le path du fichier texte
            :param data_: la liste des données à écrire ou un bloc texte directement
            :return: None

Python 문서는 내장된 기능을 사용하는 완벽한 솔루션을 제공합니다.dir.

dir(module_name)사용하면 해당 모듈 내의 함수 목록이 반환됩니다.

예를 들어 dir(time)가 반환됩니다.

['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']

이는 '시간' 모듈에 포함된 기능 목록입니다.

목록에 있는 your_module에 정의된 모든 기능이 추가됩니다.

result=[]
for i in dir(your_module):
    if type(getattr(your_module, i)).__name__ == "function":
        result.append(getattr(your_module, i))

현재 파일에 정의되어 있는 모든 함수의 목록을 가져오려면 다음과 같이 하십시오.

# Get this script's name.
import os
script_name = os.path.basename(__file__).rstrip(".py")

# Import it from its path so that you can use it as a Python object.
import importlib.util
spec = importlib.util.spec_from_file_location(script_name, __file__)
x = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x)

# List the functions defined in it.
from inspect import getmembers, isfunction
list_of_functions = getmembers(x, isfunction)

어플리케이션의 예로서 유닛테스트 스크립트에 정의되어 있는 모든 함수를 호출할 때 사용합니다.

이것은 토마스 워터와 아드리안의 답변과 세바스찬 리타우의 다른 질문에 대한 답변을 조합한 것입니다.

언급URL : https://stackoverflow.com/questions/139180/how-to-list-all-functions-in-a-module

반응형