bcode.py
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 """
00016 Python Byte Code utility functions.
00017
00018 count(fn) - count the number of times each byte code
00019 appears in a code object.
00020 """
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 import dis, types
00034
00035
00036
00037 MAX_BCODE = 150
00038
00039
00040 def count(fn):
00041 """
00042 Compile the python source file named fn.
00043 Count all the bytecodes in the file.
00044 Return a list of counts indexed by bcode.
00045 """
00046
00047
00048 src = open(fn).read()
00049 co = compile(src, fn, "exec")
00050
00051
00052 cnt = [0,] * MAX_BCODE
00053
00054
00055 _rcount(co, cnt)
00056
00057 return cnt
00058
00059
00060 def _rcount(co, count):
00061 """
00062 Recursively descend through all the code objects
00063 in the given code object, co.
00064 Add byte code counts to the count dict.
00065 """
00066
00067 str = co.co_code
00068 strlen = len(str)
00069
00070
00071 i = 0
00072 while i < strlen:
00073 bcode = ord(str[i])
00074 i += 1
00075
00076 count[bcode] += 1
00077
00078
00079 if bcode >= 90:
00080 i += 2
00081
00082
00083 for obj in co.co_consts:
00084 if type(obj) == types.CodeType:
00085 _rcount(obj, count)
00086
00087 return
00088
00089
00090 def main(fn):
00091 """
00092 Count the bytecodes in the file, fn,
00093 and print them out in human-readable form.
00094 """
00095
00096 c = count(fn)
00097
00098
00099 for i in range(len(c)):
00100 if c[i]:
00101 print dis.opname[i], ":\t", c[i]
00102 return
00103
00104
00105 if __name__ == "__main__":
00106 main("c:\\dwh\\tech\\cis\\py\\snap.py")