ChatGPT解决这个技术问题 Extra ChatGPT

如何列出模块中的所有功能?

我的系统上安装了一个 Python 模块,我希望能够查看其中可用的函数/类/方法。

我想在每一个上调用 help 函数。在 Ruby 中,我可以执行 ClassName.methods 之类的操作来获取该类上所有可用方法的列表。 Python中有类似的东西吗?

例如:

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

c
camflan

您可以使用 dir(module) 查看所有可用的方法/属性。另请查看 PyDocs。


这并不完全正确。 dir() 函数“试图产生最相关的,而不是完整的信息”。来源:docs.python.org/library/functions.html#dir
@jAckOdE 引用了吗?然后您将获得字符串模块的可用方法和属性。
@OrangeTux:哎呀,这应该是一个问题。是的,你回答了。
OP 清楚地要求函数,而不是变量。 Cf 使用 inspect 回答。
请注意,对于当前活动的模块,您需要在没有参数的情况下调用 dir (显然,它只能列出直到调用 dir 的时间点之前定义的内容)
B
Boris Verkhovskiy

使用 inspect 模块:

from inspect import getmembers, isfunction

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

另请参阅 pydoc 模块、交互式解释器中的 help() 函数和用于生成所需文档的 pydoc 命令行工具。您可以只给他们您希望查看其文档的课程。例如,它们还可以生成 HTML 输出并将其写入磁盘。


我已经在 my answer 中说明了在某些情况下使用 ast 模块的情况。
TL;DR 以下答案:使用 dir 返回函数和变量;仅使用 inspect 过滤函数;并使用 ast 解析而不导入。
值得对 Sheljohn 总结的每种方法进行测试,因为结果输出与一种解决方案截然不同。
T
Tiago Martins Peres

完成模块后,您可以执行以下操作:import

help(modulename)

... 以交互方式一次获取所有功能的文档。或者您可以使用:

dir(modulename)

... 简单地列出模块中定义的所有函数和变量的名称。


@sheljohn……这个批评有什么意义?我的解决方案列出了函数,并且 inspect 模块也可以列出变量,即使这里没有明确要求。此解决方案仅需要内置对象,这在 Python 安装在受限/锁定/损坏环境中的某些情况下非常有用。
谢谢,这几乎奏效了,但我认为 dir 会打印结果,但看起来您需要执行 print(dir(modulename))
这个答案绝对是最“有帮助”的。感谢您分享该提示!我现在发现 help(modulename) 是我的最爱。
@DanLenski 您到底在哪里运行这些命令?我尝试在 python shell 和 windows 命令提示符下运行它们,但它们没有工作。
C
Christopher Peisert

使用 inspect.getmembers 获取模块中的所有变量/类/函数等,并将 inspect.isfunction 作为谓词传入以仅获取函数:

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

getmembers 返回按名称字母顺序排列的元组列表 (object_name, object)

您可以将 isfunction 替换为 inspect module 中的任何其他 isXXX 函数。


getmembers 可以采用谓词,因此您的示例也可以写成:functions_list = [o for o in getmembers(my_module, isfunction)]
@ChristopherCurrie,您还可以避免使用 functions_list = getmembers(my_module, predicate) 进行无用的列表理解,因为它已经返回了一个列表;)
要查找该函数是否在该模块中定义(而不是导入)添加:到“if isfunction(o[1]) and o[1].__module__ == my_module.__name__” - 注意它不一定工作如果导入的函数来自与该模块同名的模块。
是否可以确定函数是在 my_module 中定义还是导入到 my_module 中?
A
Aran-Fey
import types
import yourmodule

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

对于这条路线,使用 getattr(yourmodule, a, None) 而不是 yourmodule.__dict__.get(a)
your_module.__dict__ 是我的选择,因为您实际上得到了一个包含 functionName: 的字典,并且您现在可以动态调用该函数。美好时光!
Python 3 对一些糖很友好: import types def print_module_functions(module): print('\n'.join([str(module.__dict__.get(a).__name__) for a in dir(module) if isinstance(module. __dict__.get(a), types.FunctionType)]))
这还将列出该模块导入的所有函数。这可能是也可能不是你想要的。
c
csl

为了完整起见,我想指出,有时您可能想要解析 代码而不是导入它。 import执行顶级表达式,这可能是个问题。

例如,我让用户为使用 zipapp 制作的包选择入口点函数。使用 importinspect 有运行错误代码、导致崩溃、打印出帮助消息、弹出 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 非常低级。但是,如果您有一个简单明了的用例,那么它既可行又安全。

不过,缺点是您无法检测在运行时生成的函数,例如 foo = lambda x,y: x*y


我喜欢这个;我目前正在尝试找出是否有人已经编写了一个可以执行 pydoc 之类的工具但没有导入模块的工具。到目前为止,这是我发现的最好的例子:)
同意这个答案。无论目标文件可能导入什么或它是为什么版本的 python 编写的,我都需要这个函数工作。这不会遇到 imp 和 importlib 所做的导入问题。
模块变量(__version__ 等)怎么样。有没有办法得到它?
C
Cireo

对于您不想评估的代码,我建议使用基于 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)

这给出了 [(<name:str>, <value:function>), ...] 形式的 2 元组列表。

上面的简单答案在各种回复和评论中都有暗示,但没有明确指出。


感谢您拼写出来;如果您可以在模块上运行导入以进行检查,我认为这是正确的答案。
我必须添加正文ast.parse(source).body
X
X-Istence

这可以解决问题:

dir(module) 

但是,如果您发现读取返回的列表很烦人,只需使用以下循环获取每行一个名称。

for i in dir(module): print i

OP 清楚地要求函数,而不是变量。 Cf 使用 inspect 回答。此外,这与@DanLenski 的回答有何不同?
b
bmu

dir(module) 是使用脚本或标准解释器时的标准方式,如大多数答案中所述。

但是,对于像 IPython 这样的交互式 python shell,您可以使用 tab-completion 来获得模块中定义的所有对象的概览。这比使用脚本和 print 查看模块中定义的内容要方便得多。

module. 将显示模块中定义的所有对象(函数、类等)

module.ClassX. 将显示类的方法和属性

模块.function_xy?还是 module.ClassX.method_xy?将向您显示该函数/方法的文档字符串

模块.function_x??或 module.SomeClass.method_xy??将向您展示函数/方法的源代码。


X
Xantium

对于全局函数 dir() 是要使用的命令(如大多数答案中所述),但是这将公共函数和非公共函数一起列出。

例如运行:

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

返回函数/类,如:

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

其中一些通常不用于一般编程用途(但由模块本身使用,除了 DunderAliases,如 __doc____file__ 等)。出于这个原因,将它们与公共的一起列出可能没有用(这就是 Python 在使用 from module import * 时知道要获取什么的方式)。

__all__ 可以用来解决这个问题,它返回一个模块中所有公共函数和类的列表(那些以下划线开头的 - _)。有关 __all__ 的用法,请参见 Can someone explain __all__ in Python?

这是一个例子:

>>> 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__'
>>>

c
ckb

如果您无法在没有导入错误的情况下导入所述 Python 文件,则这些答案都不起作用。当我检查来自具有大量依赖项的大型代码库的文件时,我就是这种情况。以下将文件作为文本处理,并搜索所有以“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])

在这种情况下,最好使用 ast 模块。有关示例,请参见 my answer
我认为这是一种有效的方法。为什么会投反对票?
J
Josh Peak

在当前脚本 __main__ 中查找名称(和可调用对象)

我试图创建一个独立的 python 脚本,它仅使用标准库在当前文件中查找前缀为 task_ 的函数,以创建 npm run 提供的最小自制版本。

TL;博士

如果您正在运行一个独立脚本,您希望在 sys.modules['__main__'] 中定义的 module 上运行 inspect.getmembers。例如,

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

sys.modules['__main__'] 中的@muuvmuuv 已经在 __main__ 脚本中导入的所有代码都应该在那里。我刚刚尝试使用 inspect.isclass 而不是 inspect.isfunction 并且它对我有用。 docs.python.org/3/library/inspect.html#inspect.isclass
S
Saurya Man Patel

除了前面答案中提到的 dir(module) 或 help(module) 之外,您还可以尝试: - 打开 ipython - import module_name - 输入 module_name,按 Tab。它将打开一个小窗口,其中列出了 python 模块中的所有函数。它看起来非常整洁。

这是列出 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

e
eid
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]

B
Boris Verkhovskiy

使用 vars(module),然后使用 inspect.isfunction 过滤掉任何不是函数的内容:

import inspect
import my_module

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

vars 优于 dirinspect.getmembers 的优点是它按定义的顺序返回函数,而不是按字母顺序排序。

此外,这将包括由 my_module 导入的函数,如果您想过滤掉这些函数以仅获取 my_module 中定义的函数,请参阅我的问题 Get all defined functions in Python module


这就是我需要的! vars 可以保持顺序
V
Vishal Lamba

您可以使用以下方法从 shell 获取模块中的所有函数的列表:

import module

module.*?

@GabrielFair 您在哪个版本/平台上运行 python?我在 Py3.7/Win10 上遇到语法错误。
+1 使用 ipython 在 Python 2.7 Ubuntu 16.04LTS 上为我工作;并且不需要导入额外的模块。
对我不起作用(python3)。
J
Julien Faujanet
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

K
Karthik Nandula

Python documentation 使用内置函数 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']

这是“时间”模块包含的功能列表。


a
amine

这会将 your_module 中定义的所有函数附加到列表中。

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

这是什么unit8_conversion_methods?这只是模块名称的一个例子吗?
@nocibambi 是的,它只是一个模块名称。
谢谢马尼什。我提出以下单行替代方案:[getattr(your_module, func) for func in dir(your_module) if type(getattr(your_module, func)).__name__ == "function"]
G
Guimoute

如果要获取当前文件中定义的所有函数的列表,可以这样做:

# 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)

作为一个应用程序示例,我使用它来调用我的单元测试脚本中定义的所有函数。

这是根据此处 Thomas Woutersadrian 的答案以及针对不同问题的 Sebastian Rittau 改编的代码组合。