Dimuth De Zoysa
Dimuth De Zoysa

Reputation: 61

How to compile Python code into byte code?

For example imagine I have myfile.py.
sample code:

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

So how can I convert this into bytecode?

I tried this:

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

Result:

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'

It does give me a bytecode, but when I run it using exec(), it results in this error.

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

How can I hide the source code while exec bytecode?

Upvotes: 1

Views: 2295

Answers (3)

Steven Dickinson
Steven Dickinson

Reputation: 344

See https://docs.python.org/3/library/functions.html#exec and https://docs.python.org/3/library/functions.html#compile

exec(compiled_code) will work just fine.

Were you trying to exec the string representation instead of the actual code_object by mistake?

Upvotes: 1

TimKostenok
TimKostenok

Reputation: 93

Don't execute your result bytecode. Execute compiled code as an object returned by compile function like this:

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)

Do not execute exec(compiled_code.co_code), as it contains byte code translated to viewable form, and doing this gives your error.

Upvotes: 1

purval_patel
purval_patel

Reputation: 425

Try below code:

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)

Upvotes: -2

Related Questions