[Python] How to compile Python code into byte code and the run it?

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    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(compiled_code.co_code)
    ValueError: source code string cannot contain null bytes

    Continue reading...

Compartilhe esta Página