如何将Python代码编译为字节码?

问题描述 投票:0回答:2

例如,假设我有 myfile.py。
示例代码:

a = 6
b = 4
print(a+b)

那么如何将其转换为字节码?

我试过这个:

source_code = '''a = 6
b = 4
print(a+b)'''
compiled_code = compile(source_code, '<string>', 'exec')
print(compiled_code.co_code)

结果:

b'\x97\x00d\x00Z\x00d\x01Z\x01\x02\x00e\x02e\x00e\x01z\x00\x00\x00\xa6\x01\x00\x00\xab\x01\x00\x00\x00\ x00\x00\x00\x00\x00\x01\x00d\x02S\x00'

它确实给了我一个字节码,但是当我使用 exec() 运行它时给出了这个错误。

Traceback (most recent call last):
  File "c:\Users\Dimuth De Zoysa\Desktop\Python_projects\OBftestcode.py", line 2, in <module>
    exec(bytecode)
ValueError: source code string cannot contain null bytes

期待有帮助的回复。谢谢。

python compilation exec bytecode
2个回答
0
投票

不要执行你的结果字节码。执行编译后的代码作为编译函数返回的对象,如下所示:

source_code = '''a = 6
b = 4
print(a+b)
''' # good style for using such functions as compile and others is to
#     write new line character at the end of the code
compiled_code = compile(source_code, '<string>', 'exec')
exec(compiled_code)

不要执行

exec(compiled_code.co_code)
,因为它包含转换为可查看形式的字节代码,这样做会产生错误。


-1
投票

尝试下面的代码:

import codecs

source_code = '''a = 6
b = 4
print(a+b)'''

compiled_code = compile(source_code, '<string>', 'exec')

# Convert bytecode to hexadecimal representation
bytecode_hex = codecs.encode(compiled_code.co_code, 'hex')
print(bytecode_hex)

© www.soinside.com 2019 - 2024. All rights reserved.