我正在创建一个 intellisense 类型的模块,您可以在其中输入 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
请您参考如下方法:
对于 C 扩展,您别无选择,只能导入它们并使用内省(introspection)。
例如,Komodo 的 CodeIntel 使用从模块生成的单独数据文件(使用内省(introspection))或以其他方式手动编写以为其提供 C 扩展的自动完成元数据。然后他们的自动完成器使用这个静态数据。
CodeIntel 项目是开源代码;见http://community.activestate.com/faq/codeintel-cix-schema和 http://community.activestate.com/faq/generate-python-api-catalog寻求灵感,和/或研究the source code of the toolset .
