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

我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?

例如:

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

当前回答

除了之前的回答中提到的dir(模块)或help(模块),还可以尝试: -打开ipython - import module_name - type 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

其他回答

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

例如,我让用户为用zipapp生成的包选择入口点函数。使用导入和检查的风险包括运行错误的代码、导致崩溃、打印帮助消息、弹出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。

如果你不能在没有导入错误的情况下导入上述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])

除了之前的回答中提到的dir(模块)或help(模块),还可以尝试: -打开ipython - import module_name - type 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

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

# 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 Wouters和adrian的答案,以及Sebastian Rittau对另一个问题的回答。

Dir(模块)是使用脚本或标准解释器时的标准方式,正如大多数回答中提到的那样。

然而,对于交互式python shell(如IPython),您可以使用制表符完成来获得模块中定义的所有对象的概述。 这比使用脚本和打印查看模块中定义的内容要方便得多。

模块。<tab>将显示模块中定义的所有对象(函数,类等) module.ClassX。<tab>将显示一个类的方法和属性 module.function_xy吗?还是module.ClassX.method_xy ?是否会显示该函数/方法的文档字符串 module.function_x ? ?还是module.SomeClass.method_xy ? ?将显示函数/方法的源代码。