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?
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With