runtimeerror:最大递归深度超过python

时间:2016-11-04 14:38:47

标签: python recursion

我一直收到此错误“RuntimeError:调用Python对象时超出了最大递归深度”当我尝试运行600个测试的智能卡测试工具的主机程序时,我在第300次测试后得到此错误,我试过“sys .setrecursionlimit(10000)“并解决了这个问题,但我知道这不是解决此错误的最佳方法,如何更改我的代码以便我不会遇到此错误:

def SndRcv(self,request):
    print ">> ", request
    device_api.send(request)
    resp = device_api.receive()
    print "<< ", resp
    self.processResponse(resp)

def processResponse(self, K400Message):
    global mWaitingCardRemoval
    ciMsg = card_interface_response
    ciMsgType = card_interface_response.ci_msg

    if ciMsgType is None:
        print 'weird, malformed protobuf response'
        return
    whichMsg = ciMsgType.WhichOneof('msg')
    print 'msg = ' + str(whichMsg)
    if whichMsg is 'collision':
        self.StartSession()
    elif whichMsg is 'card_removed':
        if ciMsgType.issuer== ci.CARD_INTERFACE_MASK_CxLESS:                
            mWaitingCardRemoval &= ~(ciMsgType.issuer)
            if EndofSession is False:
                self.parseMessage()
            if mWaitingCardRemoval !=0:
                self.parseMessage()
            self.StartSession()
    elif whichMsg is 'waiting_removal':
        if EndofSession is False:
            self.parseMessage()
        else:
            mWaitingCardRemoval |= ciMsgType.issuer
    elif whichMsg is 'card_detected':
        mode = ciMsgType.issuer
        reqMsg = pm.get_Deactivate((ci.CARD_INTERFACE_MASK_ANY)& ~(ciMsgType.issuer))
        self.SendOnly(reqMsg)
        acceptMsg = pm.get_Activate(mode)
        self.SndRcv(acceptMsg)
    elif whichMsg is 'card_ready':
        self.StartLoop(ciMsgType.issuer)
    elif whichMsg is 'rapdu':
        self.processCardAPDUResponse(ciMsgType.issuer, ciMsg.data.encode('hex'))
    elif whichMsg is 'card_not_responding':
        if ciMsgType.issuer == ci.CARD_INTERFACE_MASK_CONTACT:
            self.EndCardSession(ciMsgType.issuer,True)
        else:
            self.EndCardSession(ciMsgType.issuer, False)
    elif whichMsg is 'resp_special':
        if ciMsg.data.encode('hex') > 0:
            logging.info(ciMsg.data.encode('hex'))
        else:
            logging.info("")

1 个答案:

答案 0 :(得分:0)

您使用递归来编写一个固有的迭代过程。你实际上并没有将一个大问题减少到一个较小的问题;你正在逐步完成一系列的输入。处理完输入并报告响应后,您就已完成。没有理由在调用堆栈上保留它的上下文。当你完成最后的测试并通过你的千多次调用返回时,你不会对结果或函数状态做任何事情来返回主程序。

将此重写为简单的迭代。你是怎么开始的?你如何从一个测试进展到另一个测试?你怎么知道什么时候完成的?例如,您的最外层循环很可能取决于简单的

# Get first response
while ciMsgType is not None:
    # Process this response
    # Get next response

这会让你感动吗?