Python3读取.pyc文件
demo.py
x = 123
def hello():
t = (1,2)
class User: pass
run.py
import sys
import demo
import types
import marshal
import dis
def show_code(code, indent=''):
print(f"{indent}code")
indent += ' '
print(f"{indent}argcount {code.co_argcount}")
print(f"{indent}nlocals {code.co_nlocals}")
print(f"{indent}stacksize {code.co_stacksize}")
print(f"{indent}flags {code.co_flags:04x}")
dis.disassemble(code)
print(f"{indent}consts")
for const in code.co_consts:
if isinstance(const, types.CodeType):
show_code(const, indent + ' ')
else:
print(f" {indent}{const}")
print(f"{indent}names {code.co_names}")
print(f"{indent}varnames {code.co_varnames}")
print(f"{indent}freevars {code.co_freevars}")
print(f"{indent}cellvars {code.co_cellvars}")
print(f"{indent}filename {code.co_filename}")
print(f"{indent}name {code.co_name}")
print(f"{indent}firstlineno {code.co_firstlineno}")
def show_file():
header_sizes = [(8, (0, 9, 2)), (12, (3, 6)), (16, (3, 7))]
header_size = next(s for s, v in reversed(header_sizes) if sys.version_info >= v)
print(isinstance(demo, types.ModuleType))
with open(demo.__cached__, "rb") as f:
metadata = f.read(header_size)
code = marshal.load(f)
print(code)
show_code(code)
if __name__ == '__main__':
show_file()