如何在不导入的情况下获取已编译Python模块的函数名?
我正在创建一个智能提示模块,用户可以输入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