[英]How to get function names from compiled Python module without importing it?
我正在創建一個intellisense類型模塊,您在其中輸入python代碼並輸出函數和變量名的字典等。使用import
會執行代碼中的所有頂級語句,因此我寧願不使用它。 相反,我使用的是ast
模塊。 它適用於.py模塊,但不適用於.pyc或.so模塊,因為ast.parse()
實際上可以編譯代碼,而.so已被編譯。 那么有沒有辦法在不使用import
情況下從已編譯的模塊中獲取函數和變量名以及docstring?
[為清楚起見而編輯]
# 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擴展,除了導入它們並使用自省功能外,您別無選擇。
例如,Komodo的CodeIntel使用了從模塊生成的單獨數據文件(使用自省),或者使用其他方式手動編寫了數據文件,以為其提供C擴展的自動完成元數據。 然后,他們的自動完成程序將使用此靜態數據。
CodeIntel項目是開源代碼。 請參閱http://community.activestate.com/faq/codeintel-cix-schema和http://community.activestate.com/faq/generate-python-api-catalog以獲得靈感,和/或研究該代碼的源代碼。工具集 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.