Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a python .pyc file, is there a tool that let me view the bytecode?

A Python module is automatically compiled into a .pyc file by CPython interpreter. The .pyc file, which contains the bytecode, is in binary format (marshaled code?). Is there a GUI (or command line) tool that let me view the bytecode?

like image 635
dividebyzero Avatar asked Jun 21 '12 15:06

dividebyzero


People also ask

How do you find the byte code in Python?

Byte Code is automatically created in the same directory as . py file, when a module of python is imported for the first time, or when the source is more recent than the current compiled file. Next time, when the program is run, python interpretator use this file to skip the compilation step.

How do I view a .PYC file?

If you cannot open your PYC file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a PYC file directly in the browser: Just drag the file onto this browser window and drop it.


1 Answers

Extending the code form @PADYMKO based on @Apteryx 's note about the PEP:

def view_pyc_file(path):
    """Read and display a content of the Python`s bytecode in a pyc-file."""

    file = open(path, 'rb')

    magic = file.read(4)
    bit_field = None
    timestamp = None
    hashstr = None
    size = None

    if sys.version_info.major == 3 and sys.version_info.minor >=7:
        bit_field = int.from_bytes(file.read(4), byteorder=sys.byteorder)
        if 1 & bit_field == 1:
            hashstr = file.read(8)
        else:
            timestamp = file.read(4)
            size = file.read(4)
            size = struct.unpack('I', size)[0]
    elif sys.version_info.major == 3 and sys.version_info.minor >= 3:
        timestamp = file.read(4)
        size = file.read(4)
        size = struct.unpack('I', size)[0]
    else:
        timestamp = file.read(4)

    code = marshal.load(file)

    magic = binascii.hexlify(magic).decode('utf-8')
    timestamp = time.asctime(time.localtime(struct.unpack('I', b'D\xa5\xc2X')[0]))

    dis.disassemble(code)

    print('-' * 80)
    print(
        'Python version: {}\nMagic code: {}\nTimestamp: {}\nSize: {}\nHash: {}\nBitfield: {}'
        .format(platform.python_version(), magic, timestamp, size, hashstr, bit_field)
    )

    file.close()
like image 177
powersource97 Avatar answered Oct 06 '22 19:10

powersource97