AttributeError: 'float' 对象没有属性 'co_names'

问题描述

pyc 文件的简单检查脚本 co_name 函数有问题 脚本运行良好,直到 ma​​rshal 模块加载然后下降。

magic: 160d0d0a
mod_time: 1493965574
source_size: 231

code:
Traceback (most recent call last):
  File "/home/ubuntu/Downloads/book-resources-master/chapter4/code-exec-eg/python/inspect.py",line 24,in <module>
    inspect_code(code)
  File "/home/ubuntu/Downloads/book-resources-master/chapter4/code-exec-eg/python/inspect.py",line 8,in inspect_code
    print('{}{}(line:{})'.format(indent,code.co_names,code.co_firstlineno))
AttributeError: 'float' object has no attribute 'co_names'

如果有人可以帮忙! 谢谢

import marshal
import types

def to_long(s):
    return s[0] + (s[1] << 8) + (s[2] << 16) + (s[3] << 24)

def inspect_code(code,indent='    '):
    print('{}{}(line:{})'.format(indent,code.co_firstlineno))
    for c in code.co_consts:
        if isinstance(c,types.CodeType):
            inspect_code(c,indent + '    ')

f = open('__pycache__/add.cpython-39.pyc','rb')

magic = f.read(4)
print('magic: {}'.format(magic.hex()))
mod_time = to_long(f.read(4))
print('mod_time: {}'.format(mod_time))
source_size = to_long(f.read(4))
print('source_size: {}'.format(source_size))

print('\ncode:')
code = marshal.load(f)
inspect_code(code)

f.close()

import dis
dis.disassemble(code)

解决方法

我不熟悉 marshal 模块和 pyc 内容,但是当我使用 Python 3.9 尝试您的代码时, 我在读取代码值时出错。对于我使用 Python 3.9 构建的示例 pyc,文件格式似乎有所不同。

magic: 610d0d0a
mod_time: 0 # <---- Unknown
source_size: 1621462747 # <---- Must be mode time

当我在读取代码值之前再读取 4 个字节时,我得到了这个:

magic: 610d0d0a
mod_time: 0
source_size: 1621462747
4 more bytes: 14 # <----- Must be source size

然后我可以读取代码值:

code:
    ('print',)(line:1)
  1           0 LOAD_NAME                0 (print)
              2 LOAD_CONST               0 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               1 (None)
             10 RETURN_VALUE

我不知道为什么您可以毫无错误地运行 marshal.load(),但是您可以在调用 marshal.load(f) 之前尝试读取更多或更少的字节吗?