Skip to content

Instantly share code, notes, and snippets.

@abits
Last active February 28, 2026 14:02
Show Gist options
  • Select an option

  • Save abits/5927881fd95cbd76db082a64d2ffd9b3 to your computer and use it in GitHub Desktop.

Select an option

Save abits/5927881fd95cbd76db082a64d2ffd9b3 to your computer and use it in GitHub Desktop.
#!/bin/env python
import py_compile
import argparse
import os
import time
import marshal
import dis
parser = argparse.ArgumentParser(
prog="Python compilation artefacts explorer",
description="Compiles, disassembles and binary-views python source code.",
epilog="""Needs xxd installed. Use like this: 1) compile source file to pyc
compiled python code, 2) disassemble the binary to hexcode as used by python interpreter.""",
)
parser.add_argument("-c", "--compile")
parser.add_argument("-d", "--disassemble")
args = parser.parse_args()
def compile_file(target):
"""Compiles python source file to hexcode binary."""
fname = os.path.join(
os.path.dirname(target), os.path.splitext(os.path.basename(target))[0]
)
obj_name = f"{fname}.pyc"
t_start = time.perf_counter()
py_compile.compile(target, obj_name)
t_stop = time.perf_counter()
msg = f"Compiled {target} to {obj_name} in {t_stop-t_start:.4f} seconds."
print(msg)
def view_pyc_file(target):
"""Reads compiled python file and disassembles to hex code as used by
interpreter"""
with open(target, "rb") as file:
file.seek(16)
code = marshal.load(file)
dis.disassemble(code)
if __name__ == "__main__":
if args.compile:
compile_file(args.compile)
elif args.disassemble:
view_pyc_file(args.disassemble)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment