mod
不是常规的python模块对象;它是
modulefinder.Module
globalnames
验证
__version__
通过检查映射:
for name, mod in sorted(finder.modules.items()):
ver = mod.globalnames.get('__version__', '--')
print(name, ver, mod.__file__)
1
未加载
您要么必须实际导入模块,要么自己进行字节码分析以获取
全局名称。这个
Module
__code__
属性可以扫描以查看堆栈上的值
正在存储:
import dis
def load_version_string(codeobj):
"""Returns the constant value loaded for the `__version__` global
Requires that `__version__` is set from a literal constant value.
"""
instructions = dis.get_instructions(codeobj)
for instr in instructions:
if instr.opname == 'LOAD_CONST':
nxtop = next(instructions, None)
if nxtop.opname == 'STORE_NAME' and nxtop.argval == '__version__':
return instr.argval
for name, mod in sorted(finder.modules.items()):
ver = '--'
if '__version__' in mod.globalnames:
ver = load_version_string(mod.__code__)
print(name, ver, mod.__file__)
现在的输出
__main__
$ python3 demo.py | grep __main__
__main__ 1.1.1 demo.py