问题:如何列出Python模块中的所有功能?

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

我想在每个函数上调用doc函数。在ruby中,我可以执行ClassName.methods之类的操作来获取该类上所有可用方法的列表。python中是否有类似的东西?

例如。就像是:

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

I have a python module installed on my system and I’d like to be able to see what functions/classes/methods are available in it.

I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?

eg. something like:

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

回答 0

模块。另请参阅模块,help()交互式解释器中的功能以及pydoc生成所需文档的命令行工具。您可以给他们想要查看其文档的类。他们还可以生成例如HTML输出并将其写入磁盘。

The module. Also see the module, the help() function in the interactive interpreter and the pydoc command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.


回答 1

您可以dir(module)用来查看所有可用的方法/属性。还要检查PyDocs。

You can use dir(module) to see all available methods/attributes. Also check out PyDocs.


回答 2

一旦你import编的模块,你可以做:

 help(modulename)

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

 dir(modulename)

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

Once you’ve imported the module, you can just do:

 help(modulename)

… To get the docs on all the functions at once, interactively. Or you can use:

 dir(modulename)

… To simply list the names of all the functions and variables defined in the module.


回答 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函数。

An example with 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 returns a list of (object_name, object_type) tuples.

You can replace isfunction with any of the other isXXX functions in the inspect module.


回答 4

import types
import yourmodule

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

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

回答 5

为了完整起见,我想指出,有时您可能想解析代码而不是导入代码。一个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

当然,即使对于像Python这样的相对简单的语言,导航AST有时也会很棘手,因为AST的层次很低。但是,如果您有一个简单明了的用例,那么它既可行又安全。

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

For completeness’ sake, I’d like to point out that sometimes you may want to parse code instead of importing it. An import will execute top-level expressions, and that could be a problem.

For example, I’m letting users select entry point functions for packages being made with zipapp. Using import and inspect risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.

Instead I use the ast module to list all the top-level functions:

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)

Putting this code in list.py and using itself as input, I get:

$ python list.py list.py
list.py
  top_level_functions
  parse_ast

Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it’s both doable and safe.

Though, a downside is that you can’t detect functions that are generated at runtime, like 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>), ...]

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

For code that you do not wish to parse, I recommend the AST-based approach of @csl above.

For everything else, the inspect module is correct:

import inspect

import <module_to_inspect> as module

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

This gives a list of 2-tuples in the form [(<name:str>, <value:function>), ...].

The simple answer above is hinted at in various responses and comments, but not called out explicitly.


回答 7

这将达到目的:

dir(module) 

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

for i in dir(module): print i

This will do the trick:

dir(module) 

However, if you find it annoying to read the returned list, just use the following loop to get one name per line.

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??将显示函数/方法的源代码。

dir(module) is the standard way when using a script or the standard interpreter, as mentioned in most answers.

However with an interactive python shell like IPython you can use tab-completion to get an overview of all objects defined in the module. This is much more convenient, than using a script and print to see what is defined in the module.

  • module.<tab> will show you all objects defined in the module (functions, classes and so on)
  • module.ClassX.<tab> will show you the methods and attributes of a class
  • module.function_xy? or module.ClassX.method_xy? will show you the docstring of that function / method
  • module.function_x?? or module.SomeClass.method_xy?? will show you the source code of the function / method.

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

For global functions dir() is the command to use (as mentioned in most of these answers), however this lists both public functions and non-public functions together.

For example running:

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

Returns functions/classes like:

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

Some of which are not generally meant for general programming use (but by the module itself, except in the case of DunderAliases like __doc__, __file__ ect). For this reason it may not be useful to list them with the public ones (this is how Python knows what to get when using from module import *).

__all__ could be used to solve this problem, it returns a list of all the public functions and classes in a module (those that do not start with underscores – _). See Can someone explain __all__ in Python? for the use of __all__.

Here is an example:

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

All the functions and classes with underscores have been removed, leaving only those that are defined as public and can therefore be used via import *.

Note that __all__ is not always defined. If it is not included then an AttributeError is raised.

A case of this is with the ast module:

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

None of these answers will work if you are unable to import said Python file without import errors. This was the case for me when I was inspecting a file which comes from a large code base with a lot of dependencies. The following will process the file as text and search for all method names that start with “def” and print them and their line numbers.

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

Except dir(module) or help(module) mentioned in previous answers, you can also try:
– Open ipython
– import module_name
– type module_name, press tab. It’ll open a small window with listing all functions in the python module.
It looks very neat.

Here is snippet listing all functions of hashlib module

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

This will append all the functions that are defined in your_module in a list.

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.*?

You can use the following method to get list all the functions in your module from shell:

import module

module.*?

回答 14

import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]
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
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)

Output :

******************************************************************************************
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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。