2017-06-21 66 views
1

我有遞歸查看json層次結構以查找可能嵌套在任意數量的流控制塊中的操作的代碼。以下代碼完成了大部分工作。然而,當它碰到一個它不知道如何處理的密鑰並因此錯過重要數據時,似乎它一直跳出遞歸堆棧。我希望它在當前的遞歸級別繼續,我該怎麼做?Python中的遞歸和異常,如何在不丟失遞歸堆棧的情況下捕獲異常

調試打印的道歉。如果有人想看看發生此問題的示例調試輸出,請在評論中提問,然後我將其添加進去。

def getActionList(dict, parentKey, clarityOffset): 
    actions = [] 
    print(clarityOffset + str(len(dict.items())) + ' values in dict') 
    i = 0 
    for key, val in dict.items(): 
     print(clarityOffset + 'considering ' + str(i) +' -ith Key: ' + key) 
     #only go down the recursion tree for 'action container' keys. 
     if any(key.find(k) != -1 for k in kRelevantKeys): 
      print(clarityOffset + 'Key is a flow key, hopping down the tree') 
      try: 
       actions = actions + getActionList(val, key, clarityOffset + ' ') 
      except: 
       continue 
     #Some If's and foreaches are named specific things, check type here for those 
     elif any(val['type'].find(f) != -1 for f in kFlowTypes): 
      print(clarityOffset + 'Key has a flow type, hopping down the tree') 
      try: 
       actions = actions + getActionList(val, key, clarityOffset + ' ') 
      except: 
       continue 
     elif parentKey == 'actions' or parentKey == '': 
      print(clarityOffset + 'Is an action, key is ' + key) 
      actions.append((key, val)) 
     i += 1 

    print(clarityOffset + 'All actions are....') 
    for action in actions: 
     print(clarityOffset + action[0]) 
    return actions 
+0

除了' :continue'是處理你不知道如何處理的密鑰的一種非常糟糕的方式。它可能會隱藏你看不到的各種錯誤,因爲你只是在每個異常情況下都繼續。 – user2357112

回答

0

這並不是真正到了問題的核心被問過,但我能得到我想要通過改變代碼以下功能...

def getActionList(jsonDict, parentKey, clarityOffset): 
    actions = [] 

    for key, val in jsonDict.items(): 
     if not isinstance(val, dict): 
      continue 

     #only go down the recursion tree for 'action container' keys. 
     if any(key.find(k) != -1 for k in kRelevantKeys): 
      actions = actions + getActionList(val, key, clarityOffset + ' ') 
     #Some If's and foreaches are named specific things, check type here for those 
     elif 'type' in val and any(val['type'].find(f) != -1 for f in kFlowTypes): 
      actions = actions + getActionList(val, key, clarityOffset + ' ') 
     elif parentKey == 'actions' or parentKey == '': 
      actions.append((key, val)) 

    return actions