如何列出模块中的所有函数?

发布于 2024-07-06 22:36:47 字数 298 浏览 13 评论 0 原文

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

我想调用每个函数的 help 函数。 在 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 help 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?

e.g. something like:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

清风不识月 2024-07-13 22:36:47

您可以使用 dir(module) 来查看所有可用的方法/属性。 另请查看 PyDocs。

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

随风而去 2024-07-13 22:36:47

使用 inspect 模块:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

另请参阅pydoc 模块,help() 函数和 pydoc 命令行工具可生成您想要的文档。 您只需向他们提供您希望查看其文档的课程即可。 例如,它们还可以生成 HTML 输出并将其写入磁盘。

Use the inspect module:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

Also see the pydoc 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.

<逆流佳人身旁 2024-07-13 22:36:47

一旦您导入模块,您就可以执行以下操作:

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.

拿命拼未来 2024-07-13 22:36:47

使用 inspect.getmembers 获取模块中的所有变量/类/函数等,并传入 < code>inspect.isfunction 作为仅获取函数的谓词:

from inspect import getmembers, isfunction
from my_project import my_module
    
functions_list = getmembers(my_module, isfunction)

getmembers 返回按字母顺序排序的元组列表 (object_name, object)姓名。

您可以将 isfunction 替换为 isXXX 函数rel="noreferrer">检查模块

Use inspect.getmembers to get all the variables/classes/functions etc. in a module, and pass in inspect.isfunction as the predicate to get just the functions:

from inspect import getmembers, isfunction
from my_project import my_module
    
functions_list = getmembers(my_module, isfunction)

getmembers returns a list of tuples (object_name, object) sorted alphabetically by name.

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

梦在夏天 2024-07-13 22:36:47
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)])
煞人兵器 2024-07-13 22:36:47

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

例如,我让用户为使用 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.

黎夕旧梦 2024-07-13 22:36:47

对于您不想评估的代码,我建议使用基于 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)]

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

import inspect

import <module_to_inspect> as module

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

这给出了 [(, , , ) 形式的 2 元组列表。值:函数>), ...]

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

For code that you do not wish to evaluate, I recommend an AST-based approach (like csl's answer), e.g.:

import ast

source = open(<filepath_to_parse>).read()
functions = [f.name for f in ast.parse(source).body
             if isinstance(f, ast.FunctionDef)]

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.

暗喜 2024-07-13 22:36:47

这可以解决问题:

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
秋意浓 2024-07-13 22:36:47

正如大多数答案中提到的那样, dir(module) 是使用脚本或标准解释器时的标准方法。

但是,使用像 IPython 这样的交互式 python shell,您可以使用制表符补全来获取模块中定义的所有对象的概述。
这比使用脚本和 print 来查看模块中定义的内容要方便得多。

  • module. 将显示模块中定义的所有对象(函数、类等)
  • module.ClassX. 将显示方法类 module.function_xy?module.ClassX.method_xy? 的属性
  • 将显示该函数/方法
  • module.function_x?? 的文档字符串code> 或 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.
若水微香 2024-07-13 22:36:47

对于全局函数 dir() 是要使用的命令(如大多数答案中所述),但是这同时列出了公共函数和非公共函数。

例如运行:

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

返回如下函数/类:

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

其中一些通常不用于一般编程用途(但由模块本身使用,除了 DunderAliases 的情况,如 __doc____file__ 等)。 因此,将它们与公共的一起列出可能没有用(这就是 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']
>>>

所有带有下划线的函数和类都已被删除,只留下那些定义为公共的、因此可以通过 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__'
>>>
画尸师 2024-07-13 22:36:47

如果您无法在没有导入错误的情况下导入所述 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])
兰花执着 2024-07-13 22:36:47

在当前脚本中查找名称(和可调用对象)__main__

我试图创建一个独立的 python 脚本,该脚本仅使用标准库来查找当前文件中带有前缀 task_< 的函数/code> 创建 npm run 提供的最小自制版本。

TL;DR

如果您正在运行独立脚本,则希望在 sys.modules['__main__']< 中定义的 module 上运行 inspect.getmembers /代码>。 例如,

inspect.getmembers(sys.modules['__main__'], inspect.isfunction)

但我想按前缀过滤方法列表并删除前缀以创建查找字典。

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

示例输出:

{
 'install': <function task_install at 0x105695940>,
 'dev': <function task_dev at 0x105695b80>,
 'test': <function task_test at 0x105695af0>
}

较长版本

我想要定义 CLI 任务名称的方法名称,而不必重复自己。

./tasks.py

#!/usr/bin/env python3
import sys
from subprocess import run

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

def _cmd(command, args):
    return run(command.split(" ") + args)

def task_install(args):
    return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)

def task_test(args):
    return _cmd("python3 -m pytest", args)

def task_dev(args):
    return _cmd("uvicorn api.v1:app", args)

if __name__ == "__main__":
    tasks = _inspect_tasks()

    if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():
        tasks[sys.argv[1]](sys.argv[2:])
    else:
        print(f"Must provide a task from the following: {list(tasks.keys())}")

无参数示例:

λ ./tasks.py
Must provide a task from the following: ['install', 'dev', 'test']

使用额外参数运行测试的示例:

λ ./tasks.py test -qq
s.ssss.sF..Fs.sssFsss..ssssFssFs....s.s    

您明白了。 随着我的项目越来越多,保持脚本更新比保持自述文件更新更容易,我可以将其抽象为:

./tasks.py install
./tasks.py dev
./tasks.py test
./tasks.py publish
./tasks.py logs

Finding the names (and callable objects) in the current script __main__

I was trying to create a standalone python script that used only the standard library to find functions in the current file with the prefix task_ to create a minimal homebrewed version of what npm run provides.

TL;DR

If you are running a standalone script you want to run inspect.getmembers on the module which is defined in sys.modules['__main__']. Eg,

inspect.getmembers(sys.modules['__main__'], inspect.isfunction)

But I wanted to filter the list of methods by prefix and strip the prefix to create a lookup dictionary.

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

Example Output:

{
 'install': <function task_install at 0x105695940>,
 'dev': <function task_dev at 0x105695b80>,
 'test': <function task_test at 0x105695af0>
}

Longer Version

I wanted the names of the methods to define CLI task names without having to repeat myself.

./tasks.py

#!/usr/bin/env python3
import sys
from subprocess import run

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

def _cmd(command, args):
    return run(command.split(" ") + args)

def task_install(args):
    return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)

def task_test(args):
    return _cmd("python3 -m pytest", args)

def task_dev(args):
    return _cmd("uvicorn api.v1:app", args)

if __name__ == "__main__":
    tasks = _inspect_tasks()

    if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():
        tasks[sys.argv[1]](sys.argv[2:])
    else:
        print(f"Must provide a task from the following: {list(tasks.keys())}")

Example no arguments:

λ ./tasks.py
Must provide a task from the following: ['install', 'dev', 'test']

Example running test with extra arguments:

λ ./tasks.py test -qq
s.ssss.sF..Fs.sssFsss..ssssFssFs....s.s    

You get the point. As my projects get more and more involved, it's going to be easier to keep a script up to date than to keep the README up to date and I can abstract it down to just:

./tasks.py install
./tasks.py dev
./tasks.py test
./tasks.py publish
./tasks.py logs
那请放手 2024-07-13 22:36:47

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

import module

module.*?

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

import module

module.*?
多情出卖 2024-07-13 22:36:47

使用 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< code>inspect.getmembers 的优点是它按照定义的顺序返回函数,而不是按字母顺序排序。

另外,这将包括由 my_module 导入的函数,如果您想过滤掉这些函数以仅获取 my_module 中定义的函数,请参阅我的问题获取Python模块中所有定义的函数

Use vars(module) then filter out anything that isn't a function using inspect.isfunction:

import inspect
import my_module

my_module_functions = [f for f in vars(my_module).values() if inspect.isfunction(f)]

The advantage of vars over dir or inspect.getmembers is that it returns the functions in the order they were defined instead of sorted alphabetically.

Also, this will include functions that are imported by my_module, if you want to filter those out to get only functions that are defined in my_module, see my question Get all defined functions in Python module.

孤云独去闲 2024-07-13 22:36:47
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)]
初雪 2024-07-13 22:36:47

除了前面的答案中提到的 dir(module) 或 help(module) 之外,您还可以尝试:
- 打开 ipython
- 导入模块名称
- 输入 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
慈悲佛祖 2024-07-13 22:36:47
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
陈甜 2024-07-13 22:36:47

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

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

例如,dir(time)将返回

['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime ', 'ctime', '日光', 'get_clock_info', 'gmtime', '本地时间', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']

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

The Python documentation provides the perfect solution for this which uses the built-in function dir.

You can just use dir(module_name) and then it will return a list of the functions within that module.

For example, dir(time) will return

['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']

which is the list of functions the 'time' module contains.

寒江雪… 2024-07-13 22:36:47

这会将 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))
↙温凉少女 2024-07-13 22:36:47

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

# 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 Woutersadrian 这里,以及来自 Sebastian Rittau 的另一个问题。

If you want to get the list of all the functions defined in the current file, you can do it that way:

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

As an application example, I use that for calling all the functions defined in my unit testing scripts.

This is a combination of codes adapted from the answers of Thomas Wouters and adrian here, and from Sebastian Rittau on a different question.

等待圉鍢 2024-07-13 22:36:47

help() 函数效果更好

 import somemodule
 help(somemodule)

The help() function works better

 import somemodule
 help(somemodule)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文