What is the Pythonic way to implement a simple FSM?

后端 未结 7 1629
猫巷女王i
猫巷女王i 2021-01-31 21:50

Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 byte

7条回答
  •  孤独总比滥情好
    2021-01-31 22:38

    You could give your states constant names instead of using 0, 1, 2, etc. for improved readability.

    You could use a dictionary to map (current_state, input) -> (next_state), but that doesn't really let you do any additional processing during the transitions. Unless you include some "transition function" too to do extra processing.

    Or you could do a non-FSM approach. I think this will work as long as 0xAA 0xAA only appears when it indicates a "start" (doesn't appear in data).

    with open(sys.argv[1], 'rb') as f:
        contents = f.read()
        for chunk in contents.split('\xaa\xaa')[1:]:
            length = ord(chunk[0])
            data = chunk[10:10+length]
            print data
    

    If it does appear in data, you can instead use string.find('\xaa\xaa', start) to scan through the string, setting the start argument to begin looking where the last data block ended. Repeat until it returns -1.

提交回复
热议问题