# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt """ Dump the contents of a .pyc file. The output will only be correct if run with the same version of Python that produced the .pyc. """ import binascii import dis import marshal import struct import sys import time import types def show_pyc_file(fname): f = open(fname, "rb") magic = f.read(4) print("magic %s" % (binascii.hexlify(magic))) read_date_and_size = True if sys.version_info >= (3, 7): # 3.7 added a flags word flags = struct.unpack('= (3, 3): # 3.3 added another long to the header (size). size = f.read(4) print("pysize %s (%d)" % (binascii.hexlify(size), struct.unpack('= (3,): def bytes_to_ints(bytes_value): return bytes_value else: def bytes_to_ints(bytes_value): for byte in bytes_value: yield ord(byte) def lnotab_interpreted(code): # Adapted from dis.py in the standard library. byte_increments = bytes_to_ints(code.co_lnotab[0::2]) line_increments = bytes_to_ints(code.co_lnotab[1::2]) last_line_num = None line_num = code.co_firstlineno byte_num = 0 for byte_incr, line_incr in zip(byte_increments, line_increments): if byte_incr: if line_num != last_line_num: yield (byte_num, line_num) last_line_num = line_num byte_num += byte_incr if sys.version_info >= (3, 6) and line_incr >= 0x80: line_incr -= 0x100 line_num += line_incr if line_num != last_line_num: yield (byte_num, line_num) def flag_words(flags, flag_defs): words = [] for word, flag in flag_defs: if flag & flags: words.append(word) return ", ".join(words) def show_file(fname): if fname.endswith('pyc'): show_pyc_file(fname) elif fname.endswith('py'): show_py_file(fname) else: print("Odd file:", fname) def main(args): if args[0] == '-c': show_py_text(" ".join(args[1:]).replace(";", "\n")) else: for a in args: show_file(a) if __name__ == '__main__': main(sys.argv[1:])