2013-02-11 16 views
1

我需要打開串口設備的端口,但是如果它沒有打開或者有異常,它必須不斷嘗試打開門,直到它打開。 Python 2.7.3一段時間後我得到這個錯誤:如何確保它實際上打開串口

"RuntimeError: maximum recursion depth exceeded while calling a Python object"

你能幫我嗎?

我的代碼:

def opendisplay(): 
    try: 
     lcd = serial.Serial(
     port='/dev/display', 
     baudrate=9600, 
     timeout=0, 
     parity=serial.PARITY_NONE, 
     stopbits=serial.STOPBITS_ONE, 
     bytesize=serial.EIGHTBITS 
     ) 
    except Exception, e: 
     print "Error! can't connect to display Lcd check USB-Serial \n" + str(e) 
     opendisplay() 
    return lcd 

dsp=opendisplay() 
+2

停止遞歸併開始循環。 – 2013-02-11 09:03:16

+0

當它失敗時再次調用代碼。只是不要這樣做,或者至少等一段時間(例如一分鐘)再試一次。 – 2013-02-11 09:06:23

回答

0

正如馬丁/暗影說,循環,而不是遞歸:

def opendisplay(): 
    while True: 
     try: 
      # Try to connect 
      lcd = serial.Serial(...) 
      return lcd 
     except Exception as e: 
      # Connection failed 
      print "Error! etc" 
      time.sleep(1) 

如果你只想繼續努力一分鐘,你可以使用for _ in range(60)代替

+0

感謝所有!你的解決方案非常好! – user2060688 2013-02-11 10:16:40