This is a script to check the sequence number (8 bit unsigned integer) in a binary file and make sure it is incrementing till the end and not missing any sequence number in between. Sequence number is some 'x' bytes from a sentinel found in the binary file. The fixed size packet (some audio data) in binary file gets repeated and this aforementioned packet also has the sentinel along with other audio data.
I am new to python so I'd appreciate a code review.
#!/usr/bin/python
import sys,getopt
def parse_arguments():
def usage():
print("python script to check missing sequence number in a binary file")
print("pass filename, packet_size(optional) and sequence offset where sequence number is found in the packet")
print("python %s -f filename -s packet_size -i sequence_offset"% (sys.argv[0]))
filename, packet_size, sequence_offset = None, 0, None
try:
opts,args = getopt.getopt(sys.argv[1:],'ha:f:i:s:', ['help', 'filename', 'index'])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
if len(opts) != 0:
for (o, a) in opts:
if o in ('-h', '--help'):
usage()
sys.exit()
elif o in ('-f', '--filename'):
filename = a
elif o in ('-s', '--packet_size'):
packet_size = int(a)
elif o in ('-i', '--sequence_offset'):
sequence_offset = int(a)
else:
usage()
sys.exit(2)
else:
usage()
sys.exit(2)
return filename, packet_size, sequence_offset
def is_sequence_missing(filename, packet_size = 5392, sequence_offset = 11):
def get_sequence_idx(filename, sentinel = ['0x4f', '0x5f', '0x4d', '0x41']):
blob = None
with open(filename,"rb") as f:
blob = f.read()
len_sentinel = len(sentinel)
for i in range(len(blob)):
if i + len_sentinel < len(blob) and sentinel == [hex(ord(j)) for j in blob[i:i+len_sentinel]]:
return (blob, i)
return (blob, None)
missing, start, counter = False, True, 0
blob, idx = get_sequence_idx(filename)
if not idx:
print("sentinel not found")
return not missing
print("sentinel starting at 0x%x"% (idx))
for i in range(idx - sequence_offset, len(blob), packet_size):
v = ord(blob[i])
if start:
print("started with sequence number 0x%x"% (v))
start = False
counter = v + 1
continue
if counter == v:
counter += 1
if counter == 256:
counter = 0
else:
print("not matching expected: 0x%x receieved: 0x%x at 0x%x"% (counter, v, i))
counter = v + 1
missing = True
return missing
if __name__ == "__main__":
filename, packet_size, sequence_offset = parse_arguments()
print("passed filename %s packet_size %d sequence_offset %d"% (filename, packet_size, sequence_offset))
if is_sequence_missing(filename, packet_size, sequence_offset) == True:
print("sequence is missing")
else:
print("sequence is not missing")
idx
and don't use it afterwards. What's its use then? \$\endgroup\$