我的系统上安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。
我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?
例如:
from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
我的系统上安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。
我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?
例如:
from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
当前回答
一旦你导入了模块,你可以这样做:
help(modulename)
... 以交互方式一次性获得所有函数的文档。或者你可以用:
dir(modulename)
... 简单地列出模块中定义的所有函数和变量的名称。
其他回答
使用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相对于dir或inspect的优势。Getmembers是按函数定义的顺序返回函数,而不是按字母顺序排序。
此外,这将包括my_module导入的函数,如果你想过滤掉它们,只获得my_module中定义的函数,请参阅我的问题获取Python模块中所有已定义的函数。
使用inspect模块:
from inspect import getmembers, isfunction
from somemodule import foo
print(getmembers(foo, isfunction))
还可以查看pydoc模块、交互式解释器中的help()函数和生成所需文档的pydoc命令行工具。您可以只给他们您希望看到的类的文档。例如,它们还可以生成HTML输出并将其写入磁盘。
如果你想获得当前文件中定义的所有函数的列表,你可以这样做:
# 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对另一个问题的回答。
import types
import yourmodule
print([getattr(yourmodule, a) for a in dir(yourmodule)
if isinstance(getattr(yourmodule, a), types.FunctionType)])
如果你不能在没有导入错误的情况下导入上述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])