如何在python中使用switch case,在每种情况下分别调用特定函数?

时间:2019-12-16 12:21:31

标签: python

我编写了这段代码,其中我必须从文件中读取指令并必须识别每条指令,最后我要将这些指令放在列表中。

我创建了一个对象列表来描述每条指令(操作码,源..)

我的问题是,当我从文件中读取每一行(指令)时,我想获取指令的操作码以了解如何工作并从指令行中提取其他信息 我试图像这样切换大小写:

def OpcodeSwitcher(inst_opcode) :
    switcher = {
         'ADD': add_sub_branch(line), #function I call when the instruction is ADD
         'SUB': print(1)
 }

然后调用此函数,该函数是我从行中提取的操作码,但是在无限循环中被击中了!

我只是想不通,有什么帮助吗?

这是一个非常小的文件的示例:

ADD $3, $0, 4
SUB $7, $0, 1
# Program ends with infinite loop (avoid fall-through to undefined data following the end of the program)
# Data for this program. Any other location that is not explicitly set is implicitly set to zero.
D@0x000032A0
0x12345678
0xFFFFFFFF

这是主文件:

    import sys
    import memory as Memory


    # main

    file_name = sys.argv[1]
    print("Loading memory image file:", file_name)
    Memory.sim_mem_reset(file_name)

这是内存文件:

    import sys


    instructionsList = []


    class Sim_cmd(object) :
        def __init__(self, opcode, src1, src2,isSrc2Imm,dst) :
            self.opcode=opcode
            self.src1=src1
            self.src2=src2
            self.isSrc2Imm=isSrc2Imm
            self.dst=dst




    def get_inst(line,inst_num) :
        inst_opcode=line.split(' ', 1)[0]

        # here I am trying to do a case switch statement on the inst_opcode
        # for example if the opcode is "ADD" I would like to call a function to handle 
        # this line to fill the instructionsList which means to do something like this
        # instructionsList.append(Sim_cmd(inst_opcode,0,0,0,0))



    def sim_mem_reset(memFileName):
        with open(memFileName, 'r+') as fileName:
            for line in fileName:
                if line[0] == '#' or len(line.strip()) == 0:
                    continue

                inst = 0
                while len(line.strip()) != 0 and line[0] != '#' and line[0] != 'D':
                    get_inst(line, inst)
                    inst += 1

                # here the data memory begin
                if line[0] == 'D' and line[1] == '@':
                #some code

0 个答案:

没有答案