From 2ee47fc8d1e3c6089e3e358603dadca913a4527c Mon Sep 17 00:00:00 2001 From: Radhika Jagtap Date: Sun, 10 Aug 2014 05:39:20 -0400 Subject: util: Move packet trace file read to protolib This patch moves the code for opening an input protobuf packet trace into a function defined in the protobuf library. This is because the code is commonly used in decode scripts and is independent of the src protobuf message. --- util/protolib.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'util/protolib.py') diff --git a/util/protolib.py b/util/protolib.py index e085a90f2..e0507cdd4 100644 --- a/util/protolib.py +++ b/util/protolib.py @@ -71,8 +71,33 @@ # with protobuf python messages. For eg, the decode scripts for different # types of proto objects can use the same function to decode a single message +import gzip import struct +def openFileRd(in_file): + """ + This opens the file passed as argument for reading using an appropriate + function depending on if it is gzipped or not. It returns the file + handle. + """ + try: + # First see if this file is gzipped + try: + # Opening the file works even if it is not a gzip file + proto_in = gzip.open(in_file, 'rb') + + # Force a check of the magic number by seeking in the + # file. If we do not do it here the error will occur when + # reading the first message. + proto_in.seek(1) + proto_in.seek(0) + except IOError: + proto_in = open(in_file, 'rb') + except IOError: + print "Failed to open ", in_file, " for reading" + exit(-1) + return proto_in + def DecodeVarint(in_file): """ The decoding of the Varint32 is copied from -- cgit v1.2.3