问题:如何列出Python模块中的所有功能?
我的系统上安装了python模块,我希望能够看到其中可用的函数/类/方法。
我想在每个函数上调用doc函数。在ruby中,我可以执行ClassName.methods之类的操作来获取该类上所有可用方法的列表。python中是否有类似的东西?
例如。就像是:
from somemodule import foo
print foo.methods # or whatever is the correct method to call
回答 0
回答 1
您可以dir(module)用来查看所有可用的方法/属性。还要检查PyDocs。
回答 2
一旦你import编的模块,你可以做:
 help(modulename)…要一次以交互方式获取所有功能的文档。或者您可以使用:
 dir(modulename)…简单列出模块中定义的所有函数和变量的名称。
回答 3
带inspect的例子:
from inspect import getmembers, isfunction
from my_project import my_module
functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]getmembers返回(object_name,object_type)元组的列表。
您可以在检查模块中将isfunction替换为任何其他isXXX函数。
回答 4
import types
import yourmodule
print([getattr(yourmodule, a) for a in dir(yourmodule)
  if isinstance(getattr(yourmodule, a), types.FunctionType)])回答 5
为了完整起见,我想指出,有时您可能想解析代码而不是导入代码。一个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当然,即使对于像Python这样的相对简单的语言,导航AST有时也会很棘手,因为AST的层次很低。但是,如果您有一个简单明了的用例,那么它既可行又安全。
不过,缺点是您无法检测到运行时生成的函数,例如foo = lambda x,y: x*y。
回答 6
对于您不希望解析的代码,我建议上面使用基于AST的@csl方法。
对于其他所有内容,inspect模块都是正确的:
import inspect
import <module_to_inspect> as module
functions = inspect.getmembers(module, inspect.isfunction)这给出了形式为2元组的列表[(<name:str>, <value:function>), ...]。
上面的简单答案在各种回复和评论中都有提示,但没有明确指出。
回答 7
这将达到目的:
dir(module) 但是,如果您发现读取返回的列表很烦人,则只需使用以下循环即可获得每行一个名称。
for i in dir(module): print i回答 8
dir(module) 如大多数答案中所述,这是使用脚本或标准解释器时的标准方法。
但是,使用像IPython这样的交互式python shell,您可以使用tab-completion来概述模块中定义的所有对象。这比使用脚本并print查看模块中定义的内容要方便得多。
- module.<tab>将向您显示模块中定义的所有对象(函数,类等)
- module.ClassX.<tab>将向您展示类的方法和属性
- module.function_xy?或- module.ClassX.method_xy?将向您显示该函数/方法的文档字符串
- module.function_x??或- module.SomeClass.method_xy??将显示函数/方法的源代码。
回答 9
对于全局函数,dir()是要使用的命令(如大多数答案中所提到的),但是此命令同时列出了公共函数和非公共函数。
例如运行:
>>> import re
>>> dir(re)返回类似的函数/类:
'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'其中一些通常不用于一般编程用途(但由模块本身提供,除非在DunderAliases之类的情况下, __doc__,__file__ECT)。因此,将它们与公开对象一起列出可能没有用(这是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']
>>>所有带下划线的函数和类均已删除,仅保留那些定义为public的函数和类,因此可以通过来使用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__'
>>>回答 10
如果您无法在没有导入错误的情况下导入所述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])回答 11
除了前面的答案中提到的dir(模块)或help(模块),您还可以尝试:
 -打开ipython- 
 导入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回答 12
这将在列表中附加在your_module中定义的所有功能。
result=[]
for i in dir(your_module):
    if type(getattr(your_module, i)).__name__ == "function":
        result.append(getattr(your_module, i))回答 13
您可以使用以下方法从shell列出模块中的所有功能:
import module
module.*?回答 14
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]回答 15
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
