[TL;DR] Thanks to Alexi - I have a working solution below
I'm trying to figure out Python Classes and inheritence so that I can create a protocol decoder package.
The package needs to work as follows:
- I get a directory full of data files.
- My python code inspects each file, and determines a protocol id number.
- Based on the protocol_id I can calculate (yes, calculate) the file name of the specific decoder.
- If the decoder filename does not exist, I choose some default name
- Need help here: I have the filename in a variable how do I load it?
I've done this before in C code, with Shared Objects, I'm trying create something similar using python.
Part #1 Pseudo code is like this:
def GetDecoderViaId( idnumber ):
filename = "all_decoders/protocol_%04x.py" % idnumber
# Pseudo code use default if special is not found
if (! os.access(filename,os.R_OK)):
filename = "all_decoders/protocol_DEFAULT.py"
# Question #1 How do I do this
# Where each "filename" is a python class.
theclass = import_by_filename( filename )
return theclass
Part #2 - The decoders need to come from a common base class. I have done simple classes, but what does not work is when I try to load them using various techniques I have found via google. I can load something, I just can't seem to call the decoder.
Question#2 How do I do that?
My Decoder Base Class looks like this:
# Simple base class
def DecoderBase(object):
def __init__(id,name,compatlist):
self.id = id
self.name = name
self.compatiblelist = compatlist
def Decode( bytes, byte0, byteN ):
""" Default is just a hex dump """
HexDump( bytes, byte0, byteN )
def GetName(self):
return self.name
def GetId(self):
return self.id
def IsCompatible(id):
return id in self.compatiblelist
Here are two example derived classes, they would be in separate files.
# example: "all_decoders/protocol_1234.py"
class DogDecoder( DecoderBase ):
def __init__():
# pass important things to base constructor
super( DecoderBase, self ).__init__("dog","Snoopy", ["beagle", "peanuts" ])
def Decode( self, byte0, byteN ):
Snoopy specific code goes here
# Example: "all_decoders/protocol_4321.py"
class CatDecoder( DecoderBase ):
def __init__():
# pass important things to base constructor
super( DecoderBase, self ).__init__("cat","Garfield", ["fat-cat", "cartoon-cat" ])
def Decode( self, byte0, byteN ):
Garfield specific code goes here
Can somebody point me to some examples of how to (1) load modules as above and (2) they need to be derived classes and (3) how do I call these things?
[Note: Some edits, typos noticed after I clicked SUBMIT]