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

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

例如:

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

当前回答

Python文档提供了使用内置函数dir的完美解决方案。

您可以只使用dir(module_name),然后它将返回该模块中的函数列表。

例如,dir(time)将返回

[' _STRUCT_TM_ITEMS’,‘__doc__’,‘__loader__’,‘__name__’,‘__package__’,‘__spec__’,‘altzone’,‘asctime’,‘ctime’,‘阳光’,‘get_clock_info’,‘gmtime’,‘作用’,‘mktime’,‘单调’,‘monotonic_ns’,‘perf_counter’,‘perf_counter_ns’,‘process_time’,‘process_time_ns’,‘睡眠’,‘strftime’,‘strptime’,‘struct_time’,‘时间’,‘time_ns’,“时区”,“tzname”,“tzset”)

它是'time'模块包含的函数列表。

其他回答

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

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

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

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

对于你不想评估的代码,我推荐一种基于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)]

对于其他一切,inspect模块是正确的:

import inspect

import <module_to_inspect> as module

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

这给出了一个形式为[(<name:str>, <value:function>),…]的二元组列表。

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

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

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

导入模块

module.*?