如何列出的所有功能在Python模块?
-
02-07-2019 - |
题
我有一个python模块安装在我的系统和我想要能够看到什么职能/课程/方法可用。
我想打电话给医生的功能上的每一个。在红宝石我可以做的东西喜欢ClassName。方法,以获得一个名单的所有方法可用于这一类。是否有类似的东西在蟒蛇?
例如。是这样的:
from somemodule import foo
print foo.methods # or whatever is the correct method to call
其他提示
您可以使用dir(module)
查看所有可用的方法/属性。还可以查看PyDocs。
一旦你import
编辑模块,你就可以这样做:
help(modulename)
...以交互方式立即获取所有功能的文档。或者您可以使用:
dir(modulename)
...简单地列出模块中定义的所有函数和变量的名称。
检查的一个例子:
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)元组列表。
您可以使用inspect模块中的任何其他isXXX函数替换isfunction。
import types
import yourmodule
print([getattr(yourmodule, a) for a in dir(yourmodule)
if isinstance(getattr(yourmodule, a), types.FunctionType)])
为了完整起见,我想指出有时你可能想要解析代码而不是导入代码。 import
将执行顶级表达式,这可能是个问题。
例如,我让用户为使用 zipapp制作的软件包选择入口点函数。使用inspect
和list.py
冒着运行误入代码的风险,导致崩溃,帮助打印出消息,弹出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)
将此代码放入foo = lambda x,y: x*y
并使用自身作为输入,我得到:
$ python list.py list.py
list.py
top_level_functions
parse_ast
当然,导航AST有时会很棘手,即使是像Python这样相对简单的语言,因为AST非常低级。但是如果你有一个简单明了的用例,它既可行又安全。
但是,缺点是您无法检测在运行时生成的函数,例如<=>。
这样可以解决问题:
dir(module)
但是,如果您发现阅读返回的列表很烦人,只需使用以下循环为每行获取一个名称。
for i in dir(module): print i
dir(module)
是的标准方法时使用脚本或标准的解释,因为提到的大多数答复。
但是与一个交互式python壳喜欢 IPython 你可以使用项完成得到一个概述的所有对象的定义中的模块。这是更方便于使用一个脚本 print
看看什么是定义中的模块。
module.<tab>
会告诉你所有的对象,定义中的模块(功能、类和以上)module.ClassX.<tab>
会告诉你的方法和属性的一类module.function_xy?
或module.ClassX.method_xy?
会告诉你的文档字符串的功能/方法module.function_x??
或module.SomeClass.method_xy??
会告诉你的源代码的功能/方法。
对于您不想解析的代码,我推荐上面基于AST的@csl方法。
对于其他一切,检查模块是正确的:
import inspect
import <module_to_inspect> as module
functions = inspect.getmembers(module, inspect.isfunction)
这给出了[(<name:str>, <value:function>), ...]
形式的2元组列表。
上面的简单答案在各种回复和评论中都有所暗示,但没有明确说明。
对于全局函数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__吗?以使用import *
。
以下是一个例子:
>>> 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']
>>>
所有带下划线的函数和类都已删除,只留下那些被定义为公共的函数和类,因此可以通过AttributeError
使用。
请注意,并非始终定义<=>。如果未包含,则引发<=>。
这种情况与ast模块有关:
>>> import ast
>>> ast.__all__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>
如果您无法在没有导入错误的情况下导入所述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])
除了之前答案中提到的dir(模块)或帮助(模块),您还可以尝试:
- 打开ipython
- import 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
您可以使用以下方法从shell中列出模块中的所有函数:
import module
module.*?
这会将your_module中定义的所有函数附加到列表中。
result=[]
for i in dir(unit8_conversion_methods):
if type(getattr(your_module, i)).__name__ == "function":
result.append(getattr(your_module, i))
使用dir(模块)不是(或至少不再适用)。代码应如下所示:
dir('module') or dir('modules')
或者您指定所需的模块:dir('sys')
从模块名称sys生成结果。 dir()
在dir('')
是您需要的时候返回错误。 * help('')将返回大多数功能可用的帮助信息。例如; help('modules')
将返回模块帮助信息。
感谢所有的选票。当我发布这个时,我正在使用Python3.2.2和其他3x版本。关键是要使用('stuff')而不是之前的(东西)。但是我假设你的所有人都坚持使用Python2或使用更新版本的PC而不是像我一样的手机。