如何在不导入的情况下获取已编译Python模块的函数名?

2 投票
1 回答
598 浏览
提问于 2025-04-18 08:20

我正在创建一个智能提示模块,用户可以输入Python代码,然后输出一个包含函数和变量名称等信息的字典。使用import会执行代码中的任何顶层语句,所以我不想用这个。相反,我使用ast模块。这个方法适用于.py文件,但不适用于.pyc或.so文件,因为ast.parse()实际上会编译代码,而.so文件已经被编译过了。那么,有没有办法在不使用import的情况下,从一个已编译的模块中获取函数和变量名称以及文档字符串呢?

[为了更清晰而编辑]

# re module is .py
import ast, imp
file_object, module_path, description = imp.find_module('re')
src = file_object.read()
tree = ast.parse(source=src, filename=module_path, mode='exec')
for node in tree.body:
    print node

# datetime module is .so
file_object, module_path, description = imp.find_module('datetime')
src = file_object.read()
tree = ast.parse(source=src, filename=module_path, mode='exec')
for node in tree.body:
    print node


 File "test_ast.py", line 12, in <module>
   tree = ast.parse(source=src, filename=module_path, mode='exec')
 File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
   return compile(source, filename, mode, PyCF_ONLY_AST)
TypeError: compile() expected string without null bytes

1 个回答

1

对于C语言的扩展,你别无选择,只能导入它们并使用自省功能。

Komodo的CodeIntel使用从模块生成的独立数据文件(通过自省功能)或者手动编写的数据,来为C语言扩展提供自动补全所需的信息。例如,它的自动补全工具就会使用这些静态数据。

CodeIntel项目是开源的代码;你可以参考 这个链接这个链接 来获取灵感,或者研究一下 这个工具集的源代码

撰写回答