Python 程序因"maximum recursion depth exceeded while calling a python object"而出错



我目前正在开发一个python程序,该程序运行得很好,只是遇到了"递归深度"问题,我不知道如何重新编写程序以避免这种情况。

我的程序基本上就是这样的:

def foo()
    x = 0 # 
    while x != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)
     bar = ser.readline() # input from serial source
     if len(bar) != 10:
         foo()
     ''' it continues checking "bar" using some more if statement. Finally when the
         logic is satisfied the program outputs something but still restarts foo() as
         I need the program to run endlessly but I am not sure how to fix the recursive
         nature of the program'''
      if bar = 1234567890:
          print "yay you win"
          foo()
#start
foo()

最终,我的程序按原样运行,但最终会因递归限制错误而崩溃,这并不理想,因为我需要这个程序无休止地运行,但作为一个编程新手,我不确定如何修复它。我确实尝试过将程序拆分为两个或三个独立的函数,而不仅仅是一个,但它仍然存在递归问题。

感谢您的意见。如果有人需要更多的代码,我可以发布它,但我认为小部分应该足以看到我要去的地方。如有任何帮助,我们将不胜感激。

我会尝试这样做,因为它会重复调用相同递归级别的函数:

def foo()
    x = 0 # 
    while arming != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)
     bar = ser.readline() # input from serial source
     if len(bar) != 10:
     ''' it continues checking "bar" using some more if statement. Finally when the
         logic is satisfied the program outputs something but still restarts foo() as
         I need the program to run endlessly but I am not sure how to fix the recursive
         nature of the program'''
      if bar = 1234567890:
          print "yay you win"
#start
while 1:
    foo()

在foo内部只需使用一个循环,例如:

while True:
    x = 0 # 
    while arming != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)
     bar = ser.readline() # input from serial source
     if len(bar) != 10:
         # do whatever you want but don't call foo

您不需要递归地调用foo,程序就可以继续运行。特鲁会处理好的。

最新更新